Browser won't set cookie from an onclick event - php

I'm pulling my hair out with this bug, although I'm sure it's something obvious. Apologies if it is.
The following javascript successfully sets my cookie:
<script type="text/javascript">
$(document).ready(function(){
$.post('../setCookie.php',{'region':'test'});
});
</script>
But as soon as I tie the same code to an onclick event, like so...
<script type="text/javascript">
$(document).ready(function(){
$("#us a").click(function(){
$.post('../setCookie.php',{'region':'en-us'});
});
$("#uk a").click(function(){
$.post('../setCookie.php',{'region':'en-gb'});
});
});
</script>
<ul>
<li id="uk"><a href="http://www.example.com/uk">
<span>Enter UK site</span></a></li>
<li id="us"><a href="http://www.example.com/us">
<span>Enter US site</span></a></li>
</ul>
..it no longer sets a cookie! Even though the same code is called an executed in exactly the same way (I step through it fine, and see everything as it's supposed to be).
Repeat: The javascript is firing fine. I am stepping through setCookie.php and everything is the same... except no cookie at the end of it.
What's going on? I'm guessing it's browser security or something?
For anyone who's interested, here's how I solved it:
<script type="text/javascript">
$(document).ready(function(){
$("#us a").click(function(e){
e.preventDefault();
$.post('../setCookie.php',{'region':'en-us'},
function() {
window.location = "http://www.example.com/us";
}
);
});
$("#uk a").click(function(e){
e.preventDefault();
$.post('../setCookie.php',{'region':'en-gb'},
function() {
window.location = "http://www.example.com/uk";
}
);
});
});
</script>

I don't see anything stopping the normal link click going through? If you have nothing preventing the normal a href to go through, there won't be any time to do the $.post request before the page changed already.
Try the following:
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
$.post('../setCookie.php',{'region':'test'});
});
});
It will stop the page change for links, but at least should pass the cookie. Now, if you want the page to be loaded as well, then add a onComplete method to the request, so that once the cookie data has been succesfully sent, you can then continue the page change.

Place this code where the < script > tags is at: (I assume the < head >)
$(document).ready(function(){
$("#us a").click(function(){
$.post('../setCookie.php',{'region':'en-us'});
});
$("#uk a").click(function(){
$.post('../setCookie.php',{'region':'en-gb'});
});
});

If it was a security issue , you will see an error on your console (firebug\webkit\IE dev tools)
I suppose what I would do in this situation is changing the click event and put it here:
<script type="text/javascript">
$(document).ready(function(){
$("#someid > li").click(function(){
$.post('../setCookie.php',{'region':$(this).attr("id")});
});
});
</script>
and then..:
<ul id="someID">
<li id="uk"><a href="http://www.example.com/uk">
<span>Enter UK site</span></a></li>
<li id="us"><a href="www.example.com/us">
<span>Enter US site</span></a></li>
</ul>
I advice not to use JavaScript \ jQuery inside your HTML , just use document.ready() and bind your events (if you use jQuery of course)

Most likely because it's trying to access jQuery ($) before it's created. It would be best to use document.ready from your first example for this.

Related

Jquery Mobile auto-refresh every X second

Jquery Mobile auto-refresh every X second
Porting to JQM and having trouble getting page that automatically refreshes content every X seconds to display properly. Have read dozens of related threads but not finding a clear solution with code example. The purpose of this page is to display arrival and departure information on something similar to what you might see in an airport.
Previous approach was as follows with javascript in the header. PHP content (a styled table) would load to named DIV after one second then refresh every ten seconds automatically and worked great:
Controlling Page:
<head>....
<script type="text/javascript">
function Refresh_My_DynamicContent(){
$("#id_My_DynamicContent").load("NewContent.php");
setTimeout(function() { Refresh_My_DynamicContent(); },10000);
}
</script>
<script type="text/javascript">
setTimeout(function() { Refresh_My_DynamicContent(); },1000);
</script>
</head>
<body>
<div data-role="page">
<div id=” id_My_DynamicContent”></div>
</div>
When I use this same approach with JQM the content displays but without JQM, pop-ups all expanded, etc. Could anyone please help direct me to the proper approach with JQM to have a “hands-off” display that refreshes on its own with code example?
I think your code should be like
<script type="text/javascript">
$(function(){
setTimeout(function() {
$("#id_My_DynamicContent").load("NewContent.php",{'reload':true});
},1000);
});
</script>
also check that after the first call is working
I am not sure if jquery moble also relaces the all head if that is the case you should also
echo the js from the PHP
<?php
echo '<script type="text/javascript">
$(function(){
setTimeout(function() {
$("#id_My_DynamicContent").load("NewContent.php",{'reload':true});
},1000);
});
</script>';
?>

jQuery's GET is acting up for me. Using CodeIgniter. It returns source code for a view instead of one value

