Unable to post Javascript array via jQuery ajax - javascript

I am extremely reluctant to ask this question as I know it is something really stupid I am missing, but I simply cannot get this to work. Code below:
<script>
var formArray = new Array();
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";
$('#my_button').click(function() {
$.ajax({
type: "POST",
url: "scheduler.php",
data: formArray,
success: function(response){
console.log(response);
}
});
});
</script>
Server side PHP Script scheduler.php
<?php
print_r($_POST);
?>
All I get back logged to the console is an empty array:
Array
(
)
If I console.log formArray within the click function it shows the complete array just fine. So why is it not posting it to my PHP file?
Thanks in advance

Changing Array() to Object() would work as well.
You would get:
Array
(
[start] => one
[stopat] => two
[stop_at] => three
)

You are adding string properties to an array, which is for storing numeric indices.
Use an object instead:
var formArray = {};
formArray['start'] = "one";
formArray['stopat'] = "two";
formArray['stop_at'] = "three";
jQuery will iterate over the indices in an array, using a for (var i = 0; i < formArray.length; ++i) loop, which will completely miss any properties you've added to the array.
Also, new Array should have been [] (as {} should be preferred over new Object). Don't use the new X method of initialization for built-in types. (Crockford, The Good Parts)

JavaScript Arrays are designed to hold an ordered sequence of items with integer keys. When jQuery converts a data structure into Form URL Encoded data and encounters an array, it will iterate over those integer keys and not over named keys.
Use an Object if you want to have named keys.
Change new Array() to newObject()

Edit your Ajax like this and see if it works: data: {data: formArray}, dataType: 'JSON'
$.ajax({
type: "POST",
url: "scheduler.php",
data: {data : formArray},
dataType: 'JSON'
success: function(response){
console.log(response);
}
});
PHP:
print_r($_POST['data']);

Related

$.each function is not iterating

