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

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()

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 pass an array of string using ajax?

I'm using this ajax to pass an array of strings to another page.
This is the array on nomes.php
[ 'Home','A empresa','funcionarios','Quem Somos?','Historia','Inicio',]
This is the code, the alert doesn't work - can anyone help?
$.ajax({
type: 'post',
url: 'nomes.php',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType: "json",
success: function(data){
v=data;
alert(v);
}
});
You need to encode the PHP-array to a JSON-array.
<?php
echo (json_encode($myPhpArray));
?>
You can serialize the array into JSON using stringify to pass them through. Add this to your Ajax call:
data: JSON.stringify(arr);
Replace arr with your JavaScript array. This needs a plugin though. Have a look at this answer for more info.
Alternatively, if your array is in PHP, not in JavaScript you can echo it out directly like this:
data: <?php echo json_encode($arr) ?>,
If you're trying to pass the json to the server, you can do it like :
var strArray = ['str1', 'str2', 'str3'];
$.ajax({
type: 'post',
url: 'nomes.php',
data: {strarray: strArray},
dataType: "json",
success: function(data){
v=data;
alert(v);
}
});
If you're trying to receive it, you need to set the header on php side :
header('content-type: application/json');
echo json_encode(array('str1', 'str2', 'str3'));

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

How to decode a json object sent through jquery ajax method in php file?

This is the jquery ajax part in which i have sent json data to the php file.
$(function () {
$('form').submit(function () {
var fields = $(this).serializeArray();
var ans_json = JSON.stringify(fields);
console.log(ans_json);
$.ajax({
url: "results.php",
type: "POST",
data: ans_json,
dataType: "json",
success: function (result) {
console.log(result);
}
});
return false;
});
});
Now i want to use this json data sent to the php page.How can i do it? I have done it this way but it returns null.
<?php
echo json_decode('ans_json');
?>
I have a set of 10 questions which need to be answered. 3 questions were answered so got the below result.This is what i got in my console.
[{"name":"answer_9","value":"a"},{"name":"answer_10","value":"a"}] quizzes.php:14
null
You don't need to decode any JSON string at server-side if you encode properly your parameters.
You can use .serialize() to do the form serialization for you, and it's ready to send.
$(function () {
$('form').submit(function () {
var serialized = $(this).serialize();
$.ajax({
url: "results.php",
type: "POST",
data: serialized,
...
});
return false;
});
});
Your parameters will be available in your $_POST as in any normal POST request. For example,
$ninth_answer = $_POST["answer_9"];
You need to decode the POST variable. Currently you're decoding just a string which even isn't valid JSON.
<?php
$json_arr = json_decode($_POST['my_json'], true);
var_dump($json_arr);
echo "First name in json is:". $json_arr[0]['name'];
?>
and edit your javascript to reflect following:
This posts my_json parameter with your json as an value. This makes it easy for PHP to recieve it using $_POST.
$.ajax({
url: "results.php",
type: "POST",
data: {"my_json": ans_json},
dataType: "json",
success: function (result) {
console.log(result);
}
});
I suggest to read a little about those things:
http://api.jquery.com/jQuery.ajax/
http://ee1.php.net/manual/en/function.json-decode.php

Categories