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
}
?>
Related
I am trying to pass some HTML form data as well as a global array to PHP via AJAX. I know how to pass an array, and I know how to pass serialized form data. But how do I pass both at the same time? I have tried data: { formData, arrGFormId: arrGFormId }, but it doesn't work.
Edit: The form is just a simple HTML form with some inputs. My array values come from another AJAX call and are pushed into the global array arrGFormId.
function validateForm3(){
jQuery.ajax({
type: "POST",
url: "community_form_add.php",
async: false,
data: { arrAdminList: arrAdminList },
}).done(function(rs){
var sResult = rs.sResult;
var arrFormId = rs.arrFormId;
Array.prototype.push.apply(arrGFormId, arrFormId);
})
})
var arrGFormId = [];
jQuery('#formCreateForm').submit(function(e){
e.preventDefault();
var formData = new FormData(jQuery(this)[0]);
formData.append('sAction', 'submitForm');
jQuery.ajax({
type: "POST",
url: 'community_form_add.php',
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend:function(){
jQuery('.load_ball').css("display","block");
},
success: function(data)
{
jQuery('.load_ball').css("display","none");
jQuery('.cover').css("display","block");
jQuery('.popUpSubmitSuccess').fadeIn(300);
}
})
});
You need to encode the array, then you can add it to the FormData. You can convert it to JSON.
formData.append('arrGFormId', JSON.stringify(arrGFormId));
Then in PHP you can use json_decode($_POST['arrGFormId']).
you can use hidden input inside the existing form. the value of the hidden inputs are the array. so you only pass formData through ajax.
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);
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'));
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.
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()