Getting response from JQuery JSON

I am having trouble getting the response from my php jquery / json / ajax. I keep combining all these different tutorials together, but I still can't seem to show that it all comes together because no tutorial follows what I'm trying to do.

Right now I am trying to pass two arrays (since there is no easy way to pass associative arrays) to my jquery ajax function and just warn about it. Here's my code:

PHP

$names = array('john doe', 'jane doe');
$ids = array('123', '223');

$data['names'] = $names;
$data['ids'] = $ids;

echo json_encode($data);

      

Jquery

function getList(){
    $.ajax({  
        type: "GET", 
        url: 'test.php', 
        data: "",  
        complete: function(data){ 
            var test = jQuery.parseJSON(data);
            alert(test.names[0]);
            alert("here");
        }
    },
        "json");
}
getList();

      

In my html file, all I actually call is my javascript file for debugging purposes. I know I am returning an object, but I am getting an error with null values ​​in the name section and I'm not sure why. What am I missing?

My PHP file returns

{"names":["john doe","jane doe"],"ids":["123","223"]}

      

It seems like it's just the end Uncaught TypeError: Cannot read property '0' of undefined

so my sub0 is killing me.

+3


source to share


4 answers


You can try using the facade $.getJSON

that jQuery provides, this will set all the required ajax parameters for a standard JSON request:

$.getJSON('test.php', function(response) {
    alert(response.names[0]);   // john doe
}); 

      



However, I believe the problem is that 1) your server may not be returning correct response codes and / or correct headers (i.e. JSON data) - however, the above method, at least for the latter, should force this conclusion.

See: http://api.jquery.com/jQuery.getJSON

+5


source


It looks like the problem is that you are using a full callback instead of a success callback:

function getList(){
    $.ajax({  
        type: "GET", 
        url: 'test.php', 
        data: "",  
        success: function(data) { /* success callback */
            var test = jQuery.parseJSON(data);
            alert(test.names[0]);
            alert("here");
        }
    },
    "json");
}
getList();

      



From jQuery AJAX Docs:

success (data, textStatus, jqXHR)

The function to be called when the request succeeds. The function takes three arguments: data returned from the server, formatted according to the dataType parameter; a string describing the status; and a jqXHR object (in jQuery 1.4.x, XMLHttpRequest). As of jQuery 1.5, the success parameter can take a bunch of functions. Each function will be called in turn. This is an Ajax event.

complete (jqXHR, textStatus)

A function to be called when the request completes (after successful execution and error callbacks). The function takes two arguments: a jqXHR object (in jQuery 1.4.x, XMLHTTPRequest) and a string that classifies the status of the request (success, unmodified, error, timeout, abort, or parsererror). Since jQuery 1.5, full customization can take many functions. Each function will be called in turn. This is an Ajax event.

+3


source


jQuery wants to know what data to expect as a response, otherwise it doesn't know how to parse it.

So, as said above, you are specifying jQuery using an attribute dataType = 'json'

.

function getList() {
    $.ajax({  
        type: "GET", 
        url: 'test.php', 
        data: "",  
        dataType: "json",
        success: function(data) { 
            console.log(data);
        }
    });
}

      

Also, it is a good idea for PHP to render its content as json and not html. You use a header for this by setting header('Content-type: application/json');

before any output in your PHP script. So:

$names = array('john doe', 'jane doe');
$ids = array('123', '223');

$data['names'] = $names;
$data['ids'] = $ids;

header('Content-type: application/json');

echo json_encode($data);

      

+2


source


You have to pass all parameters to the ajax () function in one object. So there must be a "dataType" option. Additionally, if you set the data type explicitly, jQuery will parse the JSON data for you. The full callback will receive a parsed JavaScript object as a parameter.

function getList() {
    $.ajax({  
        type: "GET", 
        url: 'test.php', 
        data: "",  
        dataType: "json",
        success: function(test) { 
            alert(test.names[0]);
            alert("here");
        }
    });
}

      

+1


source







All Articles