Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery ajax button click event firing twice?

I have a Employee page which shows list of employees with an edit option. On clicking the edit button jquery-ajax is used to fetch the data from the server. The problem is when I click the edit button the event is firing twice.

I am using a seperate js file and is referring the file to the main page.The script was working fine until i moved it to the seperate js file.

enter image description here

The Jquery script is

  //ajaxGet on edit button click
$(document).on('click', '.editRole', ajaxGet);

 var ajaxGet = function (e) {       


    var spinner = $(this).parent('div').find('.spinner');
    var href = $("#editMenuSettings").data("url");
    var menuRoleId = $(this).data('id');

    spinner.toggle(true);

    var options = {
        type: "GET",
        url: href,
        data: { menuRoleId: menuRoleId }
    };

    $.ajax(options).success(function (data) {
        spinner.toggle(false);
        $(".modal-body").html(data);
        $(".modal").modal({
            backdrop: 'static'
        });
    });

    $.ajax(options).error(function (data) {
        spinner.toggle(false);
        toastr.error("Oops..Some thing gone wrong");
    });

    return false;

};
like image 299
ksg Avatar asked Sep 28 '15 08:09

ksg


1 Answers

You call $.ajax twice.

At lines

$.ajax(options).success(function(data)...

$.ajax(options).error(function(data)...

you actually make two different AJAX calls - one with success callback only, another one with error callback.

In your case, your call should look like this:

var options = {
    type: "GET",
    url: href,
    data: { menuRoleId: menuRoleId }
};

$.ajax(options)
    .success(function (data) {
        spinner.toggle(false);
        $(".modal-body").html(data);
        $(".modal").modal({
            backdrop: 'static'
        });
    })
    .error(function (data) {
        spinner.toggle(false);
        toastr.error("Oops..Some thing gone wrong");
    });

return false;

It will set both callbacks to the single AJAX call and execute this one.

like image 177
Yeldar Kurmangaliyev Avatar answered Nov 04 '22 06:11

Yeldar Kurmangaliyev