how to write an ajax call to a controller

65 views Asked by At

I have an ajax call on some client side java script and I want it too call to a controller too set a value too true on button click, I am very new to how ajax works.

In my controller, I have a server.append that is called 'Begin'

$(document).on('click', '.add-button', function(e) {
    $.ajax({
        url: url,
        type: 'POST',
       //here is where I dont know how to call to the controller
    })
});

I know I may have some stuff missing but this is what I am familiar with at the moment.

I want the ajax to connect to the controller function and in my controller function, set a value too true.

1

There are 1 answers

0
Amir Hossein Baghernezad On

To make an AJAX call to a controller function in JavaScript, you need to specify the URL of the controller action in the url property of the $.ajax() function. Additionally, you need to provide the necessary data to the server using the data property.

This is the codebase you might use as the boilerplate:

$(document).on('click', '.add-button', function(e) {
    $.ajax({
        url: '/controller/action', // replace with the actual URL of your controller action
        type: 'POST',
        data: { value: true }, // set the value to true
        success: function(response) {
            // handle the successful response from the server
            console.log(response);
        },
        error: function(xhr, status, error) {
            // handle the error
            console.log(error);
        }
    });
});