Ajax and php - sending javascript array to php - php

i try to send data to my php scripts but i think i miss something.
First of all,
function deleteData2()
{
var artistIds = new Array();
$(".p16 input:checked").each(function(){
artistIds.push($(this).attr('id'));
});
$.post('/json/crewonly/deleteDataAjax2', JSON.stringify({'artistIds': artistIds}),function(response){
if(response=='ok')
alert(artistIds);
});
}
Above code is my js file. i have artistIds in var artistIds. My goal is sending this array to my php script.In order to that, i make it json , i mean encode it with JSON.stringify
then in php side, i use below code.However, $array is always null. What might be the reason ?
public function deleteDataAjax2() {
$array=json_decode($_POST['artistIds']);
if (isset($array))
$this->sendJSONResponse('ok');
}

You are passing the data as a raw string of JSON, but your PHP is trying to find that string by parsing the data as application/x-www-form-urlencoded and then looking at the artistIds key.
Assuming the array is flat: Forget JSON. You don't need it.
$.post('/json/crewonly/deleteDataAjax2', {'artistIds': artistIds},function(response){
And:
$array = $_POST['artistIds'];
If the array isn't flat, then:
$.post('/json/crewonly/deleteDataAjax2',
{ json: JSON.stringify({'artistIds': artistIds}) },
function(response){
And (with suitable error checking added):
$json = $_POST['json'];
$data = json_decode($json);
$artists = $data['artistIds'];

Related

How to read array passed to php in async call

I have the following in a js script:
let skippers = {};
for(let i = 0; i < skipperIds.length;i++){
skippers[skipperIds[i].value] = skipperIds[i].checked;
}
regData.skippers = skippers;
responseData = sendData2('https://sailwbob.com/lagin/public/register.php',regData);
where sendData2 is an async call using axios. skippers looks like
{1:true,20:false}
In my php file I have:
$skippers = ($_POST['skippers']);
$skipperIds = array_keys($skippers);
$skipperValues = array_values($skippers);
but this is not working. I think php converts an array in $_POST to a string but I'm not sure.
two qustions:
how do I convert $skippers back to an array?
I've been trying to use print_r to see the data on the server but as this is an async call it's not working as the print_r results are being sent back to the js script and not printing out on the screen. Is there a way to see the results of print_r?
Update:
I tried $x=json_decode($_POST); but got an error saying it was expecting a string.
here's the call to axios:
function sendData2(url,emailPass){
let bodyFormData = new FormData()
for (const [key, value] of Object.entries(emailPass)) {
//console.log(key,value)
bodyFormData.append(key,value)
}
return axios({
method: 'POST',
url: url,
data: bodyFormData,
headers: {'Content-Type': 'multipart/form-data'}
})
.then(function(response){
return response.data
})
.catch(function(response){
return response
})
}
update2:
$skippers shows $skippers = [object Object]. Is there a way to send this to the server correctly?
As discussed in this article, axios serializes Javascript objects to JSON and becase PHP doesn't support JSON as a data format for populating $_POST, you can retrieve them in PHP like this:
$_POST = json_decode(file_get_contents("php://input"),true);
$skippers = $_POST['skippers'];
While axios does automatically stringify data it apparently doesn't do that for nested arrays. I needed to add:
regData.skippers = JSON.stringify(skippers); in my js
and then in the php file
$skippers = get_object_vars(json_decode($_POST['skippers']));

Could use some advice on jQuery each function on a associative multidimensional array

I'm working on a jQuery .get that will send a value to the server to compare against an array which will then get encoded into a json format as the responses. Below is the code (jQuery and PHP zend). I'm not sure if my problem is with identifying the keys and values or if it is the syntax. Is there away to view the raw json data echoed by my php controller?
$.get(
"/ed/macro",
{value: singleValues},
function(data) {
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
$('#stage').html("data");;
});
});
},"json");
$select = $this->getDbTable()->select();
$select->from('sub');
$resultSet = $this->getDbTable()->fetchall($select);
$data = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Subdiscipline();
$entry->setIdSub($row->idsubdiscipline)
->setSub($row->subdiscipline)
->setDescription($row->description);
$data[] = $entry;
}
return $data;
}
public function macAction()
{
$request = $this->getRequest()->getParam('value');
// acti
$sub = new Application_Model_Sub();
$fetch = $sub->fetchAll($request);
$jsonObject = Zend_Json::encode($fetch);
echo $jsonObject;
// action body
}
To view the object print_rin PHP and console.log in Javascript. Or as Sam said, after the JS has called it, look in Net to see what was sent.
Assuming that you are echoing a json string after telling your server to tell the browser it is json with header("Content-type: application/json"); your problem is probably here
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
data.value1 isn't what you're dealing with there, it's value1. I'm assuming value1 IS an array, and you're picking the first element in it value1[0] to then iterate?
$.each(data, function(key,value1){
$.each(value1[0], function(key,value2){
Or maybe you're after
$.each(data, function(key,value1){
$.each(value1, function(key,value2){
Please echo the object and show it to us.

How to access all elements in an array from php that is passed by an ajax call?

I am finding difficulty in accessing elements in an array from php file. The array is passed through an ajax call. Please find below the ajax call.
var data = ['test1', 'test2', 'test3'];
$(document).ready(function () {
$("button").click(function () {
$.ajax({
type: "POST",
url: "getResult.php",
data: {
testData: data
},
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
return false;
});
});
The server side [PHP] code is
$myArray = $_POST["testData"];
echo $myArray;
However $myArray always returns last element[test3 here] in the array. How do I access first [here test1] and other elements?
Pls help.
What you need to do is convert the JavaScript array to JSON and then send over that JSON.
On the PHP side you should decode the JSON back into an array. Finally, you should re-encode the array as JSON before sending it back.
On your client side change one line:
data: {testData : JSON.stringify(data)},
On your server side do:
$myArray = json_decode($_POST["testData"]);
header('Content-Type: application/json');
echo json_encode(array('pheeds' => $pheeds, 'res' => $res));
JS:
JSON.stringify(data)
PHP:
$myArray = json_decode($_POST['data']);
For simple structures you can use jQuery Param
data : $.param({testData:data})
With this you should be able to access your data with
echo $_POST["testData"][0]...[2];
Try this when passing JS vars by ajax.
use Firebug to see on the console what is being poted to the PHP file, this will save you a lot of trouble.
you will see that array is an OBJECT , So you want to send this array as a JSON / STRING to the PHP file.
use :
var data = ['test1','test2','test3'];
data = JSON.stringfy(data);
at the PHP:
$data = var_post('test_data');
$data=json_decode($data);
$print_r($data);

Sending JSON via AJAX to PHP using jQuery

I am trying to send JSON to a PHP file using jQuery AJAX, basically what I am trying to do is get the values and id's of a bunch of child elements and then assign them to a JSON object and then send that object via ajax to the PHP file which would then process it and enter it into a database.
Here is my code,
Javascript/jQuery:
function test(){
var selects = $('#systems_wrapper').find('.dropDowns');
var newArray = new Array();
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
var o = { 'id': id, 'value': val };
newArray.push(o);
});
$.ajax({
type: "POST",
url: "qwer.php",
dataType: 'json',
data: { json: newArray }
});
}
PHP:
<?php
$json = $_POST['json'];
$person = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $person);
fclose($file);
echo 'success?';
?>
It creates the file, but it is completely blank, any idea what it could be?
Thanx in advance!
You could try using the JSON.stringify() method to convert your array into JSON automagically. Just pass the output from this.
data: { json: JSON.stringify(newArray) }
Hope this helps
Don't use an array.
use a simple string like this:
var o = '[';
selects.each(function(){
var id = $(this).attr('id');
var val = $(this).val();
o += '{ "id": "'+id+'", "value": "'+val+'" },';
});
o = o.substring(0,o.length-1);
o += ']';
and in the ajax just send the string 'o'
data: { json: newArray }
in the php file just make a json_decode($json, true);
it will return an array of array that you can access by a foreach
if you want to see the array, use var_dump($person);
You should set a contentType on your ajax POST. I would use contentType: "application/json";
You should use json_encode() not json_decode()! This way you will get the json string and be able to write it.
No need to use json_decode if you're saving it to a text file. jQuery is encoding your array in JSON format, PHP should then just write that format right to the text file. When you want to open that file and access the data in a usable way, read its contents into a variable and THEN run json_decode() on it.

Unable to get posted array from jQuery

I am trying to post a group of arrays using the jQuery post method, but I am having trouble getting the value of the arrays. How can I get the values of the array that I have sent?
If somebody could help me i would be grateful....
Here is what i have done:
$(document).ready( function()
{
$("#submit_info").click (
function()
{
var batchArr= new Array();
batchArr=arrPush('batch');
var facultyArr= new Array();
facultyArr=arrPush('faculty');
var levelArr= new Array();
levelArr=arrPush('level');
var sectionArr= new Array();
sectionArr=arrPush('section');
var shiftArr= new Array();
shiftArr=arrPush('shift');
$.post("server_side/college_info_insert.php",{
batchArr:batchArr,
facultyArr:facultyArr,
levelArr:levelArr,
sectionArr:sectionArr,
shiftArr:shiftArr
}, function(data)
{
alert(data);
});
}
);
function arrPush(opt)
{
var Arr= new Array();
Arr.push($("#"+opt+"_1").val());
var count= $("#"+opt).val();
var i=0;
for(i;i<=count;i++)
{
if(i==0)
{
Arr.push($("#txt"+opt).val());
}
else
{
Arr.push($("#txt"+opt+i).val());
}
}
return Arr;
}
}
);
How can I get the array values in the next page "college_info_insert.php" ??
okay, so this is actually a really common issue. It's unclear that you can't just send an array as-is from javascript to PHP and have it recognized.
The problem is that PHP doesn't know how to read in multiple values from a POST request - typically things like that require the PHP author to use brackets like: varname[].
So, basically you must send variables as strings. Using JSON you can send even complicated objects as strings to PHP using a single variable name. Typically you'd use JSON.stringify or something along those lines - but if you have a simple array you might not even need it.
Here's a full example of the problem/solution, found using jquery and $.post:
Asume you have a file myurl.php:
<?php
print_r($_POST);
?>
And in a separate file (or the console), you try:
var myarray = Array('some','elements','etc');
var mydata = {postvar1: 'string', postvar2: myarray};
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
This doesn't work! The result is that postvar2 only contains "etc".
The solution is force the array into a JSON string that can be decoded from PHP.
var myarray = Array('some','elements','etc');
var json_array = $.map(myarray,function(n) {
return '"'+n+'"';
});
var mydata = {postvar1: 'string', postvar2: '['+json_array+']' };
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
ON the PHP side you now must use: json_decode($_POST['myarray']); to get your results in a proper array.
Note, this example assumes very simple strings or numbers in your array. If you have complex objects, you will need to use a JSON.stringify function which will take care of extra quotes, escaping special characters, etc.
Not sure if i understood the question but wouldn't something like this work
if (isset($_POST['batchArr'])) {
$batchArr = $_POST['batchArr'];
// Then populate your html here e.g
echo $batchArr[0];
}

Categories