Upload an image with AJAX

To begin, little reminder about sending a form (without upload) AJAX with jQuery.



<form id="my_form" method="post" action="process_form.php">
<input type="text" name="title">
<textarea name="content"></textarea>
<button type="submit">OK</button>
</form>
view raw index.html hosted with ❤ by GitHub
$(function () {
$('#my_form').on('submit', function (e) {
// prevent browser from submitting the form
e.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: $form.serialize(),
success: function (response) {
//server responce
}
});
});
});
view raw app.js hosted with ❤ by GitHub
Nothing less than a form for sending in AJAX.
Here in this example will be about an upload image, but can be adapted to any other type of file. Here is the code that supports the upload of an image, in addition to the rest of the form.

<form id="my_form" method="post" action="upload.php" enctype="multipart/form-data">
<input type="text" name="title">
<textarea name="content"></textarea>
<input type="file" name="image" accept="image/*">
<button type="submit">OK</button>
</form>
view raw index.html hosted with ❤ by GitHub
enctype added = "multipart / form-data" to the form is mandatory if you want to do a file upload. We also add our field that allows the user to select a file on his computer. It states that only the images are accepted.
$(function () {
$('#my_form').on('submit', function (e) {
// prevent browser from submitting the form
e.preventDefault();
var $form = $(this);
var formdata = (window.FormData) ? new FormData($form[0]) : null;
var data = (formdata !== null) ? formdata : $form.serialize();
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
contentType: false, // mandatory for the upload
processData: false, // mandatory for the upload
dataType: 'json',
data: data,
success: function (response) {
// server responce
}
});
});
});
view raw app.js hosted with ❤ by GitHub

The upload AJAX is related in fact to support the browser FormData API. This is supported by the major browsers
finaly PHP :
<?php
$data['file'] = $_FILES;
$data['text'] = $_POST;
echo json_encode($data);
?>
view raw upload.php hosted with ❤ by GitHub

You can use my other tutoriel to handle this php file .

Comments

Popular posts from this blog

Realtime Chat Application with CakePHP and Socket.IO #1

Let's build a mobile application with Ionic Framework #1

Let's build a mobile application with Ionic Framework #3