i am stuck with this for quiet sometime now.
all i am trying to do is send a json text to php, process it and send a response bacl..
here is the data i am sending as my textarea value..
**asdasd #$**&**%^*( AAAA SADQWEASD /// '' \\\ '' l; "" **
below is the json sent to php (got it from console):
data={"Text":"asdasd #$&%^*( AAAA SADQWEASD /// '' \\\\\\ '' l; \"\" "}
i am using jquery ajax function as below:
function ajaxfunc(data, path){
$.ajax({
type: "POST",
url: path,
data: 'data='+data,
success: function(response){
}
});
}
in php, i am doing this.
$res = json_decode(stripslashes(escapeJsonString($_POST['feed'])), true);
function escapeJsonString($value) {
# list from www.json.org: (\b backspace, \f formfeed)
$search = array("\n", "\r", "\u", "\t", "\f", "\b", "/", '"');
$replace = array("\\n", "\\r", "\\u", "\\t", "\\f", "\\b", "\/", "\"");
$result = str_replace($search, $replace, $value);
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
echo $res["Text"];
issue is : & .. is not getting parsed at php and hence the response is null..
i also wanted to make sure, the new line characters are detected.. basically i am expecting "WYSIWYG" using json.. json_encode and json_decode
Based on the comment about just wanting to send form inputs to the server, use serialize() in the following way:
$.ajax({
type: "POST",
url: path,
data: $('form').serialize(),
success: function(response){
}
);
If all you want to do is access the form inputs on the server through the $_POST array then converting to JSON on the client is a waste of effort. serialize() should work perfectly for you.
But if you really want to use a JSON then use the JSON-js lib by Douglas Crockford here. Note that there is a lot of other info on this topic: Serializing to JSON in jQuery. Example below:
$.ajax({
type: "POST",
url: path,
data: 'data='+( JSON.stringify(data) ),
success: function(response){
}
);
if you want to send a data in JSON format, you can try this
data = {"Text":"asdasd #$&%^*( AAAA SADQWEASD /// '' \\\\\\ '' l; \"\" "};
data = JSON.stringify(data);
then send with your jquery.ajax or jquery.post
Related
I am passing single base64 string as of now,but Now I need to pass multiple base64 string and sent through PHP script to the server.
as of now my code send only single data
$imagebase64 //it contains base64 array like -['data:image/jpeg;base64,/9j/4A','data:image/jpeg;base64,/9j/4A']
$("#downloadAll").click(function () {
$.ajax({
type: "POST",
url: "imageUpload.php",
data: {
// Sending single as of now
base64Img: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAADâĤ1jSchh2MkeFK5Anv7fbTv5SKFqOFdOvm764mRVLQgtO8RoP/Z",
},
contentType: "application/octet-stream",
error: function (err) {
console.log("There was an error. Try again please!", err);
},
success: function (msg) {
console.log(msg);
},
});
});
PHP Script
$base64string = $_POST['data'];
$uploadpath = 'image-cropper';
$parts = explode(";base64,", $base64string);
$imageparts = explode("image/", #$parts[0]);
$imagetype = $imageparts[1];
$imagebase64 = base64_decode($parts[1]);
$file = $uploadpath . uniqid() . '.jpeg';
file_put_contents($file, $imagebase64);
After Updated Code as suggested-
Notice: Undefined index: data in /var/www/html/image-cropper/imageUpload.php on line 1
and empty array() posted to upload.php
Ajax call:
$("#downloadAll").click(function () {
var imagebase64 = "<?= $imagebase64 ?>";
$.ajax({
type: "POST",
url: "imageUpload.php",
data: { imagesBase64: JSON.stringify(imagesBase64) },
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log("There was an error. Try again please!", err);
},
success: function (msg) {
console.log(msg);
},
});
});
PHP:
$base64string = $_POST['data'];
$uploadpath = 'image-cropper';
$parts = explode(";base64,", $base64string);
$imageparts = explode("image/", #$parts[0]);
$imagetype = $imageparts[1];
$imagebase64 = base64_decode($parts[1]);
$file = $uploadpath . uniqid() . '.jpeg';
file_put_contents($file, $imagebase64);
As I understand by your first code - your array has base64 data which is already in strings so no need to convert it again.
$("#downloadAll").click(function () {
$.ajax({
type: "POST",
url: "imageUpload.php",
data: { data: imagesBase64 },
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
});
As I saw your PHP script has a lot of issues, it was made only to handle a single item, you need to iterate over the array too.
$data = ($_POST['data']);
foreach($data as $base64_string ){
$filename_path = md5(time().uniqid()).".jpeg"; //use png or jpg if required
$base64_string = str_replace('data:image/jpeg;base64,', '', $base64_string);
$base64_string = str_replace(' ', '+', $base64_string);
$decoded = base64_decode($base64_string);
//defining path
file_put_contents("image-cropper".$filename_path,$decoded);
}
I've been able to sent FormData from angularJS to php, but I don't know how to do the reverse. I'm currently trying to get the $base64 variable into my angularJS, but I'm quite stumped on how to go about doing so. The documentation in the official angularJS doesn't help me much either
https://docs.angularjs.org/api/ng/service/$http
JS
$scope.MakeGray_Button = function(){
if ($scope.imageUrl) {
var MakeGray_Form = new FormData();
MakeGray_Form.append("FileName", $scope.imageUrl);
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(){
// some magic code here that grabs the $base64 variable from php
})
.error(function(){});
}
else{
alert("Please upload an image");
}
}
PHP
<?php
$imgname = $_POST["FileName"];
$inputDir = "../../uploads/" . $imgname;
$outputDir = "../../processed/" . $imgname;
$MakeGray = "./makegray " . $inputDir . " " . $outputDir;
$runExec = exec($MakeGray, $out);
$type = pathinfo($outputDir, PATHINFO_EXTENSION);
$data = file_get_contents($outputDir);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo "$base64";
?>
You can add a parameter in success callback to fetch the response from server if available.
var base64 = '';
$http({
method : "POST",
url : "../opencv/MakeGray/MakeGray.php",
data : MakeGray_Form,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).
success(function(response){
base64 = response; //response will contain whatever server echos to it's standard output
})
.error(function(){});
you can get the response from server by using
.then(function (data) {}
and in "data" variable you can find the value you're looking for
i want to post a json object to php.
var user = {username:"test", password:"test", name:"test",
email:"test#hotmail.com"};
var str_json = JSON.stringify(user);
$.ajax({
url: '/register_API.php',
type: 'post',
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log('success');
},
data: user
});
}
In php i want to insert it into mysql:
$data = file_get_contents('php://input');
$json = json_decode($data,true);
$username = $json['username'];
$password = $json["password"];
$email = $json['email'];
$insertSql = "INSERT INTO users (username, password, email)
VALUES ('$username', '$password', '$email');";
The $data string contains: username=test&password=test&name=test&email=test%40hotmail.com, but i can't get the variable by decoding...
Thanks in advance!
Change data: user to data: str_json and then
change $data = file_get_contents('php://input');
to $data = $_POST['data']
You're not sending a JSON string, you're sending a Javascript object which jQuery is translating to a set of parameters in the outgoing POST request. Your data will be available to PHP in $_POST - no need to decode it first.
Look for it like this:
$username = $_POST['username'];
$password = $_POST["password"];
$email = $_POST['email'];
I think you want to send raw JSON as text and have that be in the post body and not treated as an encoded form.
In this case I think your PHP code is right. Send the stringified JSON as you are, but set the data type to dataType: "text".
I think you will be able to read it with
$data = file_get_contents('php://input');
I think you can use
//works like explode, but splits your data where finds "=" and "&" too.
$output = preg_split( "/ (=|&) /", $data);
This will return an array of your data. where:
$output[0]="Username";
$output[1]="test";
This can be useful if you have fixed data.
I have an AJAX call which runs on a form submit (with prevent default to stop standard submit):
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize()
}).done(function(data) {
$('#processingFile').hide();
$('#downloadFile').show();
$('#shareURL').val(data.url);
$('#downloadFile').attr('href', data.url);
$('#aboutFile').html('<b>File URL:</b> ' + data.url + '<br /><b>File Size:</b> ' + data.size + '<br /><b>Time Stamp:</b> ' + data.timestamp + '<br /><b>Client IP:</b> ' + data.ip);
}).fail(function() {
$('#saveFile').hide();
$('#error').show();
});
The file it submits to is a PHP file which is as follows:
// VARIABLES
$fileURL = $_POST['fileURL'];
$tmpURL = substr(md5(rand()), 0, 7);
$deleteCode = md5($tmpURL);
// COOKIE
setcookie($tmpURL, $deleteCode, time()+86400);
// SAVE FILE
if($fileURL){
file_put_contents("tmp/" . $tmpFile, file_get_contents("http://" . $fileURL));
}
// OUTPUT
$result = array(
'url' => "tmp/" . $tmpFile,
'size' => filesize("tmp/" . $tmpFile) * .0009765625 * .0009765625,
'timestamp' => date('H:i:s d-m-Y'),
'ip' => $_SERVER['REMOTE_ADDR']
);
echo json_encode($result);
When the script is run everywhere which uses data.x in the jQuery returns undefined. Any idea why that happens and how to fix it?
data is a string containing your returned JSON text; it isn't an object.
To parse the JSON object, you have a couple of options:
Call JSON.parse() yourself.
Pass dataType: "json" to tell jQuery AJAX to parse it for you.
Set Content-Type: application/json in the server's response so that jQuery knows to parse it for you.
Set dataType: 'json' and check! Look this doc and set your datType.
I am just starting to learn JSON where a tutorial from other site uses this code (which I already modified to simplify this):
$(document).ready(function(){
$('#getdata-button').click(function(){
$.ajax({
type: "GET",
url: "json-data.php",
dataType: "json",
success: function(){
alert('a');
$('#showdata').html(
"<p>item1="+data.item1+
" item2="+data.item2+
" item3="+data.item3+"</p>"
);
}
});
});
});
And this is the code for json-data.php
<?php
$item1 = "candy";
$item2 = "chocolate";
$item3 = "ice cream";
//return in JSON format
echo "{";
echo "item1: ", json_encode($item1), "\n";
echo "item2: ", json_encode($item2), "\n";
echo "item3: ", json_encode($item3), "\n";
echo "}";
?>
The problem is that alert function (for debugging purposes) isn't responding after I have clicked the button (with the id of "getdata-button"). Firebug says that the request is successful and I can see the data from there. No error was found. It is just the callback function is not executing, but why?
You need to output your JSON correctly. Replace your PHP with the below
$items = array(
'item1' => $item1,
'item2' => $item2,
'item3' => $item3
);
header('Content-type: application/json');
echo json_encode($items);