Home > Software design >  How can I convert jQuery ajax to fetch?
How can I convert jQuery ajax to fetch?

Time:09-26

This was my jQuery code before. Now I want to change it to fetch.

    function fetch(){
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },
        success: function(data) {
            jQuery('#datafetch').html( data );
        }
    });
}

I have changed the code to this now but I am getting bad request 400 status code

document.querySelector('#keyword').addEventListener('keyup',()=>{
    let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value
};
let url = "<?php echo admin_url('admin-ajax.php'); ?>";
fetch(url, {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    })
    .then((response) => response.text())
    .then((data) => {
        document.querySelector("#datafetch").innerHTML = data;
    })
    .catch((error) => {
        console.error('Error:', error);
    });
})

Am I missing something? It is from WordPress if this helps somehow.

CodePudding user response:

  1. You forgot the pcat property in the data object
  2. jQuery, by default, sends form encoded data, not JSON encoded data. Use a URLSearchParams object instead of a string of JSON and omit the content-type header (the browser will add the correct one for you).

CodePudding user response:

In your jQuery code you defined data as

data: { action: 'data_fetch', keyword: jQuery('#keyword').val(), pcat: jQuery('#cat').val() },

and in fetch you defined it as

let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value
};

so, you are not passing some value which was previously passed. No wonder that your server errors out. Let's change your code to

let data = {
    action: 'data_fetch',
    keyword: document.querySelector("#keyword").value,
    pcat: document.getElementById("cat").value
};

and try this out. If it still works, then you will need to find out what differs in the request and make sure that the request you are sending via fetch is equivalent to the request you formally sent via jQuery, then it should work well, assuming that the client-side worked previously with jQuery and the server-side properly handled the requests.

  • Related