Reputation: 4085
<script>
$(document).ready(function () {
$('#enter').click(function() {
$.post('setCookie.php');
});
});
</script>
<div id="enter">
<a href="http://www.mydomain.com">Enter</a>
</div>
When clicking enter, it is supposed to go to mydomain.com and also set a cookie. It is working in Firefox, but not IE or Chrome. Any ideas?
Upvotes: 1
Views: 275
Reputation: 95
Remember that the .post() call is asynchronous so the rest of the function will continue to flow with the .post() working in the background. You will need to use a callback function inside your post: If you don't want error checking you can skip the if/else and just call the redirect.
$(document).ready(function() {
$.post('ajax/test.html', function(data) {
if (data.success === 'cookieset')
{
// redirect to page
window.location.replace("http://mydomain.com");
}
else
{
// put some sort of notification here that it wasn't set and decide what to do next
window.location.replace("http://mydomain.com");
}
});
});
as far as the redirect you can use either:
to simulate an http redirect use
window.location.replace("http://mydomain.com")
;
or simulates clicking on a link use
window.location.href = "http://mydomain.com";
Upvotes: 0
Reputation: 55
Try with
$('#enter a').click(function() {
Edit: You have a POST
going on the anchor click and then a GET
with the anchor itself. That seams to be clashing on the browser.
For better results, create a SetCookieAndRedirect.php
page and perform the redirect to the url after setting the cookie.
Upvotes: 1
Reputation: 69915
Try this
$(document).ready(function () {
$('#enter a').click(function(e) {
e.stopPropagation();
var href = this.href;
$.post('setCookie.php', function(){
window.location.href = href;
});
});
});
Upvotes: 2
Reputation: 12890
It may be going to the site before it loads for Chrome. You could set a target attribute to "_blank" on the anchor tag, or you could use a callback function after $.post finishes, like so:
<script>
$(function(){
$('#enter').click(function() {
$.post('setCookie.php',function(){
window.location = $('#enter a').attr('href');
});
});
});
</script>
<div id="enter">
<a href="http://www.mydomain.com" onclick="return false;">Enter</a>
</div>
Upvotes: 2
Reputation: 3639
I'd do
<a href="javascript:$.post('setCookie.php');window.location='http://www.mydomain.com'">abc</a>
Upvotes: -1