I'm trying to use AJAX to query my database (using this guide: https://www.w3schools.com/php/php_ajax_database.asp). I plan to write out the JavaScript and html on a Basic page, then make an AJAX call to a php file to process the selected html element values. However, I'm not very familiar with the Drupal 7 directory structure. Where do I put this php file? It seems like it would need to be in the same directory as a Basic page, but I haven't been able to find the proper path.

Edit1 - I spent some time learning Drupal form API and created some basic modules. There are several limitations (which I will not go into further detail in this post). I think it will be more practical to stick to my current form code (written in html/php/javascript). I need a way to make an AJAX call, probably without calling a Drupal module. The w3schools demonstration calls a ".php" file, which would be ideal. I haven't been able to reproduce the example on a basic Drupal page. I've been using the "/sites/all/libraries/php_file.php" file path. Here's my sample code:

Basic Page

<!DOCTYPE html>
function showUser(str) {
  if (str=="") {
  if (window.XMLHttpRequest) {
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  } else { // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  xmlhttp.onreadystatechange=function() {
    if (this.readyState==4 && this.status==200) {

<select name="countries" onchange="showUser(this.value)">
<option value="">Select a country:</option>
<option value="1">USA</option>
<option value="2">Canada</option>
<option value="3">China</option>
<option value="4">Viet Nam</option>
<div id="txtHint"><b>Country info will be listed here.</b></div>



<!DOCTYPE html>
table {
    width: 100%;
    border-collapse: collapse;

table, td, th {
    border: 1px solid black;
    padding: 5px;

th {text-align: left;}

$q = intval($_GET['q']);
echo $q;
  • Hello! You should probably not implement this like that. Read the Drupal 7 Ajax API. Instead of calling a PHP file, you should create a custom module and implement hook_menu to create your path, and then do your database querying inside the callback you define in hook_menu. Also, it's best to use drupal's built in query options, some of which are documented here. – sonfd Jun 1 '18 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.