Send array with Ajax to PHP script - php

I have array made by function .push. In array is very large data. How is the best way send this to PHP script?
dataString = ??? ; // array?
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
cache: false,
success: function(){
alert("OK");
}
});
script.php:
$data = $_POST['data'];
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
How is the best way for this?

Encode your data string into JSON.
dataString = ??? ; // array?
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "script.php",
data: {data : jsonString},
cache: false,
success: function(){
alert("OK");
}
});
In your PHP
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
Note
When you send data via POST, it needs to be as a keyvalue pair.
Thus
data: dataString
is wrong. Instead do:
data: {data:dataString}

dataString = [];
$.ajax({
type: "POST",
url: "script.php",
data:{data: $(dataString).serializeArray()},
cache: false,
success: function(){
alert("OK");
}
});
http://api.jquery.com/serializeArray/

If you have been trying to send a one dimentional array and jquery was converting it to comma separated values >:( then follow the code below and an actual array will be submitted to php and not all the comma separated bull**it.
Say you have to attach a single dimentional array named myvals.
jQuery('#someform').on('submit', function (e) {
e.preventDefault();
var data = $(this).serializeArray();
var myvals = [21, 52, 13, 24, 75]; // This array could come from anywhere you choose
for (i = 0; i < myvals.length; i++) {
data.push({
name: "myvals[]", // These blank empty brackets are imp!
value: myvals[i]
});
}
jQuery.ajax({
type: "post",
url: jQuery(this).attr('action'),
dataType: "json",
data: data, // You have to just pass our data variable plain and simple no Rube Goldberg sh*t.
success: function (r) {
...
Now inside php when you do this
print_r($_POST);
You will get ..
Array
(
[someinputinsidetheform] => 023
[anotherforminput] => 111
[myvals] => Array
(
[0] => 21
[1] => 52
[2] => 13
[3] => 24
[4] => 75
)
)
Pardon my language, but there are hell lot of Rube-Goldberg solutions scattered all over the web and specially on SO, but none of them are elegant or solve the problem of actually posting a one dimensional array to php via ajax post. Don't forget to spread this solution.

Data in jQuery ajax() function accepts anonymous objects as its input, see documentation. So example of what you're looking for is:
dataString = {key: 'val', key2: 'val2'};
$.ajax({
type: "POST",
url: "script.php",
data: dataString,
cache: false,
success: function(){
alert("OK");
}
});
You may also write POST/GET query on your own, like key=val&key2=val2, but you'd have to handle escaping yourself which is impractical.

dataString suggests the data is formatted in a string (and maybe delimted by a character).
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
}
if dataString is not a string but infact an array (what your question indicates) use JSON.

Related

Jquery pass multiple arrays to PHP

I'm trying to send 4 js arrays to a php page using AJAX, once there I want them in 4 php arrays for use in the php script.
Using $.type(var) I've confirmed my js arrays are actually arrays.
Using the following to send one array works :
$.ajax({
type: "POST",
cache: false,
url: "test.php",
data : arrayA: arrayA,
success: function(res) {
console.log (res)
}
});
But the following fails:
var data = { arrayA: arrayA, arrayB: arrayB, arrayC: arrayC, arrayD: arrayD }
$.ajax({
type: "POST",
cache: false,
url: "test.php",
data : data,
success: function(res) {
console.log (res)
}
});
My php page is :
$arrayA = $_REQUEST['arrayA'];
$arrayB = $_REQUEST['arrayB'];
$arrayC = $_REQUEST['arrayC'];
$arrayD = $_REQUEST['arrayD'];
I'm sure I'm missing the obvious, can some one advise please.
Thanks
Just to try this, this method should work:
// Create the arrays you want
var arrayA = ["cat","dog"];
var arrayB = ["lamp","rock"];
// Combine the arrays into one
var array = [arrayA, arrayB];
// Send them via ajax
$.ajax({
type: "POST",
cache: false,
url: "test.php",
data : array: array,
success: function(res) {
console.log (res)
}
});
PHP side:
<?php
// (use print_r($_POST) to see what comes through and how it is setup in the POST array, that way you can get the keys and names and build it out how you wish
foreach($_POST['array'] as $array){
// This will give each array, you could also get the array keys and use those as names if you wish
}
?>

Can't post JSON variable with AJAX to PHP

In the first document I added a JSON string filled with numbers to localstorage like this:
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}});
Then in another document I am trying to post the JSON string retrieved from local storage like this:
<script>
var data = JSON.parse(localStorage.getItem('key'));
var localData = data.join(", ");
$.ajax({
type: 'post',
data: {localData: localData},
url: '',
dataType: "json",
success: function(result){
console.log(result)
}});
</script>
The PHP on the same page as the post tries to fetch the data like this:
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$values = json_decode($user_id);
var_dump($values);
?>
When I run var_dump I get Array(), so in essence it doesn't post anything. Anyone know whats going wrong?
You don't need to use JSON when sending an array in an object argument to $.ajax. Just put the array there, and jQuery will URL-encode it.
var data = JSON.parse(localStorage.getItem('key'));
$.ajax({
type: "post",
data: { localData: data },
...
});
Then in PHP you can do:
$values = isset($_POST['localData']) ? $_POST['localData'] : array();
var_dump($values);
You can also send JSON this way:
var json_string = localStorage.getItem('key');
$.ajax({
type: "post",
data: { localData: json_string},
...
});
then in PHP do:
$values = json_decode(isset($_POST['localData']) ? $_POST['localData'] : '[]');
var_dump($values);

how to get two arrays from php using json,jquery ajax?

I want to build a graph in jqchart where i need to get two arrays
Now i want to perform operation as given below.Which is giving error ofcourse.
html
$.ajax(
{
type: "GET",
url: "customer_coverage.php",
data: {id:id},
contentType: "application/json",
dataType: "json",
success: function (data21,data22) {
initChart2(data21,data22);
}
});
function initChart2(data21,data22) {
$('#jqChart2').jqChart({
series: [
{
type: 'column',
title: 'no of days ',
data:data21,
},
{
type: 'column',
title: 'no of days ',
data:data22,
},
]
});
}
heres PHP code
echo json_encode($arr1);
echo json_encode($arr2);
So any one has idea of how to do it?
no need to echo json encode two times....merge the array and send the data.......
echo json_encode(array('result1'=>$arr1,'result2'=>$arr2));
and get data by
initChart2(data.result1,data.result2);
See if you are able to produce two object arrays of json then you can try with this:
var data21,data22;
$.ajax({
type: "GET",
url: "customer_coverage.php",
data: {id:id},
contentType: "application/json",
dataType: "json",
success: function (data) {
$.each(data, function(i, item){
data21 = item.data21;
data22 = item.data22;
});
initChart2(data21,data22);
}
});
and i am supposing if you are able to produce this:
[
{
"data21": {
.........
},
"data22": {
........
}
}
]
You cannot get multiple object like that. For a JSON object, you will need to have single object. So what you can do is, create a wrapper object put those two array inside it.
So basically, your php code will be:
<?php
$arr= array();
$arr['arr1'] = $arr1;
$arr['arr2'] = $arr2;
echo json_encode($arr);
?>
So now you will have single main array and so single JSON object.
On JS side, you will get single data. Little Modification will be
$.ajax(
{
type: "GET",
url: "customer_coverage.php",
data: {id:id},
contentType: "application/json",
dataType: "json",
success: function (data) {
var data21=data['arr1'];
var data22=data['arr2'];
initChart2(data21,data22);
}
});
This should work.
You need to combine both array using array_merge().
Example
$response = array();
$response = array_merge($arr1,$arr2);
echo json_encode($response);

parsing array from ajax into php

i want to pass array which is generated by javascript..just say i have an array named vals2=('john','peter') and i want to pass this array to my php page(insert_paket_f.php).
this is my ajax code :
$.ajax({
type: "POST",
url: "insert_paket_f.php",
data: { data : vals2 },
cache: false,
//vals=('john','peter','andrea');
success: function(){
alert("OK");
}
});
insert_paket_f.php
$data1 = $_POST['data'];
$data1 = explode(",", $_POST['data']);
print_r($data1);
when i run my browser, its show empty array, and just looks like this Array ( [0] => )
how can i fix this?
thanks..
Try this:
Use join to send the javascript array as an string.
Javascript
var vals2 = ['john','peter'];
$.ajax({
type: "POST",
url: "insert_paket_f.php",
data: { data : vals2.join(',') },
cache: false,
success: function(){
alert("OK");
}
});
PHP
$data1 = $_POST['data'];
$data1 = explode(",", $_POST['data']);
print_r($data1);
Hope it helps.
Try:
$data1 = json_decode($_POST['data']);
print_r($data1);
In the Data Feild try to use variables
as
echo data: data[]=john&data[]=peter&data[]=andrea
Code:-
$.ajax({
type: "POST",
url: "insert_paket_f.php",
data: "data[]=john&data[]=peter&data[]=andrea",
cache: false,
success: function(){
alert("OK");
}
});
Is It working?

Sending an array to php from JavaScript/jQuery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
send arrays of data from php to javascript
I know there are many questions like this but I find that none of them are that clear.
I have an Ajax request like so:
$.ajax({
type: "POST",
url: "parse_array.php",
data: "array=" + array,
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
How would I send a JavaScript array to a php file and what would be the php that parses it into a php array look like?
I am using JSON.
Step 1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
You php file looks like this:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
The success function
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
You can just pass a javascript object.
JS:
var array = [1,2,3];
$.ajax({
type: "POST",
url: "parse_array.php",
data: {"myarray": array, 'anotherarray': array2},
dataType: "json",
success: function(data) {
alert(data.reply); // displays '1' with PHP from below
}
});
On the php side you need to print JSON code:
PHP:
$array = $_POST['myarray'];
print '{"reply": 1}';
HI,
use json_encode() on parse_array.php
and retrive data with json_decode()

Categories