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.
2
Answers
In your jQuery code you defined
data
asand in fetch you defined it as
so, you are not passing some value which was previously passed. No wonder that your server errors out. Let’s change your code to
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.