sea_1987
sea_1987

Reputation: 2944

cant access JSON

I have this ajax request,

$.ajax({
    url    : '<?php echo current_url(); ?>',
    data       : "txtKeywords="+$("#txtKeywords").val()+"&search=Search For Item",
    type       : 'POST',
    dataType   : 'JSON',
    success : function(html)
    {       
        console.log(html);          
    }
});
return false;

I get the following in my console,

[{"productId":"5","productTitle":"Small Brasserie Dining Table","productPath":"small-brasserie-dining-table\/","productRangeId":"6","productSecondaryRangeId":"0","productTypeId":"2","productRefNo":"0080","productShortDesc":"","productBestSeller":"0","productFeatured":"0","productIsSet":"0","productPrice":"275","productSavingType":"none","productSavingPrice":"0","productSavingMessage":"","productDimWidth":"90","productDimHeight":"74","productDimDepth":"90","productTechnical":"Powder coated aluminium frame with welded joints.","productTemplateId":"5","productMetadataTitle":"","productMetadataKeywords":"","productMetadataDescription":"","productBandingColour":"grey","productActualPrice":"275","rangeTitle":"Dining","parentRangeTitle":"Aegean","fullRangePath":"aegean\/dining\/","fullProductPath":"aegean\/dining\/small-brasserie-dining-table\/","hasImage":"0"}]

But when I do something like,

alert(html.productTitle)

all I get is undefined?

What am I doing wrong?j

Upvotes: 0

Views: 102

Answers (4)

Edgar
Edgar

Reputation: 71

try doing something like this:

alert(html.d); // this will show the result of your ajax call

i don't know what the reason is to use the property 'd' but if you can take a look at your result, use a debug tool to see what data is getting back your ajax call.

if you want convert your JSON string to and object, you can do with the following code:

var respuesta = jQuery.parseJSON(html.d);

Upvotes: 0

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Try using Jquery's JSON ajax function instead of the $.ajax it will parse the JSON for you.

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

Upvotes: 0

sdleihssirhc
sdleihssirhc

Reputation: 42496

Is it because your html variable is an array? Wouldn't you have to do...

alert(html[0].productTitle);

Upvotes: 6

shaneburgess
shaneburgess

Reputation: 15872

Try html[0].productTitle, I have run into this problem a few times.

Upvotes: 2

Related Questions