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'];
Related
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']));
I want to send an array to PHP (POST method) using jQuery.
This is my code to send a POST request:
$.post("insert.php", {
// Arrays
customerID: customer,
actionID: action
})
This is my PHP code to read the POST data:
$variable = $_POST['customerID']; // I know this is vulnerable to SQLi
If I try to read the array passed with $.post, I only get the first element.
If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".
How can I get the complete array in PHP?
Thanks for your help.
To send data from JS to PHP you can use $.ajax :
1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.
JS:
var array = {
'customerID': customer,
'actionID' : action
};
$.ajax({
type: "POST",
dataType: "json",
url: "insert.php",
data:
{
"data" : array
},
success: function (response) {
// Do something if it works
},
error: function(x,e,t){
// Do something if it doesn't works
}
});
PHP:
<?php
$result['message'] = "";
$result['type'] = "";
$array = $_POST['data']; // your array
// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';
// now do what you want with your array and send back some JSON data in your JS if all is ok, for example :
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
Is it what you are looking for?
I am passing an object into a PHP script like this:
$http({
method: 'POST',
url: 'updateCoins.php',
data: {flips: $scope.data.flips, error: $scope.data.pe},
})
In my PHP script I tried:
$data = file_get_contents("php://input");
and
$data = json_decode(file_get_contents("php://input"));
I then tried echoing back the received value like this:
echo $data.flips
or
echo $data[flips]
or
echo $data->flips
I keep on getting either a blank result or the word "flips" back. How do I access those variables?
If the data was sent JSON-encoded, then it would make sense to json_decode(). I suspect that your data is x-www-form-urlencoded (eg: name=john&age=7). In this case, PHP parses it into the $_POST array for you. If you wish to do it on your own, and handle either case, you could do something like:
// Read content-type to determine whether it's JSON data
$type = $_SERVER["CONTENT_TYPE"];
$content = file_get_contents('php://input');
if(strpos($type,'json') > -1):
$data = json_decode($content, true);
else:
parse_str($content, $data);
endif;
print_r($data);
You can always visually inspect the data with echo file_get_contents('php://input');
Php won't grab the posted data from $_POST if the post is formatted in json. You can serialize the post data and submit it thusly
var data = 'flips='+$scope.data.flips+'&error='+$scope.data.pe;
$http({
method: 'POST',
url: 'updateCoins.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
});
OR you can do like BeetleJuice recommended. In my application I just do the following so that the rest of the code is uninterrupted.
if (empty($_POST) && file_get_contents('php://input')!==""){
$_POST = json_decode(file_get_contents('php://input'), true);
}
at which point you can access it with $_POST['flips'] and $_POST['error']
Im working on some AJAX login function, making a request via PHP.
I am wondering how do I return data via the PHP so that I can handle it like the code mentioned below. I only worked on the javascript side and not the PHP server side so I am confused now.
I want to get a value/values stored in the response like data.name , data.sessionID , data.listOfnames
Is the data a JSON Object by itself?
Thanks!
The code below was used before and has been verified to work.
function retrieveVersion(){
var URL = RSlink + "/updates";
$.ajax({
headers : {
"Content-Type" : "application/json; charset=UTF-8",
"sessionid" : result
},
type : "GET",
url : vURL,
statusCode : {
0 : function() {
hideLoadingMsg();
showError(networkError, false);
},
200 : function(data) {
currentVersion = String(data.version);
updatesArray=data.updates;
});
}
}
});
Suppose you have a php file for handling ajax calls. It should be available by this url - vURL.
In this file you need to create an array.
Something like this:
$data = array('data' => array('version' => yourversion, 'updates' => yourupdates));
Then you need to convert this object into json string. You can do this using json_encode() function
echo json_encode($data);
One thing to keep in mind: You need to echo your data and only. If somewhere in your file you will have some other echo-es, the result string returning to your ajax-funtion might be broken.
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']);