-1

I have button like this.

<input onclick="reply_click(this.id,this.name)" target="_blank" type="submit" id="'+clickid+'" name="'+click_ip+'" value="Check">

And javascript like this.

function reply_click(clicked_id,click_ip)
{
    var data        = 'sendCID=' + clicked_id;
    alert(data);
    $.ajax({
                type: 'POST',
                url: 'send_data.php',
                data: data, 
                async:false,
                success: function(){
                success = true
                }
            });
    if(success){
      window.open('http://whatismyipaddress.com/ip/'+click_ip)
    }
}

In Alert working correctly, but data not send to database. How to fix this?

Thank you...

Zayn
  • 71
  • 3
  • 12
  • Seeing as it's not asynchronous at all with the `async:false` flag, it's not really a duplicate, but as that flag should never be used, and should be removed, it's still a duplicate – adeneo Oct 14 '16 at 21:04

1 Answers1

0

The flag of this answer as a duplicate is sound. But until then, I'll tell you why it doesn't work.

Think about this code:

var a = 0;
function do_something() {
   a = 1;
}
a = 2;
console.log(a);
do_something();

What is printed to the console? 2. Just because the code is happens to come physically above some other code, does not mean that it is called in that order. It's easy to tell in this example, but now let's look at your code.

...
            success: function(){
                success = true
                }
            });
    if(success){
      window.open('http://whatismyipaddress.com/ip/'+click_ip)
    }
...

You see, success is being set inside the return function. That doesn't happen until a later time. But the next line if(success), runs immediately! That means success hasn't been changed yet. You need to move window.open inside the success callback as well. That's when you want it to happen!

success: function(){
     window.open('http://whatismyipaddress.com/ip/'+click_ip)
});
aaronofleonard
  • 2,546
  • 17
  • 23
  • 1
    A shorter summary is: The `$.ajax` call says "I'll do this later, carry on for now" so the code after runs *before* the code inside. So success has not been set when you check it. – freedomn-m Oct 14 '16 at 20:51
  • Except that he has `async: false`, so it should be executed in order. – Barmar Oct 14 '16 at 21:27