Я пытаюсь передать изображение и значение поля заголовка PHP, я обычно обрабатываю загрузку файлов прямо с PHP с помощью массива $ _FILES, я не уверен, как создать/передать этот массив с помощью ajax для PHP. Моя форма:
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
$('#success').empty();
var guestbookSendMessage = { //Fetch form data
'name' : $('input[name=name]').val(), //Store name fields value
'msg': $('textarea[name=msg]').val()
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'php/process.php', //Your form processing file url
data : guestbookSendMessage, //Forms name
dataType : 'json',
success : function(data) {
if (!data.success) { //If fails
if (data.errors.name) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
}
} else {
$('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
Попробуй это:
Jquery:
$(document).ready(function(){
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
});
Php:
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
просто измените свой код на этот код jquery и попробуйте
var guestbooksendmessage = new FormData();
guestbooksendmessage.append('file', input.files[0]);
guestbooksendmessage.append('name', $('input[name=name]').val());
guestbooksendmessage.append('msg', $('textarea[name=msg]').val());
$.ajax({
type: "POST",
url: 'php/process.php',
dataType: "json",
data: guestbooksendmessage,
processData: false,
contentType: false,
cache: false,
success: function (data) {
alert(data)
}
});
попробуйте этот код