Unable to close dialog with ajax success

I invoke the on-the-fly dialog box (on click) without first setting it as var. For instance:

$(".deleteSaved").click(function() { save_id = $(this).attr('id'); div="<div>Are you sure you want to delete this?</div>"; $(div).dialog({ buttons: { "Delete": function() { $.ajax ({ url:"util.php", data:"q=0&f=delete&save_id="+save_id, success: function(result){ $(this).dialog("close"); //this line is not working $("#toprow"+save_id).fadeOut(); $("#botrow"+save_id).fadeOut(); } }) }, "Cancel": function() { $(this).dialog("close"); } }, modal: true, title: 'Delete Saved Signal', resizable: false }); }); 

But when I call $(this).dialog("close"); in ajax success function, I get the following error:

 Uncaught cannot call methods on dialog prior to initialization; attempted to call method 'close' 

Inside the button cancel $(this).dialog("close"); works just fine.

How can I make the close function work as a result of a successful ajax call?

+4
source share
4 answers

The internal success function 'this' does not indicate a dialog object. You may need to save the dialog object in another variable, as shown below.

 "Delete": function() { var that = this; $.ajax ({ url:"util.php", data:"q=0&f=delete&save_id="+save_id, success: function(result){ $(that).dialog("close"); //this line will work $("#toprow"+save_id).fadeOut(); $("#botrow"+save_id).fadeOut(); } }) }, 
+11
source

You cannot reference it with $ (this), because you are in another function, you can do it,

 div="<div id='yourDialog'>Are you sure you want to delete this?</div>"; //........... $("#yourDialog").dialog("close"); 
+2
source

The scope of the success function does not match the scope for the delete or cancel functions ...

Try using something like var myDiv = $(div); and then you can call it wherever you want. Minimize the use of $(this) to avoid such situations.

Also, instead of using $(this).attr('id') this.id , use this.id ;)

0
source

Your $ (this) has a different meaning in the function of success. Try to assign it to a variable and use it in your ajax success function

0
source

Source: https://habr.com/ru/post/1382631/


All Articles