Reputation: 1
I get this message when I try to use $_FILES to get the image name.
Notice: Undefined index: image in C:\xampp\htdocs\upload_form\upload_query.php on line 10
I have a form that uploads information about an image to a mysql database (phpmyadmin), and then the form is cleared using JavaScript so that the user can upload another image and information. I have read that you can't use $_FILES as well as JavaScript, but I am unsure why, I would also appreciate a solution.
I am new to php, and JavaScript.
This is the JavaScript.
$('form').on('submit',function() {
var that= $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index,value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
document.getElementById("upload_form").reset();
return false;
});
This is the php.
//image properties
$name = $_FILES['image']['name'];
$size = $_FILES['image']['size'];
$temp = $_FILES['image']['tmp_name'];
$error = $_FILES['image']['error'];
$type = $_FILES['image']['type'];
//****************
This is part of the form.
<form action='upload_query.php' class='appnitro' enctype='multipart/form-data' id='upload_form' method='post' name='upload_form'>
<ul>
<li id='li_1'>
<label class='description' for='image'>Upload a Picture</label>
<div>
<input class='element file' id='image' name='image' required="" type='file'>
</div>
</li>
<li id='li_2'><label class='description' for='name'>Name</label> <span><input class='element text' id='first_name' maxlength='255' name='first_name' placeholder='First Name.' required="" size='12' value=''></span> <span><input class='element text' id='last_name' maxlength='255' name='last_name' placeholder='Last Name.' required="" size='18' value=''></span></li>
</ul>
</form>
etc.
Upvotes: 0
Views: 158
Reputation: 13535
Yes you can upload files using $.ajax
here is how
First let's have a typical form with an id. This form can include your one or many files as you wish.
<form id='fileupload' method='post' enctype="multipart/form-data" ...
Then in jQuery you do the following.
$('#btnupload').click(function () {
//the key is FormData object
var formData = new FormData(document.getElementById('fileupload'));
$.ajax({
url: 'upload.php', //server script to process data
type: 'POST',
success: function (json) {}
data: formData,
dataType: "json",
cache: false,
contentType: false,
processData: false
});
});
The key here is using the javascript FormData object to construct the data parameter of $.ajax
Upvotes: 3
Reputation: 22872
You cannot send files using AJAX (not this way).
If you want to send files, take a look at XMLHttpRequest2. Pretty good tutorial is here - http://www.html5rocks.com/en/tutorials/file/xhr2/
Upvotes: -1