Send array with Ajax to PHP script
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}
Send array with ajax request to php
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php
as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php
from $_POST
array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
Cannot send array to php via AJAX?
You defined values
as an array and therefore when you stringify it, you get an empty array. Define it as an object like values = {};
and it will work.
You don't use associative arrays in javascript because
If you use named indexes, JavaScript will redefine the array to a
standard object. After that, some array methods and properties will
produce incorrect results.
Thats's why you need to define it as object in the beginning.
values = {};
values['mpsRegnomer'] = $('#mpsRegnomer').val();
values['mpsMarka'] = $('#mpsMarka').val();
values['mpsMarkaOther'] = $('#mpsMarkaOther').val();
Here is a working JSFiddle.
http://jsfiddle.net/pk97fe0b/
how to pass array in ajax call using php
convert it into json and try it.
hope that works for you.
Send array with Ajax to PHP script and Implode
First in my JS function I forgot to:
query.join(',');
Next in my PHP I forgot to remove single quotes from my MYSQL query and also I don't need to use implode at all.
So here is what I did:
JS function:
function getRelated() {
var elements = (document.getElementsByClassName('escashare'));
var query = [];
for(var i=0;typeof(elements[i])!='undefined';query.push(elements[i++].getAttribute('data-id')));
query = query.join(',');
$.ajax({
type: "POST",
url: baseUrl+"/requests/get_related.php",
data: "query="+query+'&_token='+_token,
cache: false,
success: function(html){
$('#main-content').append(html);
}
});
}
PHP function:
function getRelated($get_query) {
$query = $this->db->query(sprintf("SELECT * FROM `posts` WHERE `id` IN (%s)", $this->db->real_escape_string($get_query)));
while($result = $query->fetch_assoc()) {
$rows[] = $result;
}
if(!empty($rows)) {
foreach($rows as $row) {
$output .= '<div class="stage">'.$row['id'].'</div>';
}
}
return $output;
}
Credits to Ayush!
Send array from php to AJAX response
You are getting empty array because you are passing name instead of id
change your <select>
as below:
<select class="district col-md-3 center-block" id="zone">
<?php
while ($res = mysqli_fetch_assoc($result_zones)) {
echo "<option value='".$res['id']."'>".$res['name']."</option>"; //<-----Add id instead of name
}
?>
</select>
Send array of files using AJAX
You have to send files as formData
var images = [image1, image2, image3]
var data = new FormData();
images.forEach(function(image, i) {
data.append('image_' + i, image);
});
$.ajax({
url: 'PHP/posts.php',
type: 'post',
data: data,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
location.reload();
}
});
But as you're reloading the page anyway, why use ajax at all ?
Passing JavaScript array to PHP through jQuery $.ajax
data: { activitiesArray: activities },
That's it! Now you can access it in PHP:
<?php $myArray = $_REQUEST['activitiesArray']; ?>
Related Topics
Finding the Subsets of an Array in PHP
PHP Json_Decode() Returns Null With Valid Json
Laravel View Not Found Exception
How to Replace Different Newline Styles in PHP the Smartest Way
PHP Image Upload Security Check List
Round Minute Down to Nearest Quarter Hour
Elegant Way to Search For Utf-8 Files With Bom
How to Only Allow Certain Filetypes on Upload in PHP
Does File_Get_Contents() Have a Timeout Setting
Run a PHP File in a Cron Job Using Cpanel
PHP Threading Call to a PHP Function Asynchronously
: Operator (The 'Elvis Operator') in PHP
PHP Library For Parsing Xml With a Colons in Tag Names