skip to Main Content

I’m trying to write this jQuery ajax POST request in Vanilla JS; it initially is:

$.ajax({
      method: 'POST',
      url: window.location.href + 'email',
      data: {
        toEmail: to, //var set elsewhere
        fromName: from, //var set elsewhere
        message: message, //var set elsewhere
        recaptcha: recaptcha //var set elsewhere
      }
    })
    .done(function (data) {
      handleResponse(data, form)
    })
    .fail(function (error) {
      console.error(error)
      alert('Couldn't send your email. Try again later.')
    })

handleResponse is

  function handleResponse (data, form) {
    if (!data.message) return

    if (!form) return

    const responseMessage = form.querySelector('[email-response]')
    const formData = form.querySelector('[email-data]')

    if ('success' === data.message) {
      responseMessage.classList.remove('error')
      responseMessage.classList.add('success')
      responseMessage.innerText = 'Success! Email has been sent.'
      formData.classList.add('hidden')
      return
    }

    return handleError(responseMessage, data)
  }

However, I tried to convert the Ajax part to:

var req = new XMLHttpRequest();
    req.onLoad = function(e){
      resolve(req.response);
    }
    req.onerror = function(e){
      console.log(e);
      alert('Couldn't send your email. Try again later.')
    };
    var data = {
        toEmail: to, //var set elsewhere
        fromName: from, //var set elsewhere
        message: message, //var set elsewhere
        recaptcha: recaptcha //var set elsewhere
      }
    }
    var url = window.location.href + 'email';
    req.open("POST",url,true);
    req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    req.send(data);

I get a console error saying req is not defined What am I doing incorrectly? How can I do the jQuery ajax request in vanilla JS properly?

2

Answers


  1. in Vanilla js you can Use XHRHttpRequest

    var http = new XMLHttpRequest();
    var url = 'your url';
    var params = 'orem=ipsum&name=binny';
    http.open('POST', url, true);
    
    //Send the proper header information along with the request
    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
    
            // http.responseText will be anything that the server return
            alert(http.responseText);
        }
    }
    http.send(params);
    

    or if you went pass an object you can use FormData

    var http = new XMLHttpRequest();
    var url = 'your urk';
    var myForm = new FormData()
    
    myForm.append('foo', 'bar')
    
    http.open('POST', url, true);
    
    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
    
            // http.responseText will be anything that the server return
            alert(http.responseText);
        }
    }
    http.send(myForm);
    
    Login or Signup to reply.
  2. You should use fetch API:

    const url = `${window.location.href}email`;
    
    const payload = {
      toEmail: to, //var set elsewhere
      fromName: from, //var set elsewhere
      message: message, //var set elsewhere
      recaptcha: recaptcha //var set elsewhere
    };
    
    fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(payload),
    })
      .then((response) => {
        if (!response.ok) {
          throw Error(response.statusText);
        }
        return response;
      })
      .then((response) => response.json())
      .then((data) => {
        handleResponse(data, form);
      })
      .catch((error) => {
        console.error(error);
        alert('Couldn't send your email. Try again later.');
      });
    

    fetch returns a promise, and work with text in the response, if you would like to use something more automatic try out Axios.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search