Niall Paterson
Niall Paterson

Reputation: 3580

Returned JSON is seemingly mixed up when using jQuery Ajax

I've a php script that has the following line:

echo json_encode(array('success'=>'true','userid'=>$userid, 'data' => $array));

It returns the following:

{
"success": "true",
"userid": "1",
"data": [
    {
        "id": "1",
        "name": "Trigger",
        "image": "",
        "subtitle": "",
        "description": "",
        "range1": null,
        "range2": null,
        "range3": null
    },
    {
        "id": "2",
        "name": "DWS",
        "image": "",
        "subtitle": "",
        "description": "",
        "range1": null,
        "range2": null,
        "range3": null
    }
]

}

But when I call a jQuery ajax as below:

$.ajax({
    type: 'POST',
    url: 'url',
    crossDomain: true,
    data: {name: name},
    success: function(success, userid, data) {

      if (success = true) {
         document.write(userid);
         document.write(success);
       }
   }
});

The userid is 'success'. The actual success one works, its true.

Is this malformed data being returned? Or is it simply my code?

Thanks in advance, Niall

Upvotes: 0

Views: 244

Answers (2)

Muthu Kumaran
Muthu Kumaran

Reputation: 17920

You can't add your own arguments in Success. Change your code like this,

success: function(response) {

      if (response.success == true) { 
         document.write(response.userid);
         document.write(response.success);
       }
   }

According to jQuery Docs for success(),

success(data, textStatus, jqXHR)

A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn.

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

Upvotes: 1

Quentin
Quentin

Reputation: 944083

The arguments the success callback takes are defined in the documentation:

success(data, textStatus, jqXHR)

The response is not split up before being passed as arguments to it. You have to extract the values from the first argument.

You also need to add header('Content-Type: application/json') to your PHP so that jQuery will parse the response as JSON instead of as HTML when populating the first argument.

You can then test data.success and access data.userid (as well as data.data which will be the array assigned to the data property in the returned data… you might want to rename it to avoid confusion).

Note that when you test it you need to use === (or ==), not the * assignment* operator you are using at present. Also note that your JSON response is returning the string "true" and not the boolean true.

Upvotes: 3

Related Questions