Hello everyone, there is a general link:

<a href="http://google.ru" onclick="return myFunc('123', 'abx')">Click</a> 

There is a function in javascript:

 var myFunc = function() { $.ajax({ type: "POST", url: "", data: { id: id, updated_at: updated_at }, success: function (result) { if(result == 'ok') { return true; } else { alert('error'); return false; } } }); } 

I need to cancel the link click if ajax returned alert ('error').
return false does not help. What can be done in this case?

  • In the if (result == 'ok') block, either directly go to google.ru , or trigger a click on the link (and not to get hung up, use the flag). - Regent
  • @Regent I need the link to remain as it is and the person could open it in another tab or simply, you just need to cancel the event, and how to do it, xs - Kexer
  • You make the decision asynchronously, so it is never "easy". In any case, you will have to block the first click event and, if the Ajax request is successful, either generate the second one or just perform the desired action. - Regent
  • You can, of course, make a synchronous Ajax request, but it’s worth shooting for that. And the return in the success function will be useless from the word "completely". - Regent

1 answer 1

Since the decision is made asynchronously, you have to block the first request and, if the Ajax request succeeds, generate the second one or follow the URL using JS.

An example implementation with generating a second event and using a flag:

 var $link = $("a"); var clickIsConfirmed = false; var result = 0; //для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° $link.on("click", function() { if (!clickIsConfirmed) { $.ajax({ url: "", error: function() { //для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° result++; //для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° if (result == 2) { //для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° clickIsConfirmed = true; $link[0].click(); } } }); return false; } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="">Click</a> 

An example implementation with transition using JS:

 var $link = $("a"); var result = 0; //для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° $link.on("click", function() { $.ajax({ type: "POST", url: "", error: function() { //для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° result++; //для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° if (result == 2) { //для ΠΏΡ€ΠΈΠΌΠ΅Ρ€Π° window.location.href = $link.attr("href"); } } }); return false; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="http://google.ru">Click</a> 

  • it's not that at all, I have a completely different example ... - Kexer
  • @Kexer How is your example different from mine? - Regent