How to grab php data from angularJS? - php

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

Related

Pass multiple base64 data array through Ajax to PHP script?

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);
}

Trying to save file using php and ajax

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?

Prevent PHP thumbnail generator response as in ajax

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);

Post a blob string to an API and save it as an image to a server [duplicate]

I'm trying to capture audiorecorder (https://github.com/cwilso/AudioRecorder) and send the blob through Ajax a php file, which will receive the blob content and create the file(the wave file in this case).
Ajax call:
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
$.ajaxFileUpload({
url : "lib/vocal_render.php",
secureuri :false,
dataType : blob.type,
data: blob,
success: function(data, status) {
if(data.status != 'error')
alert("boa!");
}
});
});
and my php file (vocal_render.php):
<?php
if(!empty($_POST)){
$data = implode($_POST); //transforms the char array with the blob url to a string
$fname = "11" . ".wav";
$file = fopen("../ext/wav/testes/" .$fname, 'w');
fwrite($file, $data);
fclose($file);
}?>
P.S:I'm newbie with blobs and ajax.
Thanks in advance.
Try uploading the file as form data
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
var data = new FormData();
data.append('file', blob);
$.ajax({
url : "lib/vocal_render.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert("boa!");
},
error: function() {
alert("not so boa!");
}
});
});
.
<?php
if(isset($_FILES['file']) and !$_FILES['file']['error']){
$fname = "11" . ".wav";
move_uploaded_file($_FILES['file']['tmp_name'], "../ext/wav/testes/" . $fname);
}
?>
According to the documentation, by using XMLHttpRequest.send() you can use the Blob object directly.
var blob = new Blob(chunks, { 'type' : 'audio/webm' });
var xhr = new XMLHttpRequest();
xhr.open('POST', '/speech', true);
xhr.onload = function(e) {
console.log('Sent');
};
xhr.send(blob);
I've tried this and it works like a charm.

AJAX POST return data not appearing

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.

Categories