Retrieving objects from JSON using PHP - javascript

I need to send some data stored in IndexedDB to server for some back-end manipulation. The needed data is fetched to a variable payLoad in javascript using JSON.stringify().
payLoad = "[{"synch":0,"id":-1,"name":"Tester","email":"test#example.com","created":"2014-08-20T07:56:44.201Z"}]";
$.ajax({
type: "POST",
url: "process.php",
data: payLoad, // NOTE CHANGE HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert('error');
}
});
Can I parse this JSON data to a PHP class?

This way, you're just sending JSON raw in the body. Try this:
$data = json_decode(file_get_contents('php://input'));
If, on the other hand, you send data with this:
data: { data: payLoad },
Then you can simply do
$data = json_decode($_POST['data']);

Related

sending base64 image to server through ajax

I have build a image cropper tool from there i wanted to store that base64 image to server. I have sent it through Ajax. Image got stored in jpg format.But the problem is it's got corrupted. Can anyone suggest me what could be the solution?
Here is my ajax call :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method: 'post',
url: 'updateProfilePicture',
cache: false,
contentType: "application/json; charset=utf-8",
data: {'image': encodeURIComponent(profileImageUrl)},
success: function (data) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
Here is the controller for converting base64 to normal image and stored to server:
public function updateProfile(Request $request)
{
$base64img = str_replace('data:image/jpeg;base64,', '', $request->Input(['image']));
$data = base64_decode($base64img);
$file = public_path() . '/users/' .'123123123.jpg';
file_put_contents($file, $data);
return \Response::json($data);
}
You aren't sending JSON so don't claim you are sending JSON. Remove this.
contentType: "application/json; charset=utf-8",
You are passing an object to data:
data: {'image': encodeURIComponent(profileImageUrl)}
When you pass an object, jQuery will encode it as form URL encoded data.
By running your code through encodeURIComponent you cause the data to be double encoded.
Don't do that.
data: {'image': profileImageUrl }

Why is my JQuery variable not sending to php?

I have a variable which contains data, i'm then using a ajax function to send this variable data to this php file. I'm slightly unsure I can store this variable into php and echo it out. This is the code that I currently have...
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: data,
success: function(data) {
alert ( data );
}
});
This is my php code
$noteone = $_POST['data'];
echo $noteone;
Any help would greatly be appreciated
data of your ajax call should be like below. Hope it will solve your problem.
data: { "data": data }
You also need to set the data type:
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: { "data": data },
dataType: "json", // <---- THIS ONE
success: function(data) {
alert ( data );
}
});
Try this :
var data = 1
// Sending this data via ajax to php file/
$.ajax({
type: 'post',
cache: false ,
url: 'function.php',
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
alert ( data );
}
});
PHP requires data to be submitted in key=value format when building $_POST/$_GET. You didn't do that. You only submitted value, so PHP has no key to populate $_POST with. You need to have:
data: { "whatever_you_want": data }
which becomes
$_POST['whatever_you_want']

JS array send to php is returning as empty [duplicate]

Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);

Ajax JSON access array from the array JSON encode server respond

I have an array JSON encode respond when the ajax JSON throw a post request (refer below).
requestparser.php:
$array = array("phweb" => "yes", "phemail" => "yeeess");
echo json_encode($array);
And this Ajax JSON use for sending post request to requestparser.php and processing the return response.
$.ajax({
type: 'POST',
url: 'requestparser.php',
data: { "request" : "pull" },
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
alert(result[1]);
}
});
I want to get the value of array key phweb and the value of array key phemail yet when an alert box popup, it says undefined. What seems the problem? Any help, ideas, clues would be greatly appreciated.
So far what I tried is:
$.ajax({
type: 'POST',
url: 'requestparser.php',
data: { "request" : "pull" },
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]->phweb);
alert(result[1]->phemail);
}
});
And sadly, it doesn't work.
The result is a JSON object. You can access it like this
success: function(result) {
alert(result['phweb']);
alert(result['phemail']);
}

Sending Multidimentional array data, with ajax, to a php script

I have two simple scripts. One client-side jquery that has multidim array & a server-side php script. in php $data stays empty.
jquery
console.log("IN JQUERY");
console.log(inps);
$.ajax({
type: 'post',
cache: false,
url: './gen.php',
data: inps,
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
gen.php
<?php
$data = file_get_contents('php://input');
$data = json_decode($data, true);
print_r($data);
?>
firefox console output
>POST ..././gen.php [HTTP/1.1 200 OK 1ms]
>"IN JQUERY"
>{isbranch: "1", ismanager: "0", isdept: "1"}
>"RESPONSE"
>""
Is there a way to send Multi Dimensional array to the php with ajax without spliting array?
You should use JSON.stringify to encode your data before send it, also better to add correct contentType to it:
$.ajax({
type: 'post',
cache: false,
url: '/gen.php',
data: JSON.stringify(inps),
contentType: 'application/json',
success: function(response){
console.log("RESPONSE");
console.log(response);
}
});
The key-value pairs should already exist in your $_POST
$isbranch = $_POST['isbranch'];
$ismanager = $_POST['ismanager'];
$isdept = $_POST['isdept'];

Categories

Resources