Pass JS Array to server through $.ajax call - php

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] ...

Related

how to load array response from ajax into array input textbox

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

working with ajax and php as front and backend

var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: text,
dataType: "text"
});
insertGroupData.done(function(msg){
alert(msg);
});
This is the first half, I'm stuck in the 1st line of my backend.php
I think it should be catch the POST value, but what should I catch?
<?php
if(isset($_POST["_____??_____"])){
echo "test";
}
Jquery: if your data should be like
data: {test:text},
Then in PHP you can use to get like below,
if(isset($_POST["test"])){
echo "test";
}
Explanation about data:
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting .
Ref: http://api.jquery.com/jQuery.ajax/
change your code to this
var insertValue= $.ajax({
url: "handle.php",
type: "POST",
data: {text:text},
dataType: "text"
});
in backend page you can check it like
echo $_REQUEST['text];
or
echo $_POST['text];
A lesson in jQuery
$(function () {
var
url = 'your/target/script.php',
data,
fn = function (text) {alert(text);},
// fn will expect text, so set return as text
dataType = 'text';
// this POST data will populate $_POST as $_POST[key] = 'value'
data = {
ajax : 1,
key : 'value',
key2 : 'another value'
};
// shorthand notation is convenient sometimes
$.post(url,data,fn,dataType);
});
Your php now has access to your key value pairs
<?php
// in my example the 3 are set
if (isset($_POST['ajax'])) {
$_POST['key'];
$_POST['key2'];
}
Happy coding

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

jQuery Looping JSON Data

I have created APIs to retrieve data from my server and then I get the data with json format like this :
{
"items": [
{
"2013-03-28": 1771,
"2013-03-29": 1585,
"2013-03-30": 1582,
"2013-03-31": 1476,
"2013-04-01": 2070,
"2013-04-02": 2058,
"2013-04-03": 1981,
"2013-04-04": 1857,
"2013-04-05": 1806,
"2013-04-06": 1677,
"2013-04-07": 1654,
"2013-04-08": 2192,
"2013-04-09": 2028,
"2013-04-10": 1974,
"2013-04-11": 1954,
"2013-04-12": 1813,
"2013-04-13": 1503,
"2013-04-14": 1454,
"2013-04-15": 1957,
"2013-04-16": 1395
}
]
}
How do I looping with my json data dynamically using jQuery?
My code :
<html>
<head></head>
<body>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type : "GET",
url: "myurl.php",
cache: false,
dataType: "jsonp",
success:function(data){
if(data==''){
alert('Fail');
}else{
alert('Success');
}
}
})
});
</script>
</body>
</html>
How do I modify my jQuery to get data dynamically following the date that the data will change every day as in the example I wrote above data??
Thanks before...
There are a few things to consider with your example data, but in your case, the following will do the trick:
var importantObject = data.items[0];
for(var item in importantObject ){
var theDate = item;//the KEY
var theNumber = importantObject[item];//the VALUE
}
Here is a working example
But what does all this mean?...
First of all, we need to get the object that we want to work with, this is the list of dates/numbers found between a { } (which means an object) - an array is defined as [ ]. With the example given, this is achieved like so:
var importantObject = data.items[0];
because items is an array, and the object we want is the first item in that array.
Then we can use the foreach technique, which effectively iterates all properties of an object. In this example, the properties are the date values:
for(var item in importantObject ){ ... }
Because we are iterating the properties, item will be the property value (i.e. the date bit), so item is the date value:
var theDate = item;//the KEY
Finally we get the number part. We can access the value of any given object property by using the string value of the property index (relative to the object), like so:
var theNumber = importantObject[item];//the VALUE
If you already know which date you want the value for, then you can access it directly like so:
var myValue = data.items[0]["2013-04-16"];//myValue will be 1395 in this example
Using jQuery.each() loop through the items
$.each(data.items[0], function (key, value) {
console.log(key + ": " + value);
var date = key;
var number = value;
});
DEMO HERE
You can use the jQuery each function to do this. For example like this:
$.each(data, function(k, v) {
// Access items here
});
Where k is the key and v is the value of the item currently processed.
//get your detail info.
var detail = data.items[0];
$.each(detail, function(key, val) {
console.log(key + ": " + val);
}

Build json to send to php using a for loop (maybe)

I've googled around, but i can find a way to build json with jQuery and send it to php using a for loop. I have a html table, and i want to take values from each row (i dont know how many rows/values there will be) construct a json string, ie. [{"row": 1, "supp_short_code" : blah blah....}, {"row": 2, ....} ....]
but i dont know how to keep adding to the json datastring each time jQuery finds more values if that makes sense??
EDIT:
So if i have this
$('#submit').live('click',function(){
var supp_short_code=$('.supp_short_code').text();
var project_ref=$('.project_ref').text();
var om_part_no=$('.om_part_no').text();
var description=$('.description').text();
var cost_of_items=$('.cost_of_items').text();
var cost_total=$('.cost_total').text();
var dataString = 'string=//' + supp_short_code + '//' + project_ref + '//' + om_part_no + '//' + description + '//' + cost_of_items + '//' + cost_total
$.ajax
({
type: "POST",
url: "order.php",
data: dataString,
cache: false,
success: function()
{
alert("Order Submitted");
}
});
});
So what (roughly) would i need to change in this code?
Ok, so as you can see by the screenshot, i'm using jquery to dynamically add the bottom table when a user click a row from the top table, its calculating totals and they can specify which supplier they want to use. I'm then using jquery to grab these values into the $('submit') bit of jquery code at the top. I then want to send these values to a php page that will somehow parse the received data at insert it into a mysql db, as something like "id 1 product blah price blah supplier blah total cost £x, id 2 product blah2 price blah2 supplier blah total cost £x" so some fields, ie the total cost and supplier will be the same, but the php might be receiving 3 different products for the same order if that makes sense? Thanks!
You don't need to build the json, just build the data array and send it with .post, .get or .ajax. jQuery will take care of encoding the array for you:
var data = {};
for (var i = 0; i < 3; ++i) {
data['field' + i] = 'value' + i;
}
$.post ('http://mysite.com/page', data, function() { alert('succes!'); });
Your server-side code's $_POST array will containing:
array( 'field1' => 'value1', 'field2' => 'value2', 'field3' => 'value3');
For your example, I would reconsider sending the data as a string and instead send the data as well-formated key/value pairs. Your server-side code can more easily decide what to do with it, and your JS won't require a rewrite if the server-side code needs the string to be built differently.
$.ajax ({
type: "POST",
url: "order.php",
data: {
supp_short_code: $('.supp_short_code').text(),
project_ref: $('.project_ref').text(),
om_part_no: $('.om_part_no').text(),
description: $('.description').text(),
cost_of_items: $('.cost_of_items').text(),
cost_total: $('.cost_total').text()
}
//...
});
Update
You could reduce the amount of typing by throwing your field names into an array, and appending the class name of any fields you want to include in the data array. Then loop over each of your table rows and extract the values:
var fields = [ 'supp_short_code', 'project_ref', 'om_part_no',
'description', 'cost_of_items', 'cost_total'];
var data = [];
// loop over each row
$('#my-table tr').each(function (i, tr) {
// extract the fields from this row
var row = {};
for (var f = 0; f < fields.length; ++f) {
row[fields[f]] = $(tr).find('.' + fields[f]).val();
}
// append row data to data array
data.push(row);
});
Here's a quick way to grab data from your table, and format it as an array:
var data_to_send = $('#yourtable').find('tr').map( function(idx){
return [
'row': idx+1,
'supp_short_code' : $(this).find('td').eq(2).text(),
'something_else' : $(this).find('td').eq(3).text() // etc
];
}).get();
Now you have data_to_send, an array formatted similarly to the example in your question. As #meagar points out, you can simply post this to the server with .ajax() et al., and allow jQuery to automatically handle the encoding. Something like this:
$.ajax ({
type: 'post',
url: 'your_script',
data: data_to_send
});

Categories