I have form and I want to send values from it with ajax to php script, but it doesn’t send value of chceckbox if is it checked and doesnt’t send file with avatar. So form send only values from text inputs, but not from checkbox and file. Can you help me please what is wrong?
Form:
<form action='' id='form1' method='post' name='form1' ENCTYPE='multipart/form-data'>
<input type='text' name='name' id='name' value=''>
<input type='text' name='age' id='age' value=''>
<input type='text' name='hobby' id='age' hobby=''>
<input type="checkbox" name="chkPHP" id="chkPHP" value="checked">
<input type='file' name='avatar' id='avatar' value='insert avatar' SIZE='30' accept=''>
<input type='submit' name='submit' id='submit' value='submit'>
</form>
Script to send values from form:
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(0);
$('#form1');
$('#error').hide(0);
$.ajax({
type : 'POST',
url : 'pksZpacuj.php',
dataType : 'json',
data: {
name: $('#name').val(),
age: $('#age').val(),
hobby: $('#hobby').val(),
chkPHP: $('#chkPHP').val(),
avatar: $('#avatar').val()
},
success : function(data){
$('#waiting').hide(0);
$('#error').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).show(0);
if (data.error === true)
$('#form1');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(0);
$('#error').removeClass().addClass('error')
.text('There was an error.').show(0);
$('#form1');
}
});
return false;
});
});
</script>
Uploading files via AJAX is quite hard, and won’t work in all browsers. I would strongly recommend against it.
If you really want to, you could follow this great post: http://net.tutsplus.com/tutorials/javascript-ajax/uploading-files-with-ajax/