I am working with a relatively complex JSON structure and am unable to iterate through it via the $.each() function. I'm pretty sure it's something to do with the weird 2-dimensional array I am passing through in the value section of the normal array (hope that made sense). I am new to Ajax and JSON so just need some guidance on the best way to handle JSON when it is returned via an AJAX Call. Thanks!
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var i = 0;
for(var k in data){
window.alert(k);
} //this works
$.each(data, function(key, value){ //however this does not display anything
window.alert("should be outputted");
window.alert("key" + key + "value" + value[i]['email']);
i++;
});
});
JSON I am using:
{"bodge.com":[{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},{"email":"fwzqfjma#bodge.com","orders":"3","value":"13.71"},{"email":"rwsofs#bodge.com","orders":"7","value":"6.49"},{"email":"vfr#bodge.com","orders":"3","value":"24.36"},{"email":"wcs#bodge.com","orders":"3","value":"11.26"},{"email":"oqmsboag#bodge.com","orders":"3","value":"5.36"},{"email":"wdvm#bodge.com","orders":"6","value":"18.21"},{"email":"xubumenme#bodge.com","orders":"1","value":"10.24"},{"email":"pleqlwpha#bodge.com","orders":"2","value":"6.59"},{"email":"dqhdcnvw#bodge.com","orders":"10","value":"7.85"},{"email":"gyxymze#bodge.com","orders":"1","value":"15.51"},{"email":"otbbqcw#bodge.com","orders":"2","value":"7.92"},{"email":"afspqpq#bodge.com","orders":"3","value":"13.22"},{"email":"fwovyddw#bodge.com","orders":"4","value":"23.14"},{"email":"urczmgy#bodge.com","orders":"7","value":"15.17"},{"email":"hkgccna#bodge.com","orders":"4","value":"17.62"},{"email":"hlrnunyf#bodge.com","orders":"4","value":"22.03"},{"email":"gafoubu#bodge.com","orders":"10","value":"16.71"},{"email":"muwfjqs#bodge.com","orders":"4","value":"6.09"},{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},{"email":"jbq#bodge.com","orders":"8","value":"5.37"}],"bodge.com ":[{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}]}
Your JSON has (at least) two levels:
an object with keys ("bodge.com", "bodge.com "), and
each key holds an array of objects
{
"bodge.com": [
{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},
{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},
...
{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},
{"email":"jbq#bodge.com","orders":"8","value":"5.37"}
],
"bodge.com ": [
{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}
]
}
In order to iterate through the structure, you will need at least two levels of iteration:
$.each(data, function(domain, objects) {
console.log(domain); // will output "bodge.com" or "bodge.com "
$.each(objects, function(index, x) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
Note that you are using $.each for two different kinds of iteration: first over the keys and values of an object, then over the items in an array.
As an alternative, use Object.keys to get an array of an object's keys, and the forEach method:
Object.keys(data).forEach(function(domain) {
console.log(domain); // will output "bodge.com" or "bodge.com "
data[domain].forEach(function(x, index) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
It looks like you should be bypassing data['bodge.com'] into the each function rather that simply data.
You could try this;
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var list = JSON.parse(data);
$.each(list, function(i){
alert(list[i].your_filed);
});
});

dynamically build data string for ajax call that contains html

For a long time I have been using the below code to dynamically build a string representing key value pairs to be used in an ajax call.
This has been working quite well for my originally simple needs.
// make an array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=val2', 'var3=val3' ];
// join each pair with "&" seperating them
var dataString = feedback.join('&');
// make an ajax call
$.ajax({
type: "POST",
url: "_php/feedback.php",
data: dataString, //pass in the built vars
success: function() {
// do stuff...
}
});
I now have the need to send html as values in the data string. First thing I notice is that html containing '&' is going to be an issue so I made a simple test using var2=<span> val2<span>:
// make any array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=<span> val2<span>', 'var3=val3' ];
// join each pair with "&" seperating them
var dataString = feedback.join('&');
// amke an ajax call
$.ajax({
type: "POST",
url: "feedback.php",
data: dataString, //pass in the built vars
success: function(info) {
$('#result').html(info);
}
});
Then in my php page:
<?php
$var1=$_POST['var1'];
$var2=$_POST['var2'];
$var3=$_POST['var3'];
echo $var1.'<br>'.$var2.'<br>'.$var3.'<br>';
?>
I want the script to return:
val1<br><span> val2<span><br>val3<br>
But, just as I suspected, the return output was:
val1<br><span><br>val3<br>
A quick look in the inspector shows:
How can I dynamically create a string to use with data: dataString, in an ajax call that may contain html?
I tried searching for this but all I can find is "how to send post data with an html form" which clearly doesnt help.
// make an array of strings representing key value pairs
var feedback = ['var1=val1', 'var2=val2', 'var3=val3' ];
// to apply encodeURIComponent function for each cell
feedback = feedback.map(function (cell)
{
var res = cell.split('=');
return res[0] + '=' + encodeURIComponent (res[1]);
}) ;
// join each pair with "&" seperating them
var dataString = feedback.join('&');
$.ajax({
type : "POST",
url : "feedback.php",
data : dataString,
success: function(info) {
$('#result').html(info);
}
});

convert php array of multidimensional arrays to javascript array

Hi i have that php code example :
$array1 = array("fruits" => "banana","vegetables" => "tomatos");
$array2 = array("name" => "Jack","Age" => "32");
$array3 = array($array1, $array2);
echo json_encode($array3);
javascript code includes jquery :
var json_data = $.ajax({
type: 'POST',
url: 'scripts/myfile.php',
data: { action: 'myaction' },
dataType: 'json',
cache: false,
success: function(result) {
console.log(result);
}
});
how to convert json_data to an array and affect the two of $array1 & $array2 to javascript arrays !
this is the json_data content :
"{"HUM":[{"label":"2014-10-16 17:08:55","y":"58"},{"label":"2014-10-15 08:16:55","y":"56"},{"label":"2014-10-15 08:16:50","y":"56"},{"label":"2014-10-15 08:16:45","y":"56"},{"label":"2014-10-15 08:16:40","y":"56"},{"label":"2014-10-15 08:16:35","y":"56"},{"label":"2014-10-15 08:16:30","y":"56"},{"label":"2014-10-15 08:16:25","y":"56"},{"label":"2014-10-15 08:16:20","y":"56"},{"label":"2014-10-15 08:16:15","y":"56"},
"TEMP":[{"label":"2014-10-16 17:08:55","y":"26"},{"label":"2014-10-15 08:16:55","y":"24"},{"label":"2014-10-15 08:16:50","y":"24"},{"label":"2014-10-15 08:16:45","y":"24"},{"label":"2014-10-15 08:16:40","y":"24"},{"label":"2014-10-15 08:16:35","y":"24"},{"label":"2014-10-15 08:16:30","y":"24"},{"label":"2014-10-15 08:16:25","y":"24"},{"label":"2014-10-15 08:16:20","y":"24"},{"label":"2014-10-15 08:16:15","y":"24"},
"HUM2":[{"label":"2014-10-16 17:08:55","y":"38"},{"label":"2014-10-15 08:16:55","y":"36"},{"label":"2014-10-15 08:16:50","y":"36"},{"label":"2014-10-15 08:16:45","y":"36"},{"label":"2014-10-15 08:16:40","y":"36"},{"label":"2014-10-15 08:16:35","y":"36"},{"label":"2014-10-15 08:16:30","y":"36"},{"label":"2014-10-15 08:16:25","y":"36"},{"label":"2014-10-15 08:16:20","y":"36"},{"label":"2014-10-15 08:16:15","y":"36"},{"label":"2014-10-15 08:16:10","y":"36"},
"TEMP2":[{"label":"2014-10-16 17:08:55","y":"23"},{"label":"2014-10-15 08:16:55","y":"24"},{"label":"2014-10-15 08:16:50","y":"24"},{"label":"2014-10-15 08:16:45","y":"24"},{"label":"2014-10-15 08:16:40","y":"24"},{"label":"2014-10-15 08:16:35","y":"24"},{"label":"2014-10-15 08:16:30","y":"24"},{"label":"2014-10-15 08:16:25","y":"24"},{"label":"2014-10-15 08:16:20","y":"24"},{"label":"2014-10-15 08:16:15","y":"24"},{"label":"2014-10-15 08:16:10","y":"24"},{"label":"2014-10-15 08:16:05","y":"24"},{"label":"2014-10-15 08:16:00","y":"24"}]}"
now i want to convert it to array and then serparate arrays HUM - TEMP - HUM2 - TEMP2
In your code,
$array3 = array(array1, array2);
here array1 and array2 considered as string without quotes, so you will not get your answer. This should be PHP variable. You have to include $ sign in this.
$array3 = array($array1, $array2);
$array3 = array(array1, array2); should be $array3 = array($array1, $array2);
From jQuery $.ajax() documentation on dataType when it is set to json.
"json": Evaluates the response as JSON and returns a JavaScript object. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
The object result is already a JSON object in the success function. So you can simply use result[0]['fruits'] or result[1]['name'] to access the relevant arrays.
Edit : Corrected index as #charlietfl pointed out.

can somene explain me, why this code result is different?(javascript object and array)

i will ask about this:
i have an javascript object like this:
var stops = [
{"Geometry":{"Latitude":52.1615470947258,"Longitude":20.80514430999756}},
{"Geometry":{"Latitude":52.15991486090931,"Longitude":20.804049968719482}},
{"Geometry":{"Latitude":52.15772967999426,"Longitude":20.805788040161133}},
{"Geometry":{"Latitude":52.15586034371232,"Longitude":20.80460786819458}},
{"Geometry":{"Latitude":52.15923693975469,"Longitude":20.80113172531128}},
{"Geometry":{"Latitude":52.159849043774074, "Longitude":20.791990756988525}},
{"Geometry":{"Latitude":52.15986220720892,"Longitude":20.790467262268066}},
{"Geometry":{"Latitude":52.16202095784738,"Longitude":20.7806396484375}},
{"Geometry":{"Latitude":52.16088894313116,"Longitude":20.77737808227539}},
{"Geometry":{"Latitude":52.15255590234335,"Longitude":20.784244537353516}},
{"Geometry":{"Latitude":52.14747369312591,"Longitude":20.791218280792236}},
{"Geometry":{"Latitude":52.14963304460396,"Longitude":20.79387903213501}}
]
alert(stops);
in first code the alert result is
i have a data from ajax request, so i can make an object like that dynamic.. i call it from my database
var stops=new Array();
var myObject={};
$.ajax({
url: 'http://localhost:5566/Gps/api/rute.php?id='+id,
//url: 'http://localhost:5566/Gps/api/rute.php?id='+id,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
async: false,
success: function(data, status){
i=0;
stops+="[";
$.each(data, function(i,item){
stops+="{\"Geometry\":{\"Latitude\":";
stops+=item.latitude;
stops+=",";
stops+="\"Longitude\":";
stops+=item.longitude;
stops+="}}";
stops+=",";
});
stops+=stops.substring(0,stops.length-1);
stops+="];";
alert(stops);
in second code the alert result is
i think the stops variable have same structure,but why the alert result is different?
can i convert second code to object like first code? thank you :)
any help will be appreciated
Your first object is an array the second you appear to be manually building a JSON string into an array?
As stops is an array just add objects to it:
success: function(data, status){
$.each(data, function(i,item){
var stop = {
Geometry: {
Latitude: item.latitude,
Longitude: item.longitude
}
};
stops.push(stop);
});
alert(stops);
}
The second one is a string. Yes, you can decode JSON.
To convert the first like the second use:
JSON.stringify(stops);
To convert the second like the first use:
JSON.parse(stops);
or
$.parseJSON(stops);
edit: As was recommended, since you are using jQuery you can use $.parseJSON(stops) in place of JSON.parse(). It will actually use the native parse if available. There is no equivalent (that I know of) for stringify.

assign object to array in javascript multidimensional array

Below i have given my code which is a javascript function which calls a php file and gets json data .... all things are perfect yet but i am getting problem when i want to adda data to a multidimensional array .. sorry for this noob question.. i don't know it can be done or not.
what i want to do
i want to retrieve data on ajax call and save this data to array
so i dont need to call again if i need data again
so i want to store data in multidimensional array which will have two keys
first key will be length iof array
and second will be dataType of my data which can be "name", "id", "description"
is this right way to do this
if it is not then what should i try ...? HELP ME...!!!
or can i assign full jsondata object data got from ajax call success to an array
Newly added requirements of my question
Its associative array like my php array of data is like
$data[0]["id"] = 1;
$data[0]["name"] = "spomething";
$data[0]["descriptoon"] = "spomething";
$data[0]["image"] = "spomething";
//for second item
$data[1]["id"] = 1;
$data[1]["name"] = "spomething";
$data[1]["descriptoon"] = "spomething";
$data[1]["image"] = "spomething";
so i want to create same array for javascript... for every item i fetch... from ajax../ and include into javascript array...
$('.searchButton').bind("mouseover", function() {
var data = $(this).parents('.item').attr('id');
var type = $(this).parents('.tab-pane').attr('id');
// dataArray will be global javascript variable because of its needdss... it will be outside the function
var dataArray = new Array();
$.ajax({
type: 'GET',
url: '<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success: function(data){
var dataArrayLength = dataArray.length;
dataArray.push({dataArrayLength:data});
console.log(dataArray[0]);
}
});
});
now i change my code on thebasis of your suggestion i can push data object in array via push fn ... now how do i call inside data from that object ....!
Object {dataArrayLength: Object}
dataArrayLength: Object
description: "World famous roasted Chicken, avacado, fresh mushrooms, red onions. Mozzarella cheese and our secret sauce."
id: "11"
images: "/htdocs/kiosk/images/dining/items/pizzas/11.jpg"
name: "Bella Notte Signature Pizza"
price: "4.50"
raters: "10"
ratings: "1"
__proto__: Object
__proto__: Object
this is the output of console.log(dataArray[0]) ... so now i want to get "id" , "name", "description" from it how can i do this...????/
MY SOLUTION TO PROBLEM
success:function(data){
var dataArrayLength = dataArray.length;
dataArray.push(data);
dataArray.forEach(function(object,index){
console.log(object.id);
console.log(object.name);
console.log(object.description);
console.log(object.image);
console.log(object.ratings);
});
and this is what i want to do ...
Try this:
$.ajax({
type:'GET',
url:'<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success:function(data){
dataArray = []; // empty it before pushing data into it...
dataArray.push(data);
}
});
I believe you can directly push the data object into the dataArray.
and while you access this simple access it like dataArray[i].id, dataArray[i].name and so on for all the keys of data.
I'm not quite sure i understand, but cant you simply do:
$.ajax({
type:'GET',
url:'<?php echo $this->createUrl("dining/AjaxItemDetailsCall") ?>/data/'+data,
dataType: 'json',
async: false,
success:function(data){
var dataArrayLength = dataArray.length;
dataArray.push({'id':data.id,'name':data.name,'image':data.image,'description':data.description});
}
});
});
Or even:
dataArray.push(data);
I havent tested this so consider it pseudo code but i belive that the push method is what you are looking for?

Categories

Resources