Skip to content

Instantly share code, notes, and snippets.

@cwhittl
Created April 13, 2017 14:42
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • 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));
});
@cwhittl
Copy link
Author

cwhittl commented Apr 13, 2017

The kicker is credentials: 'same-origin'
This is required to send the wordpress cookies with it.

@usainicola
Copy link

usainicola commented Jun 1, 2018

Interesting. Would be cool to build the fetch body as an object, like jQuery does with ajax in the data parameter:

  $.ajax({
    url:ajaxurl,
    type:'post',
    data:{
      x:x,
      y:y,
      z:z
    },
    success:function(data){
    }
  });

@surajkhanal
Copy link

Do something like this

const form = new FormData();
form.append('action', 'make_appointment');
form.append('post_title', 'hola como estas');
const params = new URLSearchParams(form);

fetch(ajaxSettings.ajaxurl, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
       'Content-Type': 'application/x-www-form-urlencoded',
       'Cache-Control': 'no-cache',
      },
      body: params
    }).then(response => {
       return response.json();
    })
    .then(response => {
       // read data here
       console.log(response);
     }).catch(err => { 
       console.log(err);
     });

@tiojoca
Copy link

tiojoca commented May 14, 2020

You can use an object directly in the body field with URLSearchParams too (no need to use FormData):

fetch(ajaxSettings.ajaxurl, {
    method: 'POST',
    credentials: 'same-origin',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cache-Control': 'no-cache',
    },
    body: new URLSearchParams({
        action: 'make_appointment',
        post_title: 'hola como estas',
    })
}).then(response => response.json())
.then(response => console.log(response))
.catch(err => console.log(err));

@over-engineer
Copy link

Just pointing out for future Google searchers that you need to instantiate URLSearchParams (i.e. use the new operator)

body: new URLSearchParams({
    action: 'make_appointment',
    post_title: 'hola como estas',
})

@tiojoca
Copy link

tiojoca commented Oct 14, 2020

👍 well spotted, I've updated the code above.

@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