Created
April 13, 2017 14:42
-
-
Save cwhittl/015827973d23ce657bfe09c735c9fa98 to your computer and use it in GitHub Desktop.
Using Fetch with Wordpress Plugins Ajax
This file contains hidden or 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
fetch(ajax_url, { | |
method: 'POST', | |
credentials: 'same-origin', | |
headers: new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), | |
body: 'action=zget_profile_user' | |
}) | |
.then((resp) => resp.json()) | |
.then(function(data) { | |
if(data.status == "success"){ | |
_this.setState({loaded:true,user:data.user}); | |
} | |
}) | |
.catch(function(error) { | |
console.log(JSON.stringify(error)); | |
}); |
Hey @nikospapapetrou,
you could do something like this:
fetch(ajaxurl, opts)
.then((response) => response.json())
.then((data) => {
console.log(data);
// TODO: Do something with the `data` you fetched
})
.catch((error) => console.log(error));
Then, it's just DOM manipulation to populate a table, create a list element, or whatever you want to do with your data.
Yes, I have done something like that. First I used in the body: I wanted for the wordpress to submit from throught ajax-admin.php.
myForm.addEventListener('submit', (e) => {
e.preventDefault();
fetch( jsforwp_globals.ajax_url, {
method: 'post',
body: new URLSearchParams({
action: 'photolensor_save_user_contact_form',
_ajax_nonce: jsforwp_globals.photolensor_save_user_contact_form
}),
}).then(function (response) {
return response.text();
}).then(function (text) {
console.log(text);
});
});
But First I used inside the new URLSearchParams( new FormData(myForm)). And in the cosole in request I could see my data. But anyway thanks. May, it is more wordpress question. Thanks anyway.
This is killer! Thank you. I was able to modify this to download a PDF file from the server.
Is there any demo or code for GET REQUEST in ajax?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello!
Does anyone know how to handle the fetch Api after I have submit a Form, so I can display the information in the admin panel.
I have created some top level menus and submenus in the admin area. Also I used new FormData(myForm) and the submit informations were displaying in the Request . Now, I use the new URLSearchParams as I saw here, but I can't see the informations being displayed.