PHP echo jQuery AJAX request - javascript

This is my jQuery request to upload an image file
$('#upload-image').change(function(e){
var file = e.target.files[0];
var imageType = /image.*/;
if (!file.type.match(imageType))
return;
console.log(file);
var form_data = new FormData();
form_data.append('file', file);
console.log(form_data);
$.ajax({
url: 'http://localhost/upload.php',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'POST',
success: function(response){
console.log(response);
},
error: function(error){
console.log(error);
}
});
});
This is upload.php on local webserver
<?php
header('Access-Control-Allow-Origin: *');
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['file']['name'];
echo $target_path;
}
?>
When I upload the image and send request. It returns and logs for me complete code lines of upload.php, not the result from echo command line that I want. I check console Network tab and see that the response is nothing except complete code of upload.php. It truly does not handle anything server-side. What did I do wrong?

You need to make sure that PHP runs server-side. If there's no PHP handler installed, the server will return the content of your upload.php file as text. I think that's your primary problem.
Based on your platform, you may try:
http://www.wampserver.com/en/ (windows)
https://www.digitalocean.com/community/tutorials/how-to-install-linux-apache-mysql-php-lamp-stack-on-ubuntu-14-04 (Ubuntu)
https://www.mamp.info/en/ (MacOS)
First of all make sure your PHP works, by creating a file called info.php in your webroot folder with the following content
<?php
phpinfo();
This should display your configuration. Then you can start debugging the Javascript. The content type should by multipart/form-data so that the server knows it expects an upload.
Good luck!

Related

Using an AJAX call to display base64 image data via PHP

I'm wanting to render an image using an AJAX call but I’m having trouble returning an image from the server as a base24 string via PHP.
In the renderImage function below the test image data 'R0lGODlhCw...' is displaying correctly but the image data coming from the AJAX call is not.
I want to use AJAX instead of just outputting the image file contents into the src attribute because I eventually want to add authorization headers to the PHP file.
I think I’m missing something in the PHP file and some headers in the ajax call?
PHP file: image.php
<?php
header("Access-Control-Allow-Origin: *");
$id = $_GET["id"];
$file = '../../upload/'.$id;
$type = pathinfo($file, PATHINFO_EXTENSION);
$data = file_get_contents($file);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
return $base64;
?>
JS
function renderImage(id) {
//return "R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
return $.ajax({
url: '[server URL]/image.php',
data:{"id":id},
type: 'GET',
});
};
$('.feedImage').each(async function() {
try {
const res = await renderImage($(this).data("id"));
$(this).attr("src","data:image/gif;base64," + res);
} catch(err) {
console.log("error"+err);
}
});
raw image obtained from How to display an image that we received through Ajax call?
First you should fix your php image rendering
<?php
header("Access-Control-Allow-Origin: *");
$id = $_GET["id"];
$file = '../../upload/'.$id;
$type = pathinfo($file, PATHINFO_EXTENSION);
$data = file_get_contents($file);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);
echo json_encode(array('id' => $base64));
?>
Then your javascript, as you already defined the data image type there is no need to repeat it on the javascript.
function renderImage(id) {
//return "R0lGODlhCwALAIAAAAAA3pn/ZiH5BAEAAAEALAAAAAALAAsAAAIUhA+hkcuO4lmNVindo7qyrIXiGBYAOw==";
return $.ajax({
url: '[server URL]/image.php',
data:{"id":id},
type: 'GET',
});
};
$('.feedImage').each(async function() {
try {
const res = await renderImage($(this).data("id"));
$(this).attr("src", res);
} catch(err) {
console.log("error"+err);
}
});

Ajax success does not display message

my ajax success:function is not work.When i have successfully uploaded file,it should dispay message.However,it does not display message eventhough the file has been successfully uploaded.Can somone help me fix this problem?
Here is my code;
type: 'POST',
url: 'upload.php',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend: function(){
$(".progress-bar").width('0%');
},
error:function(){
$('#uploadStatus').html('<p style="color:#EA4335;">File upload failed, please try again.</p>');
},
success: function(resp){
if(resp == 'ok'){
$('#uploadForm')[0].reset();
$('#uploadStatus').html('<p style="color:#28A74B;">File has uploaded successfully!</p>');
console.log('it works');
}else if(resp == 'err'){
$('#uploadStatus').html('<p style="color:#EA4335;">Please select a valid file to upload.</p>');
}
}
php code:
$upload = 'err';
if(!empty($_FILES['file'])){
$targetDir = "D:/MMHE4DFiles/";
$allowTypes = array('avi');
$path=$_POST['path'];
$fileName = basename($_FILES['file']['name']);
$targetFilePath = $targetDir.$path.".avi";//$fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath);
}
if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)){
$upload = 'ok';
echo $upload;
}
}
This cannot work.
Reason:
You move the file twice. But after the first move it is gone, so the second move must fail.
Solution:
// Check whether file type is valid
$fileType = pathinfo($targetFilePath, PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath) )
{
echo "ok";
exit();}
}
echo "err";
(Delete your last paragraph. )

how to request a single file as object

