Home > front end >  jQuery selecting data value from fetch
jQuery selecting data value from fetch

Time:06-27

I came across another issue with jquery. I seen code that uses .ajax() method and the response is being selected like this

.then(response => {
  $(response).find('.some-selector')
})

This is really confusing me.

I did a refactor to vanilla js like this

fetch('/some-endpoint', {
  method: 'POST',
  body: new FormData(e.currentTarget)
})
.then(res => res.text())
.then(data => {
  data.querySelector('.some-selector') // does not work
})

Everything is working, the response is good, but I do not understand how to get the selected value from the data.

CodePudding user response:

You need to parse the response first:

fetch('/some-endpoint', {
  method: 'POST',
  body: new FormData(e.currentTarget)
})
.then(res => res.text())
.then(function(html) {
  const parser = new DOMParser();
  return parser.parseFromString(html, "text/html");
})
.then(data => {
  data.querySelector('.some-selector');
})

  • Related