Here's a minimum example -
index.php
<?php
$count = file_get_contents("count.txt") + 0;
file_put_contents("$count.txt [loaded]", '');
file_put_contents("count.txt", $count + 1);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<main>
<p> hi there </p>
</main>
<script type="text/javascript">
var id = "<?php echo $count; ?>";
</script>
<script src="script.js"></script>
</body>
</html>
script.js
$(document).ready(function ()
{
$(window).bind('beforeunload', function () {
$.post("unloader.php", { id : id });
});
});
unloader.php
<?php
file_put_contents("$_POST[id] [unloaded]", '');
When I open the webpage, a file is created with the count number as its name.
When I close the tab jquery requests unloader.php which is just a standalone script that creates a file with the count number as its name too.
Sometimes it works, sometimes it doesn't.
I mean the opening file is always created. But sometimes the file which has to be created on closing is not made.
Any idea where the issue occured ?
You can't (reliably) make AJAX calls when unloading the page. Because it's being unloaded, anything still in progress will be dropped.
If the browser's fast enough with the AJAX call (or the server's slow enough in responding to the new page load) then you should see a result, but it is not at all reliable.
Related
I want to write a web page and use jquery to GET a small amount of data from php at the server, but in the same file, when i click a button. I want to send ?nm=bill and answer with 'bob'. i press the button but it doesn't seem to arrive at the server. I get the contents of the file i am sending the query to. I clear the browser, firefox, history before i press the button. Here is the code.
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
$("#btn").click(function(){
console.log("btn pressed");
$.get("a_foo.php?nm=bill", function(data, status){
alert("Data:\n" + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET"){
var_dump($_SERVER["REQUEST_METHOD"]);
if ($_SERVER['QUERY_STRING']) {
echo "bob";
}
}
?>
</body>
</html>
but in the same file
So all of the code shown is in one file? If that's the case then any request to that file is going to receive the entire response.
I get the contents of the file i am sending the query to.
That's expected behavior. The very first thing this file does is emit all of the HTML at the start. Then it executes some PHP and conditionally emits a single value at the end.
Putting these things into separate files would be the ideal approach. One file is the UI, the other file is the service that handles the AJAX request and returns just the expected data.
But if you really want them to be in the same file then you'd need to conditionally return all of that HTML. Since the only difference between the requests at this time is whether or not a query string is present then your whole PHP file would look something like:
<?php
if ($_SERVER['QUERY_STRING']) {
echo "bob";
} else {
/>
<!-- ALL of your other HTML goes here -->
<?php
}
?>
As you can probably imagine, this structure gets pretty ugly and difficult to maintain pretty fast. Which is why the preferred approach is to separate these things into their own files. Each PHP file would do just the one thing it needs to do, rather than having one big PHP file which conditionally does multiple different things.
The current target of request is a_foo.php i fix it and show bob if the get nm is bill else show html
<?php
$_nm = $_GET["nm"];
if($_nm == "bill"){
echo "bob";
}
else
{
?>
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
$("#btn").click(function(){
console.log("btn pressed");
$.get("?nm=bill", function(data, status){
alert("Data:\n" + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p>
<body>
</body>
</html>
<?php
}
?>
I'm trying to use jQuery to count clicks, store them in a cookie and then echo them back out.
I've found some code online that allows me to do it, but I dont seem to be able to make it work. It's creating the cookie file and storing '0' in it, but it does not update on clicking of links. Any guidance as to whats going wrong with this code would be great. :
clickCount.js
jQuery(function(){
$("a").click(function{
var cookiename = 'linkcounter';
if($.cookie(cookiename) == null){
$.cookie(cookiename, 0);
}
$.cookie(cookiename, $.cookie(cookiename)+1);
});
});
index.php
<?php
session_start();
$counter_file = 'counter';
if(!file_exists($counter_file)){
file_put_contents($counter_file, 0);
}
$counts = (int)file_get_contents($counter_file);
file_put_contents($counter_file, $counts++);
// you can use $counts if you want to display it on the page.
?><!DOCTYPE html>
<html>
<head>
<title>Link Click Counter Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="countdetect.js"></script>
</head>
<body>
<br />
<br />
Link clicks: <?php echo $counts; ?>
</body>
</html>
In you PHP code, you're not storing the click count into a cookie, but into a file.
You either have to update the counter file by by making an AJAX request from your JavaScript to your server, or actually write a cookie within your PHP file:
<?php
$cookieName = 'linkcounter';
$count = isset($_COOKIE[$cookieName]) ? (int)$_COOKIE[$cookieName] : 0;
$count++;
setcookie($cookieName, $count);
?>
Link clicks: <?=$count?>
Make sure you use the same cookie name in both JavaScript and PHP.
How to make jAlert() Message Box without OK Button.
Basically what I want is to use jAlert() like Jquery Block UI
Please check this fiddle http://jsfiddle.net/Bumts/2/.
There has been some modifications in the core jquery.alert.js, since there has been no overlay param. I made the changes to pass overlay (6th parameter) option to pass for it. You could replace the jquery.alert js code with my modified one.
$(function(){
$('#test').click(function(){$('#test3').jAlert('This is a jAlert Warning Box',"warning",'warningboxid', '', '', 1);});
});
Use JQuery events !!
Example ::
Case 1 : If you are trying to trigger your button after an interval
then use
setInterval( "clickRight()", 5000 );
function clickRight()
{
$('.slide_right').trigger('click');
};
Case 2 : If you are waiting for user to type some thing on to an input field
$('#form').on('mousedown',function(e)
{
if(e.which===1)
{
//call your function alerting message here//
}
}
Short Code ::
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input id="whichkey" value="type something">
<div id="log"></div>
<script>
$('#whichkey').on('mousedown',function(e){
alert("Error");
});
</script>
</body>
</html>
I'm learning php/javascript so don't smile...
I try from page1.php to post 3 variables to page2.php.
I'm not sure what's wrong...
Here is the code (simplified mode):
page1.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
window.onload = post_text;
function post_text() {
test1="111";
test2="222";
test3="333";
$.post("page2.php", { test1:test1 , test2:test2, test3=test3 });
}
</script>
</body>
</html>
page2.php
<?php
$a=$_POST['test1'];
$b=$_POST['test2'];
$c=$_POST['test3'];
echo $a.$b.$c;
?>
$.post("page2.php", { test1:test1 , test2:test2, test3:test3 });
Since you are learning, you might try to isolate problems by writing shorter chunks of code and seeing if they work first. In this case your first problem is an ordinary typo (test3=test3, instead of test3: test3) so your whole JS does not parse. You should be seeing the relevant error message in the firebug console (or chrome console).
I am just trying to test a simple ajax call on my server using jquery
I have a HTML file like this
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#connect_button").click(function(event){
$("#placeholder").load("http://mysever/AjaxResponse.php");
})
});
</script>
</head>
<body>
<button id="connect_button" type="button">Connect</button>
<span id="placeholder">This has not worked</span>
</body>
</html>
AjaxResponse.php, which works when accessed from the browser statically, looks like this
<?php
echo "This now works";
?>
The code runs and the replace happens the only problem is that the page returns a blank string causing the span to be empty
If I change the code to use another jQuery call such as $.get() the callback is sent back the textStatus of "Success" and a data value of ""
What am I missing here? Do severs need to be set up to respond to Ajax calls. Am I misusing jquery?
Is your AjaxResponse.php on the same domain? Ajax calls won't work cross-site.
If you want, you could check if the loaded page has anything in it like this:
$(function(){
$('#connect_button').live('click', function(){
content = $.get('test.php',function(data){
content = data;
if (content != ""){
$('#placeholder').html(content);
}else{
$('#placeholder').html('This has not worked');
}
});
});
})
That way if the returned data is empty, it will put "This has not worked" in the placeholder id.