سؤال

I am quite a noob to AJAX Requesting and PHP and I got a question: I am trying to do a GET request to a php file on my wamp server but it's responseText stays blank and when I check the status code when the readyState is 4, it's 0.

When I execute the php file in the browser it returns my expectation: An array with JSON Objects.

Does anyone know the answer?

Javascript code:

this.getCars = function(id) {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        xmlhttp=new XMLHttpRequest();
    }
    else {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    var that = this;
    xmlhttp.onreadystatechange=function()
    {

        if (xmlhttp.readyState==4)
        {
            alert(xmlhttp.status);
            //that.lastTableCars = JSON.parse(xmlhttp.responseText);

        }
    }
    xmlhttp.open("GET","http://localhost/getCars.php?q="+id,true);
    xmlhttp.send(null);
}

PHP:

<?php
$q=$_GET["q"];
$con = mysql_connect('127.0.0.1', 'root', 'root');
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}

mysql_select_db("autobay", $con);

$sql= "SELECT * FROM autoos WHERE id = '".$q."'";

$result = mysql_query($sql);
$info = [];
while( $row = mysql_fetch_assoc( $result)){
    $info[] = $row; 
}

echo json_encode($info);

mysql_free_result($result);
mysql_close();
هل كانت مفيدة؟

المحلول

For one, use jQuery to help troubleshoot. It's going to make your life so much easier. Even if you end up wanting to use raw xmlhttprequest, I'd suggest bringing jQuery in to rule out xmlhttprequest problems in your code, and more quickly hone in on the real issue.

Translation: I'm not comfortable with raw xmlhttprequest, so in order to help you let's switch to jQuery. You can go back when the issue is resolved! =)

this.getCars = function(id) {
   $.get("/getCars.php?q="+id, function(data) {
      alert("response from server: " + data);
   });
}

http://api.jquery.com/jQuery.get/

Also make sure you are using Chrome Dev Tools or Firebug to inspect the response from your server, it's possible that it's failing there.

Update:

Make sure your HTML page (that is making the ajax call) and the PHP script are running on the same domain (localhost). I noticed you were specifying the full http://localhost URL in your ajax call. Ajax does not work cross-domain (though there are workarounds, look at JSONP if you really need to do this cross-domain). Best bet is to get your HTML page loading from the same domain as the PHP script.

Update 2:

Actual issue was that the OP was loading the HTML from a folder on his computer (not via http://localhost) and trying to make an ajax call to http://localhost. The ajax call was failing since this is technically cross domain.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top