I have a PHP file in which I'm getting data from a geoJSON file, I'm going through the data and storing what I need in a new associative array, then sorting it. I need to make an AJAX call to this PHP file to get the sorted data through, but it's throwing "SyntaxError: Unexpected token a in JSON at position 0", the "a" being "a"rray... from the response, so I believe it's going through as a string.
My PHP file:
<?php
$countryBordersJson = file_get_contents("../js/countryBorders.geojson");
$countryBordersJsonData = json_decode($countryBordersJson, true);
$dataLength = count($countryBordersJsonData['features']);
$countryNames = array();
for($i = 0; $i < $dataLength; $i++) {
$countryName = $countryBordersJsonData['features'][$i]['properties']['name'];
$countryIsoa2 = $countryBordersJsonData['features'][$i]['properties']['iso_a2'];
$country[$i]['countryName'] = $countryName;
$country[$i]['iso_a2'] = $countryIsoa2;
array_push($countryNames, $country[$i]);
}
sort($countryNames);
$data = json_encode($countryNames);
$decode = json_decode($data, true);
$output['status']['code'] = "200";
$output['status']['name'] = "ok";
$output['status']['description'] = "success";
$output['data'] = $decode;
header('Content-Type: application/json');
var_dump($output);
?>
My AJAX request:
$.ajax({
url: "libs/php/countryBorders.php",
dataType: "json",
type: "GET",
success: function(result) {
console.log(result);
},
error: function(jqXHR, textStatus, errorThrown) {
console.warn(jqXHR.responseText, textStatus, errorThrown);
}
})
I'm still getting to grips with JSON, PHP etc. so would appreciate any help.
Are you sending the data with var_dump ? It cannot work like that. You need to send a string :
echo json_encode($output);
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);
}
Need to save some big data to file on server
"/php/test.php":
<?php if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = mktime() . ".txt";
$file = fopen("upload/" .$fname, 'w');
fwrite($file, $data);
fclose($file);
}
?>
jquery:
var data = 'foo bar';
$.ajax({
url: 'php/test.php',
type: 'POST',
data: { data: data },
success: function(result) {
alert('the data was successfully sent to the server');
}
});
result:
405 (HTTP method POST is not supported by this URL)
what's the problem?
I am trying to upload an image through ajax and needs to get the image URL as response.
code below..
$(".filupldt").on('change',function(){
var file_data=$(this).prop("files")[0];
var form_data=new FormData();
form_data.append("file",file_data);
form_data.append("type",$(this).prev().prev().val());
form_data.append("primerkey",$(this).prev().val());
var element = this;
$.ajax({
type:'POST',
mimeType: 'multipart/form-data',
url:'includes/dealerimg.settings.php?operation=savedealerimgeqtype',
dataType:'json',
async:false,
processData: false,
cache: false,
contentType: false,
data:form_data,
success:function(response){
console.log(response);
//$(element).parent().prev().prev().attr('src',response);
},
});
});
PHP Ajax function
$createthumb = new createthumb();
$todburl = $this->url;
$ajaxtype = $_POST['type'];
$uploads_dir = "../assets/equipmenttype/";
$uniid = uniqid();
$now =date('Y-m-d H:i:s');
$pkid = $_POST['primerkey'];
$ext =pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$filename = $pkid."_".$DealerID."_dealerupdate";
$thumbnamer = $pkid."_".$DealerID."_thumb_dealerupdate_".$uniid.".".$ext;
$tmpname = $_FILES['file']['tmp_name'];
$imagename = $_FILES['file']['name'];
$loc_thumb = $uploads_dir.$thumbnamer;
$createthumb->create_thumb_with_ratio($tmpname,300,300,$loc_thumb); //CREATING THUMB
$createthumb->upload_original(1,$filename,$imagename,$tmpname,$uploads_dir);//for upload original
$thumnametodb = $thumbnamer;
$orinametodb = $filename."_".$imagename;
$data = ['dddd'=>$todburl."assets/equipmenttype/".$thumbnamer];
header('Content-Type: application/json');
echo json_encode($data);
This function working perfectly and creating thumb in my required folder.
But this is an ajax page and I want to show the image name as response.
In this case the ajax response is like below attached image.
How can i solve this issue ?
Thanks
You said that you want to show the image name as response :
Then just
echo $_FILES['file']['name'];
then in your script you get the image name as response with :
success:function(response){
console.log('Image Name = '+response);
}
Your current response is JSON representation (json_encode($data)) & not the image's name.
Probably some output is braking the response data. To be sure that nothing prints on the response page try putting ob_start() and ob_end_clean()
ob_start();
//...
// your code here
//...
$data['dddd'] = $todburl."assets/equipmenttype/".$thumbnamer;
ob_end_clean();
echo json_encode($data);
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
JQuery
function save() {
imageData = $(".sigPad").signaturePad().getSignatureImage();
consumeData = $('#consume').val();
$.ajax({
type: "POST",
url: "",
data: {'signatureasimage' : imageData, 'consume' : consumeData },
dataType: 'json',
cache: false,
success: function(response){
alert(response.msg);
/*var imageUrl = response['signature_image'];
d = new Date();
$(".signatureImage").attr("src",imageUrl);
if (response.status == true) {
window.location.href = "<?php echo ROOT_URL.'esignup/attendees_list.php?icode='.$icode;?>";
}*/
},
error: function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
};
PHP
$data = array();
$confirmationData = array();
$data['attendee_id'] = $attendeeId;
$data['is_consume_the_provided_meal'] = $_POST['consume'];
$data['signature_image'] = $destination;
$data['confirmed'] = 1;
if($confirmedAttendee){
$sql = "SELECT * FROM `".TBL_ATTENDEE_CONFIRMATION."` WHERE `attendee_id` = '.$attendeeId.'";
$confirmationData = selectFrom($sql);
update_array('tbl_attendee_confirmation', $data, array('attendee_id' => $attendeeId));
$confirmationData = selectFrom($sql);
}else{
var_dump("it went through insert array");
insert_array('tbl_attendee_confirmation', $data);
}
$data = array();
$data['msg']="Testing, testing.";
echo json_encode($data);
Jquery ajax does post request with data imageData and consumeData. imageData and consumeData are strings. Copying to file works and the data updates the table. The problem is I get parsererror when I want to get imageUrl so I can update the sigImage with the new image source. I commented the part where I replace the image src with new imageURL. Does anyone know the issue?
Error shows up as "alert('Error.\nParsing JSON Request failed.');" from code. Error still shows up with test code.
Try doing this in your PHP:
echo json_encode($data, JSON_FORCE_OBJECT);
I don't completely understand it, but in my experience if you are returning an array you've built in PHP to be parsed using the ECMAScript JSON object, you need to use the JSON_FORCE_OBJECT constant to ensure that it returns a JSON object instead of a JSON array.
json_encode constants
You also could try outputting the header for JSON before echoing your JSON encoded array, gimme a sec.
header('Content-Type: application/json');
Also here