AJAX in pure JS (using Xmlhttprequest)

Asked

Viewed 51 times

1

I need to send data from one form to another page. I am currently using Jquery and AJAX, but I need to move to pure JS. I’ve seen other similar posts, but I couldn’t make Xmlhttprequest work.

The site I’m working on is an e-commerce with multiple products, where each product has a form with a quick button to add items to the cart (example below):

inserir a descrição da imagem aqui

My form:

<form class="formsCarrinho" method="post" data-app="product.buy-form" data-id="{{ product.id }}" action="/loja/carrinho.php?loja=686651&amp;acao=incluir&amp;IdProd={{ product.id }}" onsubmit="notRefresh(this)">
      <button class="botaoAddCarrinho" type="submit" data-tray-tst="button_buy_product"><span class="botao-commerce-img">Adicionar ao carrinho</span></button>
      <div class="divQntd">
           <span id="product-form-box" data-url-form="/mvc/store/product/variant_form/?loja=686651" class="qntdCarrinho"><div data-app="product.quantity" id="quantidade"><label class="color">Quantidade: <input name="quant" class="text" size="1" type="text" value="1" max="{{ product.stock }}" maxlength="5" oninput="seeMaxInput(this)"></label><span id="estoque_variacao"> / {{ product.stock }}</span></div><div data-app="product.buy-button" id="bt_comprar" class="remove-bg" align="left"></div></span>
           <div class="btnsQntd">
                <button type="button" class="btnQntd minus">-</button>
                <button type="button" class="btnQntd pluss">+</button>
           </div>
      </div>
</form>

My AJAX (working)

$(".formsCarrinho").on("submit", function(e){
    e.preventDefault();
    $.ajax({
        url: $(this).attr("action"),
        type: 'POST',
        data: $(this).serialize()
    });
});

In an attempt to do Xmlhttprequest, I put an onsubmit on the form calling this function. What I’ve tried so far (without much success):

function notRefresh(el){
    el.preventDefault();
    var request = new XMLHttpRequest();
    request.open('POST', el.getAttribute("action"), true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send();
}

I am a little lost and I thank you from now on! (In case you need any more of the code, I’ll try to send it without compromising possible sensitive data).

  • and what is the bug/problem? your code looks right, just to confirm, the url is correct (el.getAttribute("action"))? use the method onreadystatechange to see the answers and detect problems

  • @Ricardopunctual this is the problem: there is no error, it is redirecting to the page in the form action. I went to use onreadystatechange, but I don’t know much about it. Right after request.open, I put this code:request.onreadystatechange = function() {&#xA; if (this.readyState == 4 && this.status == 200) alert("foi!");&#xA; else alert("nop, não foi.");&#xA; }; But it didn’t work, I don’t get Alert because it redirects

  • @Ricardopunctual yes, the el.getAttribute("action") that is correct

  • Your action url looks like GET, but ajax is doing post, the other side.php cart expects what? Try to take the parameters out of the url, pass a parameter (ajax = true), use the post in ajax and also receive post in the.php cart, right at the beginning, (if ($_POST['ajax']) {die("test");}), leave the network tab in the browser’s Speed active, run and track the request, What parameters were sent? What was received in Sponse? If the request type is confused it can happen that the request goes straight through and the entire page is executed in Sponse, this can cause redirects.

1 answer

0

You are not passing the form on the request you are making

function notRefresh(el){
    el.preventDefault();
    var request = new XMLHttpRequest();
    request.open('POST', el.getAttribute("action"), true);
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(el.target);
}

A mess is you use fetch() instead of Xmlhttprequest:

fetch(url, {params})
.then(response=> JSON.parse(response))

Browser other questions tagged

You are not signed in. Login or sign up in order to post.