views:

43

answers:

3

I have the following link-

<a href="ex.com" onClick="return popitup2('<?php echo $var3; ?>');">Grab Coupon</a>

Where i have initialized $var3 like this

$var3 = "brand1,camp2";

The code for the function popitup2() is -

<script language="javascript" type="text/javascript">
function popitup2(id) {
$.ajax({
   url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
   success: function(){
     alert( "Data Saved: " );
   }
 });
    newwindow2=window.open('','name','height=225,width=350');   
var tmp = newwindow2.document;

....some more code... ...at end...

    return true;
}
</script>

Now when i click the link ex.com opens up without any alert i.e without running the php script through ajax and the javascript after that. If i remove the ajax call from the function popitup2() then the remaining javascript gets executed correctly.

A: 

What's happening here is that you're performing an asynchronous AJAX request, meaning that when you perform the request, the rest of your function continues to run. When the AJAX result comes back, it then fires the alert in your success function, but since you've clicked a link, you've navigated away from that page already.

Try adding an async: false to the ajax function's parameters to wait for the result to come back before continuing, like so:

$.ajax({
    url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
    async: false,
    success: function() {
       alert( "Data Saved: ");
    }
 });
Tim S. Van Haren
adding the async parameter did not help. Still the same thing. It just migrated to the other page without running any script.
ayush
A: 

You are passing two arguments to JS function. But function prototype (first line) accept only one. This lead into JS error.

srigi
var3 is just a single variable initialized to "sometext,sometext" value. It is a single variable.
ayush
+1  A: 

Agree with previous answer that you are executing asynchronous Ajax request. From documentation Async parameter may not work in 2 cases: Cross-domain requests or if dataType: "jsonp". If you are doing crossdomain request, I can suggest only:

<a href="ex.com" onClick="return popitup2('<?php echo $var3; ?>', this);">Grab Coupon</a>
<script type="text/javascript">
function popitup2(id, link) {
  $.ajax({
    url: "http://jainkunal.com/wordpress/wp-content/trackclicks/clickcounter.php"+"?"+id,
    context: link,
    success: function(){
      alert( "Data Saved: " );
      window.location = $(this).attr("href");
   }
  ....
  return false;
});

With such approach we track clicking for sure. There is another problem with such approaches, that tracking server should be fast otherwise, user will wait long time till navigate to resource.

xplanner expert