user14146411
user14146411

Reputation:

Convert text/string response to html

Inside my fetch POST, I am receiving an html response in plain text. I want to select the relevant part and then display it in my web page, so I'm doing:

 document.querySelector('form').onsubmit = (event) => {
    event.preventDefault();

  fetch("", {

    method: 'POST',
    body: JSON.stringify({
      body: document.querySelector('#new_message').value
    }),
    headers: {
      "Content-type": "application/json; charset=UTF-8",
      "X-CSRFToken": getCookie('csrftoken')
    }
  })
  .then(response => response.text())
  .then(result => {
    document.querySelector('#new_message').value = ""
    let div = document.createElement('div')
 
    fetch("", {
      headers: {
        "Content-type": "charset=UTF-8",
      }
    })
    .then(response => response.text())
    .then(result2 => {

        var success = $(result2).filter("#granpost"+result['id']); 
        div.append(success);

        document.querySelector('#plis').append(div);
        console.log(success); // div#success  
    });



  });

}

This is what I wan the code to do: First, convert the string to html, then, get the div with the id "granpost"+result['id'] and store it in success variable. Finally, display that success div in my page.

This is not working, the only thing that gets displayed in my page is this: '[object Object]'

And the console.log is returning this: m.fn.init [prevObject: m.fn.init(45), context: undefined]

Upvotes: 1

Views: 5968

Answers (2)

user14146411
user14146411

Reputation:

Another solution: Change the parent response of this fetch to .json() and then:

fetch("", {
      headers: {
        "Content-type": "charset=UTF-8",
      }
    })
    .then(response => response.text())
    .then(result2 => {


        var doc = new DOMParser().parseFromString(result2, "text/html");

        je = doc.querySelector(`#granpost${result['id']}`)


        div.append(je);

        $('#plis').append(div);
    });
```

Upvotes: 0

epascarello
epascarello

Reputation: 207511

First issue, response is a string and you are using it as an object. So looks like

.then(response => response.text())
.then(result => {})

should be using json

.then(response => response.json())
.then(result => {})

Now with the output:

You are mixing DOM and jQuery. So you are appending a jQuery object to a DOM element. Hence why you are getting a reference to an object in the HTML. Change

let div = document.createElement('div')

to

const div = $('<div></div>')

And change

document.querySelector('#plis').append(div);

to

$('#plis').append(div);

You also are using filter with an id. filter is running off the elements on the level it has. And since it is an id, I assume you have one. So you should be using find.

var success = $(result2).find("#granpost"+result['id']); 

Upvotes: 1

Related Questions