奇怪的jQuery AJAX问题

I'm using jQuery AJAX to grab some data from a PHP page and using a loading GIF image in the placeholder to let the user know the results are on the way.

$(".project").change(function(){
            $(".custName").html("<img src='/admin/images/ajax-loader.gif' />");
            $(".projectDesc").html("<img src='/admin/images/ajax-loader.gif' />");
            var project_num=$(this).val();
            var dataString = 'project='+ project_num;

                $.ajax
                    ({
                        type: "POST",
                        url: "customerfilter.php",
                        dataType: "json",
                        data: dataString,
                        cache: false,
                        success: function(data)
                        {
                            $(".custName").html(data.message1);
                            $(".projectDesc").html(data.message2);
                        }
                    });


        });

When i click the trigger and open up Firebug console i can see the POST go and come back and the data is correct. However the loading gif never goes away and never gets replaced by the correct data - no idea why!?

This is a screenshot of Firebug and the RESPONSE window:

alt text

Relative PHP:

while ($row = mysql_fetch_array($result)) {
                echo json_encode(array(
                    "message1" => $row['cust_name'],
                    "message2" => $row['description'],
                ));

$result is a mysql_query

I've run into similar problems when setting the type to be JSON. If the PHP doesn't return 100% correct JSON, then jQuery will not run the success function.

So try this:

  1. Put a console.log("success was called") statement inside of the success method so that you can see when it's called.

  2. Ensure that your PHP code is creating proper JSON by using the json_encode function.

  3. Post any new information you have so we can continue to help you debug :-)

That response is not a valid json. Try this:


$output = Array();
while ($row = mysql_fetch_array($result)) {
                $output[] = Array(
                    "message1" => $row['cust_name'],
                    "message2" => $row['description'],
                );
}
echo json_encode($output);

EDIT: additionally, you have to change your 'success' javascript callback too:


success: function(data) {
  $(".custName, .projectDesc").empty();
  for(var x in data) {
     $(".custName").append(data[x].message1);
     $(".projectDesc").append(data[x].message2);
  }
}