Jump to content

Ajax post/get and returned json_encoded php array


viviosoft

Recommended Posts

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);
              }
            });
        })
    

 

 

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").

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!

 

 

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.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.