viviosoft Posted June 3, 2011 Share Posted June 3, 2011 Hello all, I have the following code that I thought I could retrieve json_encoded data but I'm just getting "undefined". Thanks for any help you can provide. The json_encoded string from the php array: [{"table":null,"id":"2","itemCode":"1003","itemDesc":"Item infor for 1003","itemWholesale":"1.99"}] I thought I could "grab" the name of each in the array and output the data accordingly. So on success of the ajax post (which does return data) I tried alert(itemData.itemCode); This is on line 10 in the below code snippet. Using this method returns "undefined" and NOT the data 1003 as I would expect. I even tried the jquery's .get() method and that also returned null?? $('#search_results tr').live('click', function() { var $itemrow = $(this).closest('tr'); var itemId = $itemrow[0].id; $.ajax({ type: "POST", url: "post-data/inv-get-item.php", data: "itemID="+itemId, success: function(itemData) { alert(itemData[0].itemCode); } }); }) Quote Link to comment https://forums.phpfreaks.com/topic/238306-ajax-postget-and-returned-json_encoded-php-array/ Share on other sites More sharing options...
salathe Posted June 3, 2011 Share Posted June 3, 2011 Be sure that your PHP scripts tells browsers that the response is JSON (e.g. header("Content-Type: application/json");). It's also a good idea to tell jQuery to expect a JSON response in your $.ajax() options (e.g. dataType: "json"). Quote Link to comment https://forums.phpfreaks.com/topic/238306-ajax-postget-and-returned-json_encoded-php-array/#findComment-1224622 Share on other sites More sharing options...
viviosoft Posted June 3, 2011 Author Share Posted June 3, 2011 Thank you salathe! That worked. Man I can't believe that the jQuery Library Documentation didn't even have anything on this. Even in their examples it doesn't state to have the dataType defined?? Anyway, thanks for the help and quick response! As for defining the meta Content-Type... would I just add another meta tag in the header? I guess I'm not sure where I should be adding the meta tag or how to go about adding it. That seems trivial right? haha! Quote Link to comment https://forums.phpfreaks.com/topic/238306-ajax-postget-and-returned-json_encoded-php-array/#findComment-1224627 Share on other sites More sharing options...
salathe Posted June 3, 2011 Share Posted June 3, 2011 For the content type, just send the header that I gave you (copy and paste!). No need for meta tags, as those are part of HTML and you're creating JSON. The jQuery docs are pretty awesome, but you do have to know what you're looking for sometimes. Quote Link to comment https://forums.phpfreaks.com/topic/238306-ajax-postget-and-returned-json_encoded-php-array/#findComment-1224738 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.