views:

133

answers:

1
<script type='text/javascript'>
$("#cart").click(function() {
var loadUrl = "ajax_redirect.php";
var val = "2";
$.post(loadUrl,
{ page: "cart", data: val },

   function(data)
   {
 alert(data);
     alert("Course added to Cart");
   }
  );
});
</script>
<body>
 `<a class="button" id="cart" href="#" title="Apply"><img src="images/button.png" alt="apply" />Apply</a>`
</body>

If i click the <a> link nothing happens but refreshing. I am not able to get return data value.

+1  A: 

Your script is run before the a element exists and is ready in the DOM. You should have wrapped the entire thing in a $(document).ready() call, like so:

$(document).ready (function () {
    $("#cart").click(function(event) {
        event.preventDefault ();
        var loadUrl = "ajax_redirect.php";
        var val = "2";
        $.post(loadUrl,
            { page: "cart", data: val },
            function(data)
            {
                alert(data);
                alert("Course added to Cart");
            }
        );
    });
});

Also note the event.preventDefault(), to prevent the link from doing it's default action

K Prime
Thanks Prime, but one doubt page is redirecting to the requested url but i'm not able to get the request value. function alert(data) is not working. I am getting the value $_POST['page'], $_POST['data']
RSK
Sorry, do you mean your backend (PHP) cannot read the parameters you passed? Or that the Javascript cannot get the data you passed back?
K Prime
This answer helped me out greatly in my first venture into AJAX using jQuery! Good show!