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
Related
I will send value type ajax but when data return come back will return json
How to append value to input text.
$.ajax({
type: "POST",
url: "find_data.php",
data: "location=" + location_code,
success : function(data){
$.each(data, function(key, values){
$('#card').val(values.card);
});
},
dataType: "json",
error:function(error){
alert(error);
}
});
Sorry for my english.
This is will show like this =>
Seems you have an invalid markup as in having same IDs for multiple input[type=text] elements. The valid thing is IDs should be unique for each element or use a common class name.
If this is the case then i would suggest you to change the ID to class instead:
<input type='text' class='card'>
now in your ajax success you can change to this:
success : function(data){
$.each(data, function(key, values){
$('.card').get(key).val(values.card);
});
},
this line can be changed to this too:
$('.card')[key].value = values.card;
You have to post your markup for this, this case is my assumption.
What could be the issue?
If you assign same ID to multiple elements and when you make a selector of that ID, That always returns a single element in the page elements lookup. When lookup gets started and it finds the ID, it stops the lookup as per valid markup every element should have unique IDs.
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
$(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);
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.
<input id="u1" class="username">
<input id="u2" class="username">
<input id="u3" class="username">
...
How to fetch input value with "username" class and send with ajax jquery to php page.
i want to recive data like simple array or simple json. (i need INPUT values and not ids)
var inputValues = [];
$('input.username').each(function() { inputValues.push($(this).val()); });
// Do whatever you want with the inputValues array
I find it best to use jQuery's built in serialize method. It sends the form data just like a normal for submit would. You simply give jQuery the id of your form and it takes care of the rest. You can even grab the forms action if you would like.
$.ajax({
url: "test.php",
type: "POST",
data: $("#your-form").serialize(),
success: function(data){
//alert response from server
alert(data);
}
});
var values = new Array();
$('.username').each(function(){
values.push( $(this).val());
});