We are sending data through Ajax call and getting response as array. we want to loop that array and load into array input field. but data not loading into input.
<input type="hidden" name="loadchild[]" id="loadchild[]" >
this textbox is in loop
$.ajax({
type: "POST",
url: "asign.php",
data: {plan_id: plan_id},
dataType: "json",
success: function (dta)
{
/*
here dta['insert_id'] is single value and
dta['child_ids'] are multiple values and i am getting as [1,2,3,4,5] */
for (var i = 0; i < dta['child_ids'].length; i++)
{
$("#loadchild[" + i + "]").val(dta['child_ids'][i]);
}
}
});
here i am getting as [object Object] when asigning value to textbox
Please let me know how to pass array value one by one into
try this
1)you have to escape the brackets like this
for(var i=0;i<dta['child_ids'].length;i++)
{
//$("#loadchild["+i+"]").val(dta['child_ids'][i]);
$("#loadchild\\[\\]").eq(i).val(dta['child_ids'][i]);
}
Related
I am trying to Pass a comma separated Id values to PHP using Jquery Post. I have below code in my Jquery
var values = [];
$('tr#trdata td:nth-child(1)').each(function () {
values.push("'"+$(this).html()+"'");
});
Above code is out putting value like this '238','239','240','241','242','243','244','245','246'
I am then Trying to post above value using below code
$.ajax({
url : "mypage.php",
method:"POST",
dataType:"text",
cache:false,
data:{page_no:values, type: type, keyword: keyword},
success:function(data){
}
});
And in my php I am trying to get the value with below code
if (isset($_POST['page_no'])) {
$page = $_POST['page_no'];
}else{
$page = 0;
}
I am getting the comma separated values in console correctly but in php it is always empty
what is the wrong I am doing?
Here is my piece of code :
$('#addType').on('submit', function(e) {
$form = $(this);
var type = [];
$(this).find('input[type=number]').each(function() {
type[$(this).attr('id')] = $(this).val();
});
console.log(type);
$.ajax({
type: 'POST',
url: '<?php echo $this->url(array(), 'addType');?>',
data: {type: type},
success: function() {
$form.find('input[type=submit]').attr('disabled','disabled');
}
});
e.preventDefault();
});
As you can see, it builds an javascript array from the inputs in form#addType and send it to a server side script supposed to handle this array. My problem is that no data is passed through $.ajax({}).
UPDATE
It seems that it comes from the values of the array keys that cannot by litteral. If I put an incremented number as key, the array is successfully passed. How come?
Make the type an object, not an array:
var type = { };
You created type as an array (using []). Array is an object, too, so You can add named members to it, which is what You do in Your loop:
type['my-item-id'] = xxx;
But when You add the type variable to the Ajax request, jQuery checks that the variable is an array and so it iterates through the type as trough an array, so it looks for it's "numerical-indexed" items using type.length (which is 0 as You added none):
for (var i = 0; i < type.length; i++)
... type[i] ...
When You create type as an Object (using {}), jQuery sees that it should iterate over type as over an object and does it so and "sees" the "named" items:
for (var i in type)
... type[i] ...
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 have a php page that returns json like this:
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
$rows[] = $row;
}
print json_encode($rows);
When I run the php page I get back something like:
[{"phone":"1234567"},{"phone":"1234567"}]
This is my jquery code:
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(response) {
$.each(response, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
});
I got that from another SO question. This will give me my keys and value in the alert. This was just for me to make sure everything works. I have searched but cannot figure out how to just get one value. Say I wanted the name, what do I put? I have tried:
success: function(response) {
var obj = $.parseJSON(response);
alert( obj.phone );
}
But since it is multiple rows it won't work unless I have, and it also fails when I have one row like this:
echo json_encode(array("phone" => "123")
How do I get a single value from a row?
How do I iterate through multiple rows and only get one of the column values?
The response variable is an array of objects. To access a single index in your response variable:
var phone = response[0].phone;//replace `0` with the index you want
If you end-up iterating through your response in a loop make sure to do it like this for the best performance:
var len = response.length;
for (var i = 0; i < len; i++) {
console.log(response[i].phone);
}
Check-out this jsperf to see how much faster this type of loop is than for(i in array): http://jsperf.com/for-in-tests
The response JSON is an array. To get the first phone number, retrieve the first object through response[0], then get the property using .phone:
success: function(response) { //response = array, when using dataType:"JSON"
alert(response[0].phone);
}
Replace 0 with any number between 0 and response.length to get the corresponding phone property.
Javascript:
for (var i; i < response.length; i++) {
console.log(response[i].phone);
}