1

So I'm a bit new to ajax, I just want to see if anyone can help me with this... I have my main page. I'll just put the element I'm working with so I don't have to put the whole page.

<input type="file" id="myphoto" />

Then, instead of submitting it, what I want to do is run it through a javascript function with an ajax form in it like this

$.ajax({
    type: "POST",
    url: "myphppage.php",
    "Whatever other code needed"
})

to upload the photo. Then, the form URL could be a php page that moves the photo to a different directory. I hope you know what I mean. Any help would be greatly appreciated...

Jeremy Board
  • 181
  • 1
  • 9
  • duplicate http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – oshell Aug 14 '15 at 12:34
  • Just explore about how to do file upload. AJAX calls are always in background and you can optionally include a callback function. –  Aug 14 '15 at 12:37

2 Answers2

3

first make a html file which select the file from anywhere, like

uplaod.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>AJAX UPLOAD</title>
</head>
<body>
<form enctype="multipart/form-data">
    <input id="file" type="file" />
    <input type="button" id="upload" value="Upload" />
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="upload.js"></script>
</html>

now, make js file like below,

upload.js

$(document).ready(function() {
$('#upload').on('click', function() {
var file_data = $('#file').prop('files')[0];   
var form_data = new FormData();                  
form_data.append('file', file_data);

$.ajax({
            url: 'upload.php', 
            dataType: 'text',  
            cache: false,
            contentType: false,
            processData: false,
            data: form_data,                         
            type: 'post',
            success: function(data){
                alert(data); 
            }
 });
});
});

now, make a directory uploads and a php file which upload the file to upload directory

upload.php

<?php

if (0 < $_FILES['file']['error']) {
    echo 'Error: ' . $_FILES['file']['error'] . '<br>';
} else {
    move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
    echo "success";
}
Itz Raghu
  • 457
  • 2
  • 6
  • 16
1

XHR2 AJAX request can submit binary data like images:

DEMO

However, changing the address bar (windows.location) will interrupt the upload as the new page is loaded. You can work around of this by loading pages via AJAX and using History API:

Demo1

Ivin Raj
  • 3,448
  • 2
  • 28
  • 65