Jquery ajax button click event firing twice?
Asked Answered
P

1

6

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;

};
Pope answered 28/9, 2015 at 8:18 Comment(0)
C
15

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.

Counterman answered 28/9, 2015 at 8:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.