Last active
November 26, 2020 14:15
-
-
Save techslides/7ff437bc9e2c84605485 to your computer and use it in GitHub Desktop.
Upload to WordPress with Ajax and FormData
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
<input type="file" name="file" id="file"> | |
<input type="submit" id="submit" name="Upload" onclick="upload();return false;"> | |
<script type="text/javascript"> | |
function upload(){ | |
var formData = new FormData(); | |
formData.append("action", "upload-attachment"); | |
var fileInputElement = document.getElementById("file"); | |
formData.append("async-upload", fileInputElement.files[0]); | |
formData.append("name", fileInputElement.files[0].name); | |
//also available on page from _wpPluploadSettings.defaults.multipart_params._wpnonce | |
<?php $my_nonce = wp_create_nonce('media-form'); ?> | |
formData.append("_wpnonce", "<?php echo $my_nonce; ?>"); | |
var xhr = new XMLHttpRequest(); | |
xhr.onreadystatechange=function(){ | |
if (xhr.readyState==4 && xhr.status==200){ | |
console.log(xhr.responseText); | |
} | |
} | |
xhr.open("POST","/wp-admin/async-upload.php",true); | |
xhr.send(formData); | |
} | |
</script> |
Hi,
can you explain me how to get response of this code?
current code in not getting response?
thanks.
This is not working for me. I get a 403 (forbidden) response.
I get a 400 (Bad Request)
thank u . it work well for me
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More info here: http://techslides.com/wordpress-upload-files-with-ajax