简体   繁体   中英

How to query database from JavaScript using Ajax and PHP correctly?

I'm trying to do a simple exercise querying a database from JS using XMLHTTPrequest Object and POST method. Basically I pass a string to PHP server, it recieves it, queries DB and returns an XML from where I read the information with JS, but something is not working: the callback function that should be executed after request is ready.

Here's the JS code:

function leerDNI(dni){

var params="dni="+dni;

downloadUrl(params,"genxml.php", function(data) {
    var xml = parseXml(data);//THIS IS NOT BEING EXECUTED
    var dnis = xml.documentElement.getElementsByTagName("dni");//THIS IS NOT BEING EXECUTED
    for (var i = 0; i < dnis.length; i++) {//THIS IS NOT BEING EXECUTED
    var name = dnis[i].getAttribute("name");
    alert(name); //THIS IS NOT BEING EXECUTED
    document.getElementById("name").value=name; //THIS IS NOT BEING EXECUTED
 }
 });

 }

function downloadUrl(params,url, callback) {
 var request = window.ActiveXObject ?
 new ActiveXObject('Microsoft.XMLHTTP') :
 new XMLHttpRequest; 

request.onreadystatechange = function() {
 if (request.readyState == 4) {
 request.onreadystatechange = doNothing;
 callback(request.responseText, request.status);

 }
 };
 request.open("POST", url, true);
 request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");//creación de headers
 request.send(params);//enviamos la petición POST
}

function parseXml(str) {
 if (window.ActiveXObject) {
 var doc = new ActiveXObject('Microsoft.XMLDOM');
 doc.loadXML(str);
 return doc;
 } else if (window.DOMParser) {
 return (new DOMParser).parseFromString(str, 'text/xml');
 }
}

function doNothing() {}  

The XML is being generated correctly. Anyone can light me up with what's wrong in my code? Thank you very much!

May not be the reason but in downloadUrl(param, url, callback) function, the callback call is:

callback(request.responseText, request.status);

So 2 parameters.

However when you call the function:

downloadUrl(params,"genxml.php", function(data){...} )

The callback you gave has only 1 parameter. Check that.

This one uses post and is ready to go and change to your needs!

html file (file name does not matter)

<html>
<head>
<script type="text/javascript">

var request = false;
try { 
  request = new XMLHttpRequest(); 
} catch (trymicrosoft) {                         
  try { 
    request = new ActiveXObject("Msxml2.XMLHTTP"); 
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {                  
      request = false;       
    }
  }
}

if (!request) 
  alert("Error initializing XMLHttpRequest!"); 
</script>

<script type="text/javascript">

 var fileOption;


   function runPhp(Args) 
   {  
        var url = "script.php"; 
        fileOption = Args;
        var params = "Args=" +Args+"";
        request.open("POST", url, true);  

        //Some http headers must be set along with any POST request.
        request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
        request.setRequestHeader("Content-length", params.length);
        request.setRequestHeader("Connection", "close");

        request.onreadystatechange = updatePage;
        request.send(params);

   }////////////////////

   function getXml( ) 
   { 
        var url = 'temp.xml'; 
        var params = null; 
        request.open("POST", url, true);     
        request.setRequestHeader("Connection", "close");    
        request.onreadystatechange = displayFile;
        request.send(params); 
   }////////////////////

   //You're looking for a status code of 200 which simply means okay.
   function updatePage() {
     if (request.readyState == 4) {
       if (request.status == 200) 
       {   

            if(fileOption==1)  
                {fileName=request.responseText;  return;}
            document.getElementById('divResults').innerHTML=request.responseText;
            document.getElementById('textareaResults').innerHTML=request.responseText;   
       } 
       else{
         //alert("status is " + request.status);
         }
     }
   }

      function displayFile() {
     if (request.readyState == 4) {
       if (request.status == 200) 
       {   
            document.getElementById('textareaResults').innerHTML=request.responseText;
            document.getElementById('divResults').innerHTML='File loaded in text area above.';
       } 
       else{
         //alert("status is " + request.status);
         }
     }
   }

</script>
</head>
<body >


<span style="background-color:blue;color:yellow;"  
onClick="runPhp('GetFromMysql')"/>
Click this to get data from MySql.<br> 
</span><br><br>

<span style="background-color:blue;color:yellow;"  
onClick="runPhp('MysqlToFile')"/>
Click this to get data from MySql and store them in a file instead of displaying.<br> <br> <br> 
</span>

<span style="background-color:blue;color:yellow;"  
onClick="getXml()"/>
Click to read the xml file.<br> 
</span>

<textarea rows="10" cols="88"  id="textareaResults">
</textarea>
 <br><br>
<pre><div    id="divResults"></div></pre>
<br><br>




</body>
</html>

and this is script.php

<?PHP

    $xml_output = routine();
    if($_POST['Args']==='GetFromMysql')
        echo $xml_output .= "</records>"; 

    elseif($_POST['Args']==='MysqlToFile')
    {
        $fileName =  'temp.xml';
        $fp = fopen($fileName, 'w');
        fwrite($fp,  $xml_output); 
        fclose($fp); 
        echo "temp.xml";//return the file name
    }

    function routine()
    {
        mysql_connect('localhost', 'root',''); 
        mysql_select_db("mysql");
        $query="select * from help_category;"; 
        $resultID = mysql_query($query ) or die("Data not found."); 
        $xml_output = "<?xml version=\"1.0\"?>\n"; 
        $xml_output .= "<records>\n"; 

        for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++)
        { 
            $row = mysql_fetch_assoc($resultID); 
            $xml_output .= "\t<record>\n"; 
            $xml_output .= "\t\t<help_category_id>" . $row['help_category_id'] . "</help_category_id>\n";  
            $xml_output .= "\t\t<name>" . $row['name'] . "</name>\n";  
            $xml_output .= "\t\t<parent_category_id>" . $row['parent_category_id'] . "</parent_category_id>\n"; 
            $xml_output .= "\t</record>\n"; 
        }
        return $xml_output;
    }

?> 

I've solved the issue, it was this line:

var dnis = xml.documentElement.getElementsByTagName("dni");

That was supossed to be substituted for:

var dnis = xml.documentElement.getElementsByTagName("persona");

Because I was generating persona nodes.

Thanks for your answers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM