Not sure how to connect an AJAX call to a controller and make it update a object

113 Views Asked by At

I am very new to ajax calls and controllers, please be patient with me.
I have some client side JS that I need to add an ajax call to update a boolean to true once a button is clicked
Client Side JS:

$(document).on('click', '.add-to-cart', function(e) {
    $.ajax({
        url: url,
        type: 'post',
        data: true// but I do not know what goes here
    success:(function () {//dont know what response to put in
       //I know it handles response from server but what would I put in here to update 
    }).fail(function (err) {
        console.log({err});
    });
});

Controller:

server.post(
    'updateButtonAdded',
    function (req, res, next) {
        var addToCartButtonClicked = customer.profile.custom.AddButton;// declaring the custom attribute I want to show on a profile if the button is clicked       
        if (??) {
           // I know I need to add something here to have the logic of when the button gets clicked, set the addToCartButtonClicked = true to update to the customer profile and have it checked because I set as a boolean 
        }
    next();
    }
);

I tried to fill out what I dont understand, please assist if can, I am very confused when it comes to controllers and ajax calls. More the explanation the better for me!

1

There are 1 best solutions below

0
Maher Nabil On

normally what we would do, is to set the URL in the ISML, get the URL value in the JS files, then make the AJAX call. Here is an example:

ISML:

<input id="yourIdHere" type="hidden" value="${URLUtils.url('YOURCONTROLLER-updateButtonAdded')}"/>

JS:

var url =  $('#yourIdHere').val();
$.ajax({
  url: url,
  method: "GET",
  success: function (data) {
    //your success code
  },
  error: function () {
    //your error code
  },
});