Search code examples
javascriptjqueryajaxclickcall

Problem: pass some parameters in ajax call (post)


I have 2 functions: one to add and another to delete. I would like to reuse the same ajax call to send the parameters that are added or deleted. How can I optimize my function?

Here is my code at the moment

jQuery(document).ready(function () {

    function ajaxCall(action, callback) {
        jQuery.ajax('/index.php', {
            type: 'POST',
            dataType: 'json',
            data: {
                option: 'quotes',
                view: 'request',
                task: action,
                format: 'raw',
                tmpl: 'component'
            },
            success: function (response) {
                if (response.error == true) {
                    alert(response.errors.join('\n'));
                }
                else if (response.status == "DONE") {
                    callback(false);
                }
            },
            error: function (xhr) {
                console.log("Error: ", JSON.stringify(xhr));
                callback(true);
            }
        });
    }

    jQuery('#ajax_add').click(function (event) {
        event.stopPropagation();

        var id = jQuery('#id').val();
        var price = jQuery('#price').val();

        //I want to send two variables: id, price

        ajaxCall("addData", function (error) {
            if (error) {
                alert("Error!.");
            }
            else {
                alert("It's OK!");
            }
        });
    });

});

The function to delete is similar to "addData" function, it also calls "ajaxCall" and will send parameters to remove.

I'm blocked and I do not know how to solve it, I hope you can give me some help, thanks


Solution

  • You could add a new argument to the ajaxCall function and send the parameters as an object them merge them with the data you've in the function like :

    function ajaxCall(action, params, callback) {
    

    Then in the ajax call :

    jQuery.ajax('/index.php', {
        type: 'POST',
        dataType: 'json',
        data: $.extend(params, {
            option: 'quotes',
            view: 'request',
            task: action,
            format: 'raw',
            tmpl: 'component'
        }),
        ...
    

    The call inside the event will be like :

    ajaxCall("addData", {id: id, price: price}, function (error) {