ian
ian

Reputation: 12335

Retrieving array values in jquery

My code:

$.get('ajax/time_menus.php', {
    shift: $('#shifts').val()
  },
  function(data) {
    //load the array into a test element so we can see what is returned
    $("#test").html(data);

    //set the hour menu
    var startHour = data[0];
    alert(startHour);
    $('#from_hours').val(data[0]);
  });

Returns an array like this:["08","00","AM","11","00","AM"]

But for some reason the alert( startHour ); line will throw up an alert of: [

What am I doing wrong?

I am receiving this error with Firebug.

site.com/schedule/ajax/time_menus.php?shift=23 GET http://www.sharingizcaring.com/schedule/ajax/time_menus.php?shift=23

200 OK 296ms jquery-1.3.2.js (line 3633) uncaught exception: [Exception... "Could not convert JavaScript argument arg 0" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://www.sharingizcaring.com/schedule/js/jquery-1.3.2.js :: anonymous :: line 957" data: no]

Upvotes: 0

Views: 223

Answers (2)

Ionuț G. Stan
Ionuț G. Stan

Reputation: 179098

It happens because data is a string. You need to receive it as an array in order to obtain what you want. Use the fourth argument of $.get in order to specify the type, in your case JSON:

$.get('ajax/time_menus.php', { shift: $('#shifts').val() }, function(data) {
    ...
}, "json"); // <--here

// or shorter

$.getJSON('ajax/time_menus.php', { shift: $('#shifts').val() }, function(data) {
    ...
});

Upvotes: 1

Liviu
Liviu

Reputation:

try working with json by setting the type on the $.get to "json" (by default it returns a HTML/XML response)

Upvotes: 0

Related Questions