I have the following code to submit a form using jQuery Ajax:
HTML
<form id="note_form" action="upload_note.php" enctype="multipart/form-data">
<input id="note_title" />
<textarea id="note_text"></textarea>
<input type="file" id="image" multiple="false" accept="image/*" />
</form>
Script
<script>
$(document).ready(function () {
$('#note_form').on("submit", function (e) {
e.preventDefault();
var $form = $(this),
url = $form.attr('action');
var posting = $.post(url, {
title: $("#note_title").val(),
text: $("#note_text").val()
});
posting.done(function (response) {
alert(response);
});
});
});
</script>
PHP
$title = $_POST['title'];
$text = $_POST['text'];
//$image = $_POST['image'];
echo $title;
The code works fine but I have no idea on how to send the image to the server using this function.
EDIT
HTML
<form id="note_form" enctype="multipart/form-data">
<input name="note_title" />
<textarea name="note_text"></textarea>
<input type="file" name="image" multiple="false" accept="image/*" />
</form>
SCRIPT
$(document).ready(function () {
$('#note_form').on("submit", function (e) {
e.preventDefault();
var url = "upload_note.php";
var formData = new FormData($(this)[0]);
$.ajax({
url: url,
type: 'POST',
dataType: "json",
data: formData,
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
});
});
PHP
$title = $_POST['note_title'];
echo $title;