How to read array passed to php in async call - php

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

Related

angular-php: form data is empty in php

I am using angular as frontend and php as backend here is the code of angular.
$scope.processForm = function($scope.formData) {
console.log($scope.formData);
$http({
method : 'POST',
url : 'process.php',
data : {'data': $scope.formData,'uid':uid}, // no need to use $.param, even never see it in angular
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
here is the process.php
$postContent= file_get_contents("php://input");
$req= json_decode($postContent);
$formData= $req->formData;
$uid= $req->uid;
problem is $formData is empty in php. however $uid is showing value.
in form i have two entry email and password but i don't know how can i use that in php because formdata is empty.
I checked in firebug and found data is posting.
{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}:""
But nothing is coming response tab of firebug.
Assuming you call your function with something like ng-submit="processForm(formData)" then this is all you actually need
$scope.processForm = function(formData) {
$http.post('process.php', {
formData: formData, // note the key is "formData", not "data"
uid: uid // no idea where uid comes from
});
};
Where you have
$scope.processForm = function($scope.formData) {
isn't even valid JavaScript. You cannot use object dot notation in function argument names. That should have been throwing an error in your console.
You also appeared to be incorrectly setting your request content-type. You are sending JSON, not application/x-www-form-urlencoded formatted data. Angular's default POST content-type (application/json) is sufficient.
Try like this..
$json='{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}';
$req= json_decode($json);
$formData= $req->formData;
$uid= $req->uid;
$password = $req->formData->password;
$cpassword = $req->formData->cpassword;
OR convert into array using json_decode() with second argument as true.
$json='{"formData":{"password":"ff","cpassword":"errgreg"},"uid":"75"}';
$req= json_decode($json,true);//converts into array format
$formData= $req['formData'];
//print_r($formData);
echo $formData['password'];

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

json array to php

I have array in json, but I want to print it in php. I get in post this :
[{"cartData":{"id":"dragged_567737","left":"255px","top":"71px"}},{"cartData":{"id":"dragged_757836","left":"43px","top":"73px"}}]
but when I use print_r($_POST) in my php file, it print me the empty array.
there is my js code:
jQuery('#save_project_data').click( function() {
var array=[];
var numItems = $('.icart').length;
$(".icart").each(function(index) {
var cart_id = $(this).attr("id");
var cart_left = $(this).css("left");
var cart_top = $(this).css("top");
var cartData = {
"id" : cart_id,
"left" : cart_left,
"top" : cart_top
};
queryStr = { "cartData" : cartData };
array.push(queryStr);
});
var postData = JSON.stringify(array);
$.ajax({
url : "modules/cart_projects/saveData.php",
type : "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data : postData,//{ 'data': '{"name":"chris"}' }
traditional: true,
success: function(){
alert("OK");
}
});
return false;
});
PHP has native support for decoding JSON with json_decode();
$data = json_decode($_POST['myJson']);
print_r($data);
The PHP $_POST array is interpreted from key value pairs, so you need to change your ajax call like below, because your code is sending the post data with no key.
data : { myJson : postData },//{ 'data': '{"name":"chris"}' }
If you change the data structure like above, you need to also remove your application/json; charset=utf-8 content type.
From the Manual:
Takes a JSON encoded string and converts it into a PHP variable.
If you're sending raw JSON-strings to PHP, $_POST will not be populated (as it needs a standard urlencoded string as submitted by POST requests to decode). You can solve this by either using postData as an object: {'json': json}, so that you get the value in $_POST['json'], or by reading the raw response:
$json_string = file_get_contents('php://input');
$struct = json_decode($json_string, true);
Try to use json_decode() function.
According to jQuery.ajax() documentation:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
To be safe, you might be better off using the jQuery.post() method.
Finally, I suggest to give the data property an object. That way you can set an identifier for your post data.
Javascript
{
url: 'modules/cart_projects/saveData.php',
data: {
mydata: postData
}
}
PHP
$_POST['mydata'];
If you need to decode the JSON:
json_decode($_POST['mydata']);

Ajax and php - sending javascript array to 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'];

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.

Categories