Admittedly, there are similar questions lying around on Stack Overflow, but it seems none quite meet my requirements.
Here is what I'm looking to do:
Up until here, all is well. The data gets in my database as I need it. But I'd also like to submit my form via an AJAX post:
.ajax()
jQuery methodI think I could imagine how to do this by auto-uploading the file when the field's value changes using pure javascript, but I'd rather do it all in one fell swoop on for submit in jQuery. I'm thinking it's not possible to do via query strings as I need to pass the entire file object, but I'm a little lost on what to do at this point.
Can this be achieved?
File upload is not possible through AJAX. You can upload file, without refreshing page by using IFrame .
jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!
It's not too hard. Firstly, take a look at FileReader Interface.
So, when the form is submitted, catch the submission process and
var file = document.getElementById('fileBox').files[0]; //Files[0] = 1st file var reader = new FileReader(); reader.readAsText(file, 'UTF-8'); reader.onload = shipOff; //reader.onloadstart = ... //reader.onprogress = ... <-- Allows you to update a progress bar. //reader.onabort = ... //reader.onerror = ... //reader.onloadend = ... function shipOff(event) { var result = event.target.result; var fileName = document.getElementById('fileBox').files[0].name; //Should be 'picture.jpg' $.post('/myscript.php', { data: result, name: fileName }, continueSubmission); }
Then, on the server side (i.e. myscript.php):
$data = $_POST['data']; $fileName = $_POST['name']; $serverFile = time().$fileName; $fp = fopen('/uploads/'.$serverFile,'w'); //Prepends timestamp to prevent overwriting fwrite($fp, $data); fclose($fp); $returnData = array( "serverFile" => $serverFile ); echo json_encode($returnData);
Or something like it. I may be mistaken (and if I am, please, correct me), but this should store the file as something like 1287916771myPicture.jpg
in /uploads/
on your server, and respond with a JSON variable (to a continueSubmission()
function) containing the fileName on the server.
Check out fwrite()
and jQuery.post()
.
On the above page it details how to use readAsBinaryString()
, readAsDataUrl()
, and readAsArrayBuffer()
for your other needs (e.g. images, videos, etc).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With