-1

I'm trying have user input some data, use ajax to post it and after that use that info to create objects dynamically, but my if statement isn't working. I need the code to be under click function because of many $(this) targeting inside the code I'm trying to fire after ajax post.

 $(document).on('click' , ".addition" , function(event) {

    $(".submitfolder").click(function() {
     var data3 = $("#form2 :input").serialize();
     var data4 = $("#form2 :input").val();
     nameforfolder = data4;

       $.ajax({
         url: "userfolders.php",
         type: "POST",
         data: data3,
         success: function() {
         var asd = 1;
         }
      });

   if (asd > 0) {
      //do stuff that needs data4.

   } else {        
      //something

   }
 });
ArK
  • 20,698
  • 67
  • 109
  • 136
  • partial dupe http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323 – Kevin B Aug 22 '16 at 18:36

2 Answers2

-1

The problem is that in your function on success, you declare a new variable asd that will be only visible in that function. So you should declare asd in your first function and then just change it in your second function.

  var asd = 0;
  $(".submitfolder").click(function() {
         var data3 = $("#form2 :input").serialize();
         var data4 = $("#form2 :input").val();
         nameforfolder = data4;

           $.ajax({
             url: "userfolders.php",
             type: "POST",
             data: data3,
             success: function() {
             asd = 1;
             }

          });
Dan Lupascu
  • 308
  • 1
  • 3
  • 9
-1

You need to understand that Javascript and AJAX works asynchronously, that means javascript continues to execute next line of code even if the previous line isn't done yet! So your if (asd > 0) statement is working with a variable which in time of execution isn't defined. So you have to place that logic in your success callback function of $.ajax call.

And if you're worried about $(this), just use a well-known common hack

var _this = this;

In the end, you should end up with something like this:

$(".submitfolder").click(function() {
  ...  
  var _this = this;

  $.ajax({
    url: "userfolders.php",
    type: "POST",
    data: data3,
    success: function() {
      var asd = 1;
      if (asd > 0) {
        // instead of $(this).hide()
        $(_this).hide();
      } else {
        // something
      }
    }
  });
});
LordDave
  • 1,118
  • 1
  • 11
  • 22