Skip to content

Instantly share code, notes, and snippets.

@techslides
Last active November 26, 2020 14:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save techslides/7ff437bc9e2c84605485 to your computer and use it in GitHub Desktop.
Save techslides/7ff437bc9e2c84605485 to your computer and use it in GitHub Desktop.
Upload to WordPress with Ajax and FormData
<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>
@techslides
Copy link
Author

@kjvaghasiya
Copy link

Hi,
can you explain me how to get response of this code?
current code in not getting response?
thanks.

@dionkitchener
Copy link

This is not working for me. I get a 403 (forbidden) response.

@luisgagocasas
Copy link

luisgagocasas commented Aug 9, 2018

I get a 400 (Bad Request)

@socheatit1992
Copy link

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