I am trying to test the jQuery GET method, but what I am getting as result is completely insane. All I am trying to do is call a function from my controller with jQuery and then display the echoed value in a div within my view. Below is my code and finally a breakdown of the problem I am encountering.
Controller
public function generate_suggestions2() {
echo "James";
}
View views\suggestions_v.php
<body>
//This DIV is used a button to call the jQuery function
<div id="next_btn">
<p>Click here to display a name</p>
</div>
//In this div the value retrieved by the jQuery should be displayed
<div id="listB"></div>
//This is the function that calls the function within my controller
<script type="text/javascript">
$( "#next_btn" ).click(function() {
$.get("core/generate_suggestions2/",
function(data) {
$( "#listB" ).html(data);
});
});
</script> //For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
</body>
Now the problem is that when I click the DIV next_btn it does NOT display the James in the DIV listB.
Instead it populates the DIV listB with my source code from my main view views\core_v.php
I have no idea how this is even remotely possible, so please if you have a clue or even better you know what I am doing wrong please tell me. I am trying to get this to work for the past three days without any success or progress :(
Try using this code in your view
<script type="text/javascript">
"$( "#next_btn" ).click(function() {
$.get("<?php echo site_url().'/core/generate_suggestions2';?>",
function(data) {
$( "#listB" ).html(data);
});
});"
</script>
Also delete the </script> tag just right before this block comment.
Regarding this comment you have:
//For some reason I need to put the script at the end of the body. When it's in the head nothing happens when I click the button. Also something I do not understand.
It is because the DOM is not yet fully loaded and Javascript executes its code when the browser has finished loading the DOM you are referring to. So you either have to put it after the DOM element you want to edit, like you do now or you could use $(document).ready(function(){
}
); .
Read more about it here
This line is pretty strange:
</script><script type="text/javascript">
Try to delete first closing tag 'script' on it.

Pick an element from included PHP using Javascript

I have been making a website that has lots of pages. Hence decided to put the navigation bar in a separate php file to reduce re-work in all those pages in case of changes. So in my index.php I have included the navigation bar like:
<?php include 'navbar.php'; ?>
And the navbar.php looks like:
<div id="nav">
<ul>
<li pg="#home" >home</li>
<li pg="#pack" >packages</li>
<li pg="#about" >about</li>
</ul>
</div>
In the index.php, I have a javascript onClick function to select the <li> from navbar:
<script type="text/javascript">
var oldpg = "#home";
$(document).ready(function() {
$('#nav ul li').click(function() {
//here are the codes to hide/show divs });
});
</script>
But when you click those <li> nothing happens. I think the js is not picking up the elements from the php. How can I refer to those elements in a separate php file?
You need to fix your JavaScript:
$(document).ready(function() {
$('#nav ul li').click(function() {
//here are the codes to hide/show divs });
});
}); // you left off this closing
You can use Chrome DevTools or Firebug to view the console.
Use on and try. Not tested but that may be the problem here. Try
$(document).ready(function() {
$(document).on('click', '#nav ul li', function(e) {
//Your code
});
});
Also make sure that you included jQuery library
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
The code you showed us is correct. As long as the div with id "nav" is indeed being displayed, make sure you are including the jQuery library correctly. If it is, your error must reside inside whatever you did inside the click event handler $.click (in //here are the codes to hide/show divs).
Thanks for replying #Retsam #Campari #Chris #Ankit
As #Retsam said, I tried with Chrome console and found the error to be
Uncaught reference error: $ not defined (Firebug console didn't give any error/message)
The reason was because I had put my code before linking with the jQuery library.
So I moved my
<script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
above the onClick function and it worked.
Silly me ...
Thanks guys

PHP remember chat open/close method

On my site in the bottom left hand corner there's a chat tab that you can open and close with a click. The button is named 'trigger' and the chat panel is named 'panel'. I'm not familiar with javascript really, I just cobbled this together from existing scripts, anyway, the code I use that works this is:
<script type="text/javascript">
$(document).ready(function(){
$(".trigger").click(function(){
$(".panel").toggle("fast");
$(this).toggleClass("active");
return false;
});
});
</script>
What happens though is if the user opens chat then goes to another page, the chat must be reopened again. I need a way to keep the chat open if it's already open.
Maybe something in the body onload tag? And using sessions?
Note: My site's in php
With jquery-cookie you can save state of the chat class toggle. Something like this:
<script type="text/javascript">
$(document).ready(function(){
if($.cookie('panel-active')) {
$(".trigger").toggleClass("active",true);
}
$(".trigger").click(function(){
$(".panel").toggle("fast");
$(this).toggleClass("active");
$.cookie('panel-active', $(this).hasClass("active"), { path: '/' });
return false;
});
});
</script>

Load when page loads, not on click, etc(ajax,php)

$(function(){
$('p.load_it a').click(function(){
$('#demo_content').load('http://d.com/myphp.php? nice=1149632');
return false;
});
});
Click me to load some HTML with AJAX.
<div id='demo_content'>
</div>
I wanted to know if anyone can give me advice as to how I can load this kind of Effect not by a click, but by an animated "loading" effect.
Let me know if anyone has any suggestions.
This will execute your load() call when the DOM on the page is ready.
$(document).ready(function() {
$('#demo_content').load('http://example.com/myphp.php? nice=1149632');
return false;
});
As for your 'loading' request, I suggest you take a look at this StackOverflow question. Nevermind, I just saw you already had something in mind.
$(document).ready(function() {
$.ajax({
url: 'http://example.com/myphp.php?nice=1149632',
success: function(data) {
$('#demo_content').html(data);
}
beforeSend: function(){
//show loading here
$('#demo_content').html("Loading...");
}
});
});
If you want the javascript code to be executed when the page has been loaded, you can also add the script at the bottom of the page, like this:
<script>
$('#demo_content').load('http://example.com/myphp.php? nice=1149632');
</script>

Categories