Getting undefined response from jQuery AJAX form post - php

$(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;
});
});
Need to set #sku as value of a hidden form field (not sure if i am doing that correctly in the above jQuery code.
<input type="hidden" name="sku" id="sku" value="*/PUT VAR VALUE HERE/*" />
Also need to pass the F_PRICE to the #price div.
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"
}
]
Yet I only get 'undefined' in the price box. What is the reason here?

The structure returned as JSON is an array [] containing one element which is the object {} you are targeting. Access it via 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 could also .shift() the first element off the array and use that as you have it:
// 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);

This the the proper way (best)
$('#sku').val(data.businesscards_id);
If you insist on using attr, this should work
$('#sku').attr('value', data.businesscards_id);

Related

Pass value to a textbox use AJAX / JSON

I have te following script and want to pass a value to a textbox using AJAX.
<script>
$(document).ready(function(){
$("#searchName").change(function(){
var name = $("#searchName").val();
$.ajax({
'url': 'ontwikkelpunten.php',
'method': 'post',
'data':
{
naam: $("#searchName").val()
},
'dataType': 'json'
}).done(function(data){
console.log(data);
$('#test').val(data.naam);
});
});
});
<input type="text" id="test" name="">
When I change searchName and check the console in Chrome I see the array, but its still not working.
Your JSON return is an array of objects (in your case, a single array element containing an object). So when you tried to assign with:
$('#test').val( data.naam );
// ^--- direct object item reference
This was not finding the right element to use because naam didn't exist in the base array. Instead you need to adjust that to first reference the array element, THEN the object element:
$('#test').val( data[0].naam );
// ^--- first array element

how to have access to 2d array elements using JSON.stringify?

