deviloper
deviloper

Reputation: 7240

how do I access the array string returned by jquery ajax function

I have the following code that searches the characters typed in the search box with the onkeyup event.

$("#keywords").keyup(function () {
    var kw = $("#keywords").val();
    if (kw != '') {
        var url = "<?php echo base_url().'index.php/simpromotions/livesearch/';?>" + kw;
        $.ajax({
            type: "POST",
            url: url,
            datatype: "json",
            success: function (data) {
                **alert(data);**
                $.each(data,function(ptitle, category){
                    $("#results").html('<label>'+ptitle+': '+category+'</label><br>');
                }
            }
        });
    }else{
        $("#results").html("");
        return false;
    }
});

In the above code when I alert the data it displayes the following array string.

{"pcode":"22","category":"NightTalk","ptitle":"HourlyNightTalk"}

I cant seem to access the pcode, category and ptitle as I have done in the next line. (after alert) Please help me how I can access the three!

Upvotes: 1

Views: 7772

Answers (3)

Felix Kling
Felix Kling

Reputation: 816422

That means data is a string, and the response is a simple JSON encoded object, not an array.

You have to parse the response first. You can let jQuery do this for you by fixing the dataType property:

dataType: "json" // dataType, not datatype

Inside the callback, data will be a JavaScript object now and you just directly access its properties (learn more about objects in MDN - Working with Objects):

success: function (data) {
    $("#results").html('<label>'+data.ptitle+': '+data.category+'</label><br>');
}

It doesn't make sense to use $.each here. Have a look at the documentation to learn what it does and how it works.


You mentioned that sometimes you actually get an array back. In that case you probably want to use $.each. To make your code simpler, I recommend to always return an array from the server:

var $results = $('#results');
$results.empty();
$.each(data, function(i, obj){ 
    $results.append('<label>'+obj.ptitle+' is in '+obj.category+'</label><br>'); 
});

Upvotes: 2

mdup
mdup

Reputation: 8529

Your problem is that you misunderstood jQuery's each() function. The prototype of the callback function is function(index, value) where index will be "pcode", "category", "ptitle" and value will be "22", "NightTalk", "HourlyNightTalk" respectively.

Upvotes: 0

BeNdErR
BeNdErR

Reputation: 17927

You have to enter the property. Try this:

alert(data.ptitle)

or, in your case

$("#results").html('<label>'+data.ptitle+': '+data.category+'</label><br>');

example http://jsfiddle.net/CcJEX/

Upvotes: 0

Related Questions