skip to Main Content

Friends, I’m converting Jquery to javascript and I’m having problems with this block of code:

$.post('ajax_data',{action:'service_price',service:service,quantity:quantity,dripfeed:dripfeed,runs:runs}, function(data){
        $("#charge").val(data.price);
        $("#dripfeed-totalquantity").val(data.totalQuantity);
    }, 'json');

I tried to do this, but it doesn’t work for me

const request = new XMLHttpRequest();
const url = "ajax_data";
const params = "action=service_price&service=" + service + "&quantity=" + quantity+ "&dripfeed=" + dripfeed+ "&runs=" + runs;
request.responseType =  "json";
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 
request.addEventListener("readystatechange", () => {
 
    if (request.readyState === 4 && request.status === 200) {
        let data = request.response;
      document.querySelector("#charge").val(data.price);
      document.querySelector("#dripfeed-totalquantity").val(data.totalQuantity);
    }
});
request.send(params);

2

Answers


  1. Chosen as BEST ANSWER

    I solved it this way:

    async function postData(url = "", data = {}) { //https://developer.mozilla.org/ru/docs/Web/API/Fetch_API/Using_Fetch
      // Default options are marked with *
      const response = await 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',
        },
        redirect: "follow", // manual, *follow, error
        referrerPolicy: "no-referrer", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
        body: JSON.stringify(data), // body data type must match "Content-Type" header
      });
      return response.json(); // parses JSON response into native JavaScript objects
    }
    
    
    postData('ajax_data', {action:'service_price',service:service,quantity:quantity,dripfeed:dripfeed,runs:runs}).then((data) => {
        console.log(data);
    });
    

  2. Here:

    let url = 'ajax_data';
    let params = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'action=service_price&service=' + encodeURIComponent(service) + '&quantity=' + quantity + '&dripfeed=' + dripfeed + '&runs=' + runs
    };
    fetch(url, params)
        .then(response => {
            if (response.ok) {
                return response.json();
            }
            throw new Error('Network response was not ok.');
        })
        .then(data => {
            document.querySelector('#charge').value = data.price;
            document.querySelector('#dripfeed-totalquantity').value = data.totalQuantity;
        })
        .catch(error => {
            console.error('There was a problem with the fetch operation:', error);
        });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search