Getting an undefined response to a jQuery AJAX form post

$(document).ready(function() { $('#pricingEngine').change(function() { var query = $("#pricingEngine").serialize(); $('#price').fadeOut(500).addClass('ajax-loading'); $.ajax({ type: "POST", url: "index.php/welcome/PricingEngine", data: query, dataType: 'json', success: function(data) { $('#price').removeClass('ajax-loading').html('$' + data.F_PRICE).fadeIn(500); $('#sku').attr('value') = (data.businesscards_id); } }); return false; }); }); 

You need to set #sku as the value of the hidden form field (not sure if I am doing this correctly in the jQuery code above.

 <input type="hidden" name="sku" id="sku" value="*/PUT VAR VALUE HERE/*" /> 

You also need to pass F_PRICE to the #price div .

The console in Chrome shows the JSON response as:

 [ { "businesscards_id":"12", "X_SIZE":"1.75x3", "X_PAPER":"14ptGlossCoatedCoverwithUV(C2S)", "X_COLOR":"1002", "X_QTY":"250", "O_RC":"NO", "F_PRICE":"12490", "UPS_GROUND":"12000", "UPS_TWODAY":"24000", "UPS_OVERNIGHT":"36000" } ] 

But I only get 'undefined' in the price field. What is the reason?

+2
source share
2 answers

The structure returned as JSON is an array [] containing one element, which is the {} object that you are targeting. Access through its array index [0]

 // Access the array-wrapped object via its [0] index: $('#price').removeClass('ajax-loading').html('$' + data[0].F_PRICE).fadeIn(500); // Likewise here, and set the value with .val() $('#sku').val(data[0].businesscards_id); 

You can also .shift() remove the first element from the array and use it as is:

 // Pull the first element off the array, into the same variable // WARNING: Use a different variable if the array has multiple elements you need to loop over later. // You *don't* want to do it this way if the array contains multiple objects. data = data.shift(); $('#price').removeClass('ajax-loading').html('$' + data.F_PRICE).fadeIn(500); $('#sku').val(data.businesscards_id); 
+2
source

This is the right way (best)

 $('#sku').val(data.businesscards_id); 

If you insist on using attr, this should work

 $('#sku').attr('value', data.businesscards_id); 
0
source

All Articles