I have posted a question about How to alert a php array in ajax success function in this post: How to alert a php array in ajax success function
I got the answer to use alert(JSON.stringify(result[0])); but this will give me access to the first row of the array while i need to have access to each element of each row. imagine that my array is like this now
[0]1>>>>2>>>>>3>>>>>5>>>>>6
[1]1>>>>2>>>>>3>>>>>5>>>>>6
[2]1>>>>2>>>>>3>>>>>5>>>>>6
[3]1>>>>2>>>>>3>>>>>5>>>>>6
[4]1>>>>2>>>>>3>>>>>5>>>>>6
[5]1>>>>2>>>>>3>>>>>5>>>>>6
alert(JSON.stringify(result[0])) will give me only [0]1>>>>2>>>>>3>>>>>5>>>>>6 but I want to alert 5 only, I have tried alert(JSON.stringify(result[0][3])) but no luck.
Could you tell me how to have access to 2d array elements using JSON.stringify? Or is there any other way than JSON.stringify(result[0]
Here is the ajax function :
$.ajax({
type: 'POST',
url: "profile/ajax/getorder.php",
data: {id:gotid},
dataType: 'json',
cache: false,
success: function(result) {
alert(JSON.stringify(result[0]))
},
});
here is the php
$ent = $_POST['id'];
$column = array();
$gtord = mysql_query("SELECT * FROM order WHERE oId = '$ent' ");
while($rowmnu2=mysql_fetch_array($gtord))
{
$column[] = $rowmnu2;
}
echo json_encode($column);
Appreciated.
The json.stringify method simply gets the array in a text format that can be sent to alert. If you are only looking at a single value that isn't an array, you don't need it. Just alert(result[0][3]).
After getting more info:
To access a whole row, use JSON.stringify(result[0]), to look at a specific element use result[0]['user_id']. If you want to use numbers to look at the specific elements, use mysql_fetch_row instead of mysql_fetch_assoc. Hope that helps.

jquery : pass an array in ajax

I have a form with several identical fields:
<input type="text" id="qte" value="" name="qte[]">
How transmetre the array in my file processing?
I noticed that the array sent ajax became a string.
$("#form_commande").submit(function(event){
var qte = $("#qte").val();
if(qte== '')
{
$('#qte_message').html("KO QTE");
}
else
{
$.ajax({
type : "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
success : function(){
$('#form_commande').html('<p>OK</p>');
},
error: function(){
$('#form_commande').html("<p>KO</p>");
}
});
}
return false;
}
Get value in jquery like:
$("#form_commande").submit(function(event){
var qte_array = new Array();
$('input[name="qte[]"]').each(function(){
qte_array.push($(this).val());
});
if(qte_array.length== 0)
{
$('#qte_message').html("KO QTE");
}
else
{
$.ajax({
type : "POST",
url: $(this).attr('action'),
data: {qte:qte_array},
success : function(){
$('#form_commande').html('<p>OK</p>');
},
error: function(){
$('#form_commande').html("<p>KO</p>");
}
});
}
});
and get it in php like:
$qte = $_POST["qte"];
here qte an array
This returns the input textbox object:
$("#qte");
This returns the value of the input textbox object:
$("#qte").val();
Remember you asked for DOM object by id, and this by definition returns only one.
Please read this topic:
JQuery - Reading an array of form values and displaying it?
In short you should iterate with tag name="qte[]" instead of using ids. In DOM you cannot have two different objects with different ids.
var qte_array = new Array();
$('input[name="qte[]"]').each(function(){
qte_array.push($(this).val());
});
After this you have all the values of qte[] array in one object - qte_array. You can later serialize this array to JSON and then pass it as a string.
ALTHOUGH - you shouldn't need to do all those things. You can send ajax request directly with your form, all those data in these inputs will be transferred anyway. You just need to handle them correctly server-side.
id is unique, you can't have more fields with the same ID.
By the way you should convert values to JSON and pass them to Ajax

Passing HTML INPUT field ID to PHP completion program in jQuery Autocomplete

I want to pass the id of the INPUT field to the PHP file providing options. Here's my HTML & jQuery code. But the PHP program gets the id as undefined. Thanks for helping.
jQuery :
$('.classfield').autocomplete({
//define callback to format results
source: function(req, add){
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+$(this).attr('id')+"&callback=?", req, function(data) {
//create array for response objects
var suggestions = [];
//process response
$.each(data, function(i, val){
suggestions.push(val.name);
});
//pass array to callback
add(suggestions);
});
},
//define select handler
change: function(e) {
$("#spill").html("change "+$(this).val()+e.type);
}
}); // autocomplete
HTML:
<input type="text" class="classfield" id="hello" value="there"></input><br>
the value of $(this).attr('id') is undefined because this is the object that is put in the parameter of autocomplete (the parameter of autocomplete accepts an object, so if you use $(this).attr('id'), you are referencing the object that was passed in the parameter on the autocomplete)
therefore you cannot use $(this).attr('id').
You have to store the id of the text field, may be as a global variable... Hope this helps a little bit
Try getting the id from this.element:
//pass request to server
$.getJSON("ajax/ajax_suggestions.php?id="+this.element.attr('id')+"&callback=?", req, function(data) {
Also see this example.

Creating a 2-dimensional jQuery array from a 2-dimensional PHP array with AJAX

I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.
I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.
jQuery code to call AJAX:
var element= $('select[name=elementName]');
var data = 'inData=' + element.val();
// Call AJAX to get the info we need to fill the drop downs by passing in the new ID
$.ajax(
{
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
success:
function(outData)
{
// WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
},
error:
function()
{
}
});
PHP code:
$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'");
$outData = array();
// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));
// echo the data to return it for use in the jQuery file
echo $outData;
The code posted is working fine - I just don't know how to read 'outData' in jQuery.
Thanks in advance for any help!!
Have you looked at json_encode?
echo json_encode($outData);
This will convert it into a json object that can be read by jQuery.
your looking for json
//php
echo json_encode($outData);
//javascript
$.ajax({
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
dataType: "json",
success: function(outData) {
console.log(outData); //this will be an object just like
//your php associative array
},
error: function() {
}
});
JSON can do the trick, but why not look at it from another angle?
If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.
There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.
jQuery can not read the echo of a PHP array. Use json_encode before you output it:
echo json_encode($outData);
That's a format jQuery actually can parse as the response.

Categories