I'm new to jQuery/Ajax and I am trying to upload a file like so:
var fd = new FormData();
fd.append('file', file);
$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(e) {
var percent = 0;
if (e.lengthComputable) {
percent = Math.floor(e.loaded / e.total * 100);
}
progressDiv.find('progress').val(percent);
progressDiv.find('b').html(percent + '%');
});
}
},
type: 'POST',
url: 'upload.php',
data: fd,
success: function(data) {
progressDiv.find('progress').val(100);
progressDiv.find('b').html('100%');
alert(data);
},
error: function() {
alert('Error uploading!');
}
});
My upload.php file looks like this:
<?php
file_put_contents('log.txt', "LOG\n");
file_put_contents('log.txt', implode(', ', $_FILES) . "\n", FILE_APPEND);
$target = 'upload/' . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $target)) {
file_put_contents('log.txt', "SUCCESS\n", FILE_APPEND);
} else {
file_put_contents('log.txt', "FAILURE\n", FILE_APPEND);
}
?>
The problem is that the progress bars are remaining at 0 and the no alert ever appears. Also nothing is being written to the log file, meaning that upload.php is not even being called.
What am I doing wrong?
EDIT:
After searching for a while I stumbled across this nifty little question: Submitting a file with jQuery.ajax gives TypeError
So adding contentType: false and processData: false seems to have done something. Now I get the alert "Error uploading", but I still don't think upload.php is being called as nothing is being written to log. Commenting out the xhr stuff after making those changes allows the upload to complete. Now the question becomes what is wrong with the xhr stuff?
What is 'log'?
file_put_contents('log', "LOG\n");
I bet if you looked at your webserver error log the PHP script would be found to be choking on trying to write to 'log'.
EDIT
Here's an existing question that appears to show correctly how to do what you're trying to do. If you're still not getting the result you expect, I would still suspect there's something wrong with your file paths. Full error reporting should clarify the issue
update progress bar using ajax request seconds
Related
This might be a dumb question. I'm fairly new to PHP. I am trying to get a look at some echo statements from a page I'm posting to but never actually going to. I can't go directly to the page's url because without the post info it will break. Is there any way to view what PHP echos in the developer console or anywhere else?
Here is the Ajax:
function uploadImage(image) {
var data = new FormData();
data.append("image", image);
imgurl = 'url';
filepath = 'path';
$.ajax({
url: imgurl,
cache: false,
contentType: false,
processData: false,
data: data,
type: "post",
success: function(url) {
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
error: function(data) {
console.log(data);
}
});
}
And here is the php file:
<?php
$image = $_FILES['image']['name'];
$uploaddir = 'path';
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo $uploadfile;
} else {
echo "Unable to Upload";
}
?>
So this code runs fine but I'm not sure where the echos end up and how to view them, there is more info I want to print. Please help!
You already handle the response from PHP (which contains all the outputs, like any echo)
In the below code you have, url will contain all the output.
To see what you get, just add a console.log()
$.ajax({
...
success: function(url) {
// Output the response to the console
console.log(url);
var image = $('<img class="comment_image">').attr('src', path + url);
$('#summernote').summernote("insertNode", image[0]);
},
...
}
One issue with the above code is that if the upload fails, your code will try to add the string "Unable to upload" as the image source. It's better to return JSON with some more info. Something like this:
// Set the header to tell the client what kind of data the response contains
header('Content-type: application/json');
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo json_encode([
'success' => true,
'url' => $uploadfile,
// add any other params you need
]);
} else {
echo json_encode([
'success' => false,
'url' => null,
// add any other params you need
]);
}
Then in your Ajax success callback, you can now check if it was successful or not:
$.ajax({
...
dataType: 'json', // This will make jQuery parse the response properly
success: function(response) {
if (response.success === true) {
var image = $('<img class="comment_image">').attr('src', path + response.url);
$('#summernote').summernote("insertNode", image[0]);
} else {
alert('Ooops. The upload failed');
}
},
...
}
If you add more params to the array in your json_encode() in PHP, you simply access them with: response.theParamName.
Here is a basic example...
HTML (Form)
<form action="script.php" method="POST">
<input name="foo">
<input type="submit" value="Submit">
</form>
PHP Script (script.php)
<?php
if($_POST){
echo '<pre>';
print_r($_POST); // See what was 'POST'ed to your script.
echo '</pre>';
exit;
}
// The rest of your PHP script...
Another option (rather than using a HTML form) would be to use a tool like POSTMAN which can be useful for simulating all types of requests to pages (and APIs)
I've searched for hours and tried more things than I can count on both hands. But, this is perplexing me.
I'm trying to show upload progress when uploading a file. I'm using the jQuery ajax method to do this while adding in an event listener for the progress. The upload works fine and gets uploaded without any issue. However, the progress is always at 100 right from the start. The only exception to this is if I hit the upload button repeatedly in quick succession in which case it seems to show progress. Sometimes this progress will be 50% then 100% within a second on a 25mb file, so not confident this is real progress. Other times it does actually look like it's showing real progress.
I've also tried a pure JavaScript approach and the results are exactly the same.
Any assistance in helping identify why this is happening would be greatly appreciated.
upload_handler.js
$('#upload_form').submit(function(event){
event.preventDefault();
var form = $('#upload_form')[0];
var fd = new FormData(form);
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
var percent = (evt.loaded / evt.total) * 100;
console.log(percent);
}, false);
return xhr;
},
url: "https://example.com/upload_file.php",
method: "POST",
data: fd,
contentType: false,
processData: false,
})
.done(function(){
console.log('Done');
})
.fail(function(){
console.log('Fail');
})
.always(function(){
console.log('Always');
});
})
Console Output
When the form is submitted the console will read:
100 - this shows immediately when the form is submitted
Done - this shows a couple seconds after submitting the form
Always - shows immediately after Done
upload_file.php
<?php
$file = $_FILES['file_upload'];
$file_dir = __DIR__ . '/test_uploads/';
if( is_dir( $file_dir ) === false ) {
mkdir(
$file_dir,
0755
);
}
$file_path = "{$file_dir}{$file['name']}";
if( move_uploaded_file( $file['tmp_name'], $file_path ) ) {
error_log("File uploaded to {$file_path}");
echo 'success';
} else {
error_log("Failed to upload file to {$file_path}");
echo 'failed';
}
EDIT
The files above are on a server. So, I wouldn't expect a 25mb file to instantly upload when the file is originating from my computer (I don't pay for that kind of internet...)
Uploading larger files 2gb does show progress. Is there anyway to get these smaller file sizes to show progress?
I am trying to save a loaded image on Server Using jQuery,Ajax and PHP.
Here is the code I have for Ajax part:
<script>
$(function () {
$("#uploadimage").on('submit', function (e) {
e.preventDefault();
var formData = new FormData(this);
var imgloader = $.ajax({
type: "POST",
url: "imgLoader.php",
data: formData,
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formData);
}
});
imgloader.fail(function () {
console.log('Error');
});
imgloader.done(function (data) {
$('#res').text(data);
});
});
});
</script>
and I have this PHP on imgLoader.php
<?php
if (isset($_FILES["file"]["type"])) {
$file = $_FILES['file']['tmp_name'];
$newloc = "newupload/" . $_FILES['file']['name'];
move_uploaded_file($file, $newloc);
} else {
echo 'There is Something Wrong?!';
}
?>
but I am getting the
There is Something Wrong?!
on the page without uploading the image on server. Can you please let me know what I am doing wrong? (I know this is not a secure and safe way to upload image to server, but please be informed that I am trying to lean the whole process of uploading without validation, sanitizing or filtering)
Thanks
AJAX doesn't do file uploads. It's not designed for that. For uploading files without page refreshing you will have to use any jquery ajax plugin.For e.g.
http://www.malsup.com/jquery/form/
This problem is already discussed in following link:
PHP and Ajax file upload - Can't get the tmp_name with $_FILES
I have been attempting to get a nice neat file upload using ajax, and from the many items on SO I have been able to get the framework done as follows:
My HTML:
<form enctype="multipart/form-data" method="post">
<input name="file" type="file" />
<input type="button" value="Upload" />
Pretty straight forward.
My PHP storeSales.php
if ($_FILES["file"]["name"] != NULL) {
if (file_exists("accounting/" . $_FILES["file"]["name"])){
echo $_FILES["file"]["name"] . " already exists. ";
}else{
move_uploaded_file($_FILES["file"]["tmp_name"], "accounting/" . $_FILES["file"]["name"]);
}
}
$file = fopen($_FILES['myfile']['name'],'r') or die('cant open file');
and my .js:
$(":button").click(function(){
var formData = new FormData($('form')[0]); if (formData !=null) {
alert("Got the file");
} else {
alert("nothing Here");
}
$.ajax({
url: 'storeSales.php', //Server script to process data
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
success: function(result)
{
console.log($.ajaxSettings.xhr().upload);
alert(result);
},
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});
function progressHandlingFunction(e){
if(e.lengthComputable){
$('progress').attr({value:e.loaded,max:e.total});
}
}
When I try to upload a file, I get the alert in my .js file that says "Got the file" but in the php code I get the error that a file cannot be empty. From everything I have been able to find, I thought I was doing the php correctly. what is the correct way to handle this? Am I missing something else?
You can't use ajax to upload files - it's an illegal operation (via the dry Ajax route) without a third-party script. In short, you can't pass $_FILES data via Ajax. Only $_POST data. You need to find a plugin.
Try Uploadify:
http://www.uploadify.com/
I have a script which grabs another JavaScript which is made using PHP, it all works fine, but im trying to build in some error handling incase there is an issue. At the moment the error works if it cannot find the file, but I would like it to display a message from the PHP code if there is an error. I thought using JSON would work, but im very new to it, and admit to not knowing what im doing.
If someone could help me get this working, as at the moment I am not getting the message response message appear in the alert.
I have the following JQuery code:
graphURL = 'functions/ICP_summary_graph.php';
graphData = '?ICP=' + ICPSet;
$.ajaxSetup({
type: 'get',
URL: graphURL,
data: graphData,
success: function (data) {
var reponse = jQuery.parseJSON(data.response);
alert("response : "+reponse);
//$('#expconchart').html(data.response);
},
error: function(data) {
$('#meterloader').hide();
$('#meterbox').html("<div><p class='textcentre bold red'>There was an error loading the chart.</p>");
}
});
$.getScript(graphURL + graphData);
and this PHP:
//GENERATE GRAPH
//SET RESULT ARRAY
$result = array();
//CONNECT TO DATABASE
if(!require('../../connect.php')){
$result['response'] = "Unable to aquire connection";
header("content-type: application/json");
exit(json_encode($result));
} else {
...
Any help greatly appreciated. :)