Shahriar N Khondokar
Shahriar N Khondokar

Reputation: 578

Weird behaviours in JQuery.ajax

The code below is part of an autocomplete input created using JQuery UI. But my question here is related to the JQuery-AJAX part only.

change: function(event, ui){
$.ajax({
type: "POST",
url: "includes/c_t_v_choices.php",
data: { filter: ui.item.value },
//dataType: "JSON",
}).done(function( msg ) {
    c_t_v_choices = msg;
    alert( "Data Saved: " + c_t_v_choices );
    $("#c_t_v").autocomplete("option", "source", c_t_v_choices);
});

The last line in the c_t_v.php file is:

echo json_encode($return_arr);

The way the code is currently, I see valid data in the alert, sent by the php file. An example is shown below:

Data Saved: [{"label", "value"}, {"label", "value"}...]

However, when I enable the line:

dataType: "JSON",

I see something like:

Data Saved: [object: Object], [object: Object]

Why this weird behavior?

On a side note, any idea why $("#c_t_v").autocomplete is accepting the source i am providing in the code below (which is part of the code above):

$("#c_t_v").autocomplete("option", "source", c_t_v_choices);

Upvotes: 0

Views: 43

Answers (1)

nanobar
nanobar

Reputation: 66355

Data Saved: [{"label", "value"}, {"label", "value"}...]

Do a log on this data in this instance like this console.log(typeof your_data_var) -- is it a string?

When you specify JSON jQuery converts the returned json STRING into an object array so that you can easily access the json hierarchy using the dot notation, e.g. Parent.child.something.

It is the normal way jQuery handles JSON responses as it is more elegant and faster to lookup than using an array :)

PS In case you aren't I recommend you use console.log, and console.dir can be handy for arrays/objects and inspect with Firebug to get a better understanding of the object and what it contains.

Upvotes: 1

Related Questions