Reputation: 4886
I am setting cookie in Jquery according to screen width . Like this
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).on('pageinit','#outerPage',function(){
var windowWidth = $(this).width();
// alert(windowWidth);
if(windowWidth <290)
{
console.log('cookie:small');
$.cookie("adds", 0);
//setTestCookie("adds","0");
}
else
{
console.log('cookie :Big');
$.cookie("adds", 1);
//0setTestCookie("adds","1");
}
});
</script>
And then I am using these cookie to validate a div in php along with some other parameter in the same file like this
<?php
if($current_item == 2 && $_COOKIE['adds'] == '1')
{
//place the adsense after the third ad.
?>
<div id="bloque" class="addsTpl addBigphone" style="min-height:90px">
<div class="google_add">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- resultmobile -->
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:90px"
data-ad-client="ca-pub-765756"
data-ad-slot="657567"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script></div>
</div
<?php
}
?>
So far so good .The problem I am facing is that the if() statement is only getting true after I reload the page .
What I have understood is that the cookie is set after the server if() statement is executed in the first time as the Jquery will execute only after the server script is done loading .
Can any one suggest me any other method I can use to do this .
Thanks & regards
Upvotes: 0
Views: 210
Reputation: 173
thats correct, the server side code is running first and serving up you page which only then executes the javascript - which is too late for you
You could move the window size test that you run to set the cookie into an earlier page in your app (e.g. a login page) or you could have a 'hidden' page which runs your javascript and then immediately redirects to your main page e.g.
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>
<script>
$(document).on('pageinit','#outerPage',function(){
var windowWidth = $(this).width();
// alert(windowWidth);
if(windowWidth <290)
{
console.log('cookie:small');
$.cookie("adds", 0);
//setTestCookie("adds","0");
}
else
{
console.log('cookie :Big');
$.cookie("adds", 1);
//0setTestCookie("adds","1");
}
// redirect to the actual page you want
document.location.href = 'new main page url'
});
</script>
So your hidden page is never rendered - it just runs the javascript and then redirects to the main page.
Hope that helps Garrett
Upvotes: 2