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 }
Related
i want to send a json data to my php but there is no response when i access it to my php.
this is my ajax request
var project = {project:"A"};
var dataPost = JSON.stringify(project);
$.ajax({
url: 'fetchDate.php',
data: {myData: dataPost},
type: 'POST',
datatype:'json',
contentType: "application/json",
success: function(data) {
alert(JSON.stringify(data));
}
});
});
and this is my php where i process the request and return back the data to test
<?php header("Content-Type: application/json; charset=UTF-8");
$objProject = json_decode($_GET["myData"]);
echo json_encode($objProject->project); ?>
i'm new to ajax so please i need your help
you don't need to add the content type on your ajax since you're not actually sending json to the server.
$.ajax({
url: 'fetchDate.php',
data: {myData: project},
type: 'POST',
datatype:'json',
// contentType: "application/json",
success: function(data, status, jqXHR) {
console.log(data,status,jqXHR);
alert(JSON.stringify(data));
}
});
no need to stringify project object,
in your php just encode it to json
<?php header("Content-Type: application/json; charset=UTF-8");
$obj = $_POST['myData'];
echo json_encode($obj); ?>
you should get json string on alert
Please try change
$objProject = json_decode($_GET["myData"]);
to
$objProject = json_decode($_POST["myData"]);
because ajax type : 'POST'
$.ajax({
url: 'fetchDate.php',
data: {myData: dataPost},
type: 'POST',
datatype:'json',
contentType: "application/json",
success: function(data) {
alert(JSON.stringify(data));
}
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);
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']);
}
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']);
I have a problem. I'm trying to send content of a textarea with an ajax call, but it doesn't seem to be working, and I don't know why.
There's the method called GetStatus(string statusText) which need to receive the content.
Here's the javascript code:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
$.ajax({
type: "GET",
url: "Default.aspx/GetStatus",
data: "{statusText:'" + statusText + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});
Please advise. You should also know that I'm new into web development.
You can't have a request body in a GET request, you have to use a POST request for that
The string you are constrcting is not valid JSON since:
Property names must be strings
You have no idea what the user will enter in the textarea - it might contain characters with special meaning in JSON
Generate your JSON programatically.
{
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify({
statusText: statusText
}),
// etc
Obviously, the server side of the process needs to be set up to accept a POST request with a JSON body (instead of the more standard URL Form Encoded format) as well.
Try this:
$("#btnSaveStatus").on("click", function () {
var statusText = $(".textareaEdit").val();
var jsonText = new Object();
jsonText.statusText = statusText;
$.ajax({
type: "POST",
url: "Default.aspx/GetStatus",
data: JSON.stringify(jsonText);,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// $('#littlbioID').text(result.d);
}
});
});