Getting Response From Jquery JSON

I'm having trouble getting a response from my php jquery / json / ajax. I keep combining all these different tutorials together but I still can't seem to pull it all together since no one tutorial follow what I'm trying to do.

Right now I'm trying to pass two arrays (since there's no easy way to pass associative arrays) to my jquery ajax function and just alert it out. 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'm really calling is my javascript file for debugging purposes. I know i'm returning an object but I'm getting an error with null values in my names 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 to be just ending here Uncaught TypeError: Cannot read property '0' of undefined so my sub0 is killing me.

Answers


You could prob use the $.getJSON facade that jQuery provides, this will setup all the required ajax params for a standard JSON request:

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

However i think the route of the issue is that 1) your server may not be returning the correct response codes and/or the correct headers (ie: JSON data) - however the above method at least for the latter should force this conclusion.

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


It looks like the problem is that you're using the complete callback instead of the 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)

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. This is an Ajax Event.

complete(jqXHR, textStatus)

A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.


jQuery wants to know what kind of data to expect as a response, otherwise it wont know how to parse it.

So, as has been said before here, you tell jQuery using the dataType = 'json' attribute.

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

On top of this it is a good idea to have PHP present its content as json rather than html. You use the 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);

You should pass all parameters for ajax() function in single object. So, there should be "dataType" option. Also, if you set data type explicitly, jQuery will parse JSON data for you. Complete callback will receive parsed JavaScript object as parameter.

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

Need Your Help

need specific style of pagination using CI pagination technique

php css codeigniter pagination

i have done pagination using CodeIgnitier pagination library successfully. problem is here i want pagination styling in different format other than what CI provides in cusotom style

System.AccessViolationException error when accessing COM DLL written in Visual FoxPro

c# com foxpro visual-foxpro

I have a C# WinForms .NET 3.5 application that I need to call a COM DLL written in Visual FoxPro 7. I have added the COM object to the C# project fine, and can