0

My jQuery

 let name = document.getElementById("Name").value;
  let code = document.getElementById("Code").value;
  let type = document.getElementById("ProductTypeId").value;

$.ajax({
   url: "/Home/jQueryAddComment",
   type: "POST",
   dataType: "html",
   data: json,
   success: function(data){ 
      //var message = data.Message; 
      alert(data);
      $('.CommentSection').html(data);
   }
}

I need to convert my jQuery to pure Javascript function using fetch. It is a post method with html return. Is it possible using fetch.

Edit: Below is the get method of my Javascript:

    fetch(url + "?" + o)
        .then(function (response) {
            //check if it is redirected to custom error page
            if (response.redirected && response.url.indexOf("/Error") > 0) {
                response.text().then(function (html) {
                    debugger
                    window.location.href = response.url;
                });
            } else {
                response.text().then(function (html) {
                    document.getElementById('view-all').innerHTML = html;
                });
            }
        })
        .catch(function (err) {

            console.log('Fetch Error', err);
        });
3
  • 2
    what seems to be the issue? what is not working? Commented Sep 19, 2020 at 11:34
  • i know only get method of fetch ..is it possile to do post with fetch and get html response..? Commented Sep 19, 2020 at 11:36
  • 1
    @Ajt well of course you can: developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch Commented Sep 19, 2020 at 11:38

1 Answer 1

1

fetch also accepts a second argument which is a literal object containing information pertaining to the request - such as Request method, mode, headers, and POST BODY.

Straight from Mozilla docs:

var data = { name: "justin", code: "SDF", type: "some-type" };

fetch(url, {
   method: 'POST', // *GET, POST, PUT, DELETE, etc.
   mode: 'cors', // no-cors, *cors, same-origin
   cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
   credentials: 'same-origin', // include, *same-origin, omit
   headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
   },
   body: JSON.stringify(data) // body data type must match "Content-Type" header
});

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.