简体   繁体   中英

Is there a way to add an OnSuccess script to my Ajax call

I have the following script:

$.ajax({
    url: '/Switch/showOptions',
    data: {
        switchid: "331",

    },
    type: 'get',
    success: function (html) {
        $('#showoptions').html(html);
        $("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
        OnSuccess('createsuccess')         
    },
});

What I am trying to do is to fire an OnSuccess script after showing the dialog, currently I am getting an exception that OnSuccess is not defined? So can anyone advice how I can fire an OnSuccess script for my Ajax call?

Try this using jQuery.when() as described in this answer here :

Provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events.

So with that in mind, here is your code reworked to use jQuery.when() :

var ajax_action = $.ajax({
    url: '/Switch/showOptions',
    data: {
        switchid: "331",

    },
    type: 'get',
    success: function (html) {
        $('#showoptions').html(html);
        $("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
    },
});

$.when(ajax_action).then(function(data, textStatus, jqXHR) { OnSuccess('createsuccess'); });

Or if you just want to test this concept, change the jQuery.when() to be this:

$.when(ajax_action).then(function(data, textStatus, jqXHR) { alert('I am a success!'); });

EDIT: Last edit to try and address original posters request. They want to fire a script called createsuccess , so just do this:

$.when(ajax_action).then(function(data, textStatus, jqXHR) { createsuccess(); });

Your code should work if you add a ; after your OnSuccess call. This isn't an event to be fired but it is aa function that will be executed after the first two statements.

function OnSuccess(p_Success) {
    alert('it worked!');
}


$.ajax({
    url: '/Switch/showOptions',
    data: {
        switchid: "331",

    },
    type: 'get',
    success: function (html) {
        $('#showoptions').html(html);
        $("#showoptions").dialog("show"); //This could also be dialog("open") depending on the version of jquery ui.
        OnSuccess('createsuccess');
    },
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM