Created
June 21, 2017 07:34
-
-
Save corerman/42772eec73e4b3713cc39ac6fa6d90cb to your computer and use it in GitHub Desktop.
ajax post file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can upload data and files with one form using ajax. | |
PHP + HTML | |
<? | |
print_r($_POST); | |
print_r($_FILES); | |
?> | |
<form id="data" method="post" enctype="multipart/form-data"> | |
<input type="text" name="first" value="Bob" /> | |
<input type="text" name="middle" value="James" /> | |
<input type="text" name="last" value="Smith" /> | |
<input name="image" type="file" /> | |
<button>Submit</button> | |
</form> | |
jQuery + Ajax | |
$("form#data").submit(function(){ | |
var formData = new FormData($(this)[0]); | |
$.ajax({ | |
url: window.location.pathname, | |
type: 'POST', | |
data: formData, | |
async: false, | |
success: function (data) { | |
alert(data) | |
}, | |
cache: false, | |
contentType: false, | |
processData: false | |
}); | |
return false; | |
}); | |
Short Version | |
$("form#data").submit(function() { | |
var formData = new FormData($(this)[0]); | |
$.post($(this).attr("action"), formData, function(data) { | |
alert(data); | |
}); | |
return false; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment