Shyam Krishna Sreekumar Shyam Krishna Sreekumar - 5 months ago 16
Ajax Question

store data via ajax and then go to that URL

I am here for an help.

<a class="text" href="http://test.com?id=87"><img src="/2016/02/BlueFantasyThumb.jpg"><h3>Milky</h3></a>


When i click on this, i need to do certain ajax things that i know how to do. But the problem is i need to perform ajax and then go to that href link.

Upon clicking i know using e.preventDefault(); we can prevent default behaviour. But the case is i dont want to prevent this. I want to occur that event just after that ajax implementation without any obstruction in viewers point.

Any kind of inputs will help me a lot. Thanks.

Answer

You can store the href value in a variable, call e.preventDefault() to prevent redirection and run your ajax code. In your ajax success callback, you can pick the href value and redirect to that link using javascript.

$("a.text").on("click", function(e){
 e.preventDefault();
 var href = $(this).attr("href");
 $.ajax({
  url: URL,
  data: DATA,
  success: function(response){
   // your code here to be executed before redirecting
   window.location.href = href;
  }//success
 });//ajax
});//click
Comments