3

I have converted following script from jquery based Ajax to Pure javascript-based Ajax but it is not working

here is Jquery based script

var cart = {
'add': function(product_id, quantity) {
    $.ajax({
        url: 'index.php?route=checkout/cart/add',
        type: 'post',
        data: 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1),
        dataType: 'json'
    });
  }
}

Here is converted Javascript code

function addCart(elements, product_id, quantity) {
    // Creating the XMLHttpRequest object
    var request = new XMLHttpRequest();

    // Instantiating the request object
    request.open("POST", "/index.php?route=checkout/cart/add", true);

    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    // Defining event listener for readystatechange event
    request.onreadystatechange = function() {
        // Check if the request is compete and was successful
        if(this.readyState === 4 && this.status === 200) {
            alert("Success");
        }
    };

    var data = 'product_id=' + product_id + '&quantity=' + (typeof(quantity) != 'undefined' ? quantity : 1);
    // Sending the request to the server
    request.send(data);
}

I think there might be a problem in sending data as I am not that much aware of it.

I changed HTML from

<button type="button" onclick="cart.add('{{product_id }}', '{{minimum }}');">Add</button>

to

<button type="button" onclick="addCart(this, '{{product_id }}', '{{minimum }}');">Add</button>
13
  • 1
    is there a specific reason you use the old XMLHttpRequest method instead of fetch API? Commented Feb 21, 2020 at 14:01
  • @GeneSy actually I am unawre of Fetch API Commented Feb 21, 2020 at 14:04
  • 2
    Also, please give more information than 'it doesn't work'. What errors do you get? Commented Feb 21, 2020 at 14:04
  • 1
    You should be using application/json, instead of application/x-www-form-urlencoded; charset=UTF-8. Commented Feb 21, 2020 at 14:05
  • 2
    Well that's because you've not converted the jQuery line $('#cart > ul').load('index.php?route=common/cart/info ul li'); to plain JS Commented Feb 21, 2020 at 14:06

1 Answer 1

3

In order to send a form encoded message in JS, you either need to submit a form or create a FormData object. In your case, we will be creating a FormData.

// Set the needed params.
let formData = new FormData();
const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
formData.append('product_id', product_id);
formData.append('quantity', finalQuantity);

Now, I would recommend using the new fetch API instead of using XMLHttpRequest. So, your request would look something like the following code.

fetch('index.php?route=checkout/cart/add', {
            method: 'POST',
            body: formData,
        }))
        .then(response => response.json())
        .then(() => {
            console.log('Success.');
        }).catch(error => {
            console.log(error.message);
        }).finally(function () {
            console.log('Something you wanna execute even if you caught an error or if the request was successful.');
        });

It is on my opinion, much easier to understand and it is easier to translate from jQuery, because of the similar structure.

So, doing all the corresponding changes, your method would end up looking like this.

function addCart(element, product_id, quantity) {

    // Set the needed params.
    let formData = new FormData();
    const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
    formData.append('product_id', product_id);
    formData.append('quantity', finalQuantity);

    fetch('index.php?route=checkout/cart/add', {
            method: 'POST',
            body: formData,
        }))
        .then(response => response.json())
        .then(() => {
            console.log('Success.');
        }).catch(error => {
            console.log(error.message);
        }).finally(function () {
            console.log('Something you wanna execute even if you caught an error or if the request was successful.');
        });
}

If fetch is not allowed, because of browser compatibility, we can still use XMLHttpRequest. Your code would just need some minor changes.

function addCart(elements, product_id, quantity) {

    // Build the form data.
    let formData = new FormData();
    const finalQuantity = typeof(quantity) != 'undefined' ? quantity : 1;
    formData.append('product_id', product_id);
    formData.append('quantity', finalQuantity);    

    // Creating the XMLHttpRequest object
    const request = new XMLHttpRequest();

    // Instantiating the request object
    request.open("POST", "/index.php?route=checkout/cart/add");

    // Defining event listener for readystatechange event
    request.onreadystatechange = function() {
        // Check if the request is compete and was successful
        if(this.readyState === 4 && this.status === 200) {
            alert("Success");
        }
    };

    request.send(formData);
}
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.