I just start to learn javascirpt, php about 2 days. The problem I face is I already have a x.dcm file under server root, and I already known that path(e.g. http://localhost:8888/....)
My question is how can I simply grab that file from server to use, maybe something like:
var file= 'http://localhost:8888/....'; ////file is not an object
I ask this question because I already known how to use input method:
<input type="file" name="file" id="file">
<script>
$('#file').on('change',function(e){
var file = e.target.file; ///file is an object
});
</script>
but that is not what I want, what I want is to use an existed file rather than input.
So the whole thing is that:
<form id="input" method="post" enctype="multipart/form-data">
<input type="file" id="fileToUpload" name="fileToUpload">
</form>
I firstly make a input to upload some file,then in script
<script>
$("form#input").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'segmentation.php',
type: 'POST',
data: formData,
async: false,
success: function (html) {
$('#segbound').html(html);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
</script>
I sent this file(e.g image.dcm) to do something( run a exec) on the server side, then it generates another image(imgproc.dcm) in an expected path(http://localhost:8888/....), and then the next thing is that I what that processed image display on the screen. To do that I need to use a js called cornerstone, and the function in it imageLoader.fileManager.get(file)
which file is that one I what to display.
When I select from input using var file = e.target.file; as I mentioned above, it works perfect, then I check the file type it is a [file object].
But when I want to simply display that 'imgproc.dcm' by using var file= 'http://localhost:8888/....'; the file type is not an object which comes out my question, how can I simply grab that known path image to use as an object.
Or, to improve that, it is possible to get the return (generated imgproc.dcm) directly after it process on server side, and then to use that return(maybe give it an id...do not know) to display (call cornerstone function imageLoader.fileManager.get(file))
On server side, it looks like:
<?php
$target_dir = "/Applications/MAMP/htdocs/dicomread/temp/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (file_exists($target_file)) {
echo "file has already been uploaded.";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file)) {
echo "The file ". basename( $_FILES['fileToUpload']['name']). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
$cmd = "/Applications/MAMP/htdocs/dicomread/abc 2>&1";
$Output_fileName = "imgproc.dcm";//$_FILES['fileToUpload']['name'];
exec("$cmd $target_file $Output_fileName);
echo "<br/>done";
?>
Any help would be appreciated.
Use fopen with URL to the file:
$file = fopen("http://localhost:8888/x.dcm", "r");
Refer to this for fopen: http://php.net/manual/en/function.fopen.php

Saving data into a text file sent as JSON with Ajax

I have currently a problem with my code. I would like to send JSON data with Ajax to a PHP script but it doesn't work. What does work is that the PHP script can be called by the Ajax code but it can't put the code into the .txt file. I have tried several things but I can't get it working. (I am trying to set the users array in the .txt file)
jQuery code:
var users = [];
$.ajax({
type: "POST",
url: hostURL + "sendto.php",
dataType: 'json',
data: { json: JSON.stringify(users) },
success: function (data) {
alert(data);
}
});
PHP Code:
<?php
$json = $_POST['json'];
$data = json_decode($json);
$file = fopen('test.txt','w+');
fwrite($file, $data);
fclose($file);
echo 'Success?';
?>
You must know that in PHP json_decode generates an Array that you can't write into an text file.
So only remove the json_decode command.
Since json_decode() function returns an array, you can use file_put_contents() that will save each array element on its own line
<?php
$json = $_POST['json'];
$data = json_decode($json, true);
file_put_contents('test.txt',implode("\n", $data));
?>

Download File in AJAX Handler

I wrote a small script using only PHP to test file download functionality using a experimental API, where this worked fine. When I decided to commit this code to my project, I added the same code to the handler for my AJAX call, however it does not start the download as it did before.
I believe this is due to the fact I am using AJAX, however as I was using header() to initiate the file download on the client, I am at a loss as to how to work around this.
Can anyone suggest an alternative method to do this now?
AJAX:
$.ajax({
type: "POST",
url: "handler.php",
data: { 'action': 'downloadFile', 'filename': curSelectedFile },
dataType: 'json',
success: function(data)
{
//Success
}
});
PHP Handler:
case "downloadFile":
{
$filename = '';
if (isset($_POST["filename"]))
{
$filename = $_POST["filename"];
}
$pos = 0; // Position in file to start reading from
$len = 32; // Length of bytes to read each iteration
$count = 0; // Counter for the number of bytes in the file
do
{
$result = $fm->getFileChunk($filename, $pos, $len);
$chunk = $result->result;
if (!empty($chunk))
{
$chunk = base64_decode($chunk);
$count += strlen($chunk);
echo $chunk;
}
$pos += $len;
}
while (!empty($chunk));
header('Content-Disposition: attachment; filename="'. $filename .'"');
header('Content-Type: application/octet-stream');
header('Content-Length: ' . $count);
$response['status'] = "success";
echo json_encode($response);
break;
}
You can encode your file in base64 and create File Object using JavaScript.
I wouldn't recommend this for large files!
Alternative:
Save your file on server and you can just retrieve file location and redirect using location.href in Ajax callback.
You can decode base64 using atob() and create typed array. refer to following link for creating Binary Object on client side. You create typed array like answered here.

Categories

Resources