Skip to content

Instantly share code, notes, and snippets.

@cwhittl
Created April 13, 2017 14:42
Show Gist options
  • Save cwhittl/015827973d23ce657bfe09c735c9fa98 to your computer and use it in GitHub Desktop.
Save cwhittl/015827973d23ce657bfe09c735c9fa98 to your computer and use it in GitHub Desktop.
Using Fetch with Wordpress Plugins Ajax
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));
});
@nikospapapetrou
Copy link

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.

@over-engineer
Copy link

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.

@nikospapapetrou
Copy link

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.

@mattmintun
Copy link

This is killer! Thank you. I was able to modify this to download a PDF file from the server.

@cuchakma
Copy link

cuchakma commented May 7, 2021

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