user1849908
user1849908

Reputation:

jQuery success function not executing

the first success function works, the second doesnt... it works if I change datatype to text... but if i change datatype to text am not able to iterate through the array .. for example i require data[0].. which works with json....but with json success function is not working ...

var turl = "getForum.php";
var turl = "getForum.php";
var wurl = "getDiscussions.php";
$.ajax({
    url:turl,
    type:"POST",
    dataType:"json",
    success:function(data){
        forumid = data[0]; // this works ...
        dataString = 'forumid='+ forumid;
        $.ajax({
            url:wurl,
            type:"POST",
            dataType:"json",
            data:dataString,
            success:function(data){
                alert(data); // this works if I change datatype to text... but if i type datatype to   text am not able to iterate through the array .. for example i require data[0].. which works with json....but with json success function is not working ... 
            }
        });
    }
});

php file return json object

$query1 = " select * from discussforum where forumId= '$forumid'; ";
$result1 = mysql_query($query1); 

 while($info1 = mysql_fetch_array( $result1 )){
 echo json_encode($info1);
 }

Upvotes: 2

Views: 140

Answers (2)

alexfernandez
alexfernandez

Reputation: 1978

I think the solution is delineated in the comments, but here it goes in a bit more detail. First take a look at the fine documentation for jQuery.ajax(). You need to add an error callback to all your Ajax calls. with the following signature:

error(jqXHR, textStatus, errorThrown)

You can just add a parameter to .ajax() like this:

error: function(jqXHR, textStatus, errorThrown) {
  console.error(textStatus);
},

This way you will see in the console every error that happens during the Ajax call and also during the processing of the message. You can define a generic ajaxError callback in some common .js file and use it everywhere.

In this case you are explaining very well the cause of the error: what getDiscussions.phpis returning is not a JSON, and thus the jQuery parser cannot understand it when you set dataType:"json": it would call the error callback if there was one. It works however when the dataType is set to text. So the POST request is probably failing.

To see what it is sending you can just extract it in the error callback, like this:

error: function(jqXHR, textStatus, errorThrown) {
  console.error('Error in response: ' + jqXHR.responseText
},

so you can diagnose the problem in the server.

Upvotes: 0

Ene
Ene

Reputation: 464

Are you sure about your PHP is returning only one JSON object? If not:

$ret = array();
while($info1 = mysql_fetch_array( $result1 )){
    $ret[] = $info1;
}
print json_encode($ret);

Upvotes: 2

Related Questions