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


Need Your Help

how to get the value of the hidden fields in here after the radio button is clicked

javascript jquery

Am trying to get the value of the hidden input fields on every click of a radio button. I have just posted a single div. I have a multiple div with same structure. I have successfully obtained the ...

JQuery Mobile Show and Hide loading message on page load

jquery-mobile

I am trying to get the loading message to appear when the pages load and the is my attempt:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.