Passing Javascript Click counts to php - php

Hi I wrote a javascript click count its working properly but i want it to pass a single click to an external php script so as to insert the click and the id into db, it redirect a person to deals.php once a click is made on "click me" href and counts ,this is my code: Any help would be appreciated.
<script type="text/javascript">
var clicks = 0;
function linkClick()
{
document.getElementById('234').value = ++clicks;
}
document.write('<a href="deals.php?name=" + ++clicks;
onclick="linkClick()">Click Me!</a>');
</script>
You have clicked the link times.enter code here

You Can done it by using php only
on HTML Page
<?php
$query=mysql_query("select clickCount from click_count");
$result=mysql_fetch_assoc($query);
$clickCount=result['clickCount '] // get the value from database ?>
<a href="deal.php?name=<?php echo ($clickCount+1);?>" >click me</a>
on deal.php Page
let table name is click_count
$clickCount=$_GET['name'];
mysql_query("update click_count set clickCount = '".$clickCount."'");

You should not relay on client side to count the clicks. This should be done in PHP when the user clicks:
Click me
and then, on deal.php:
$id = $_GET['id'];
$clicksCount = getClicksCountForId($id);
setClicksCountForId($id, $clicksCount++);
get and set clicks count into database can be done like Shut proposed in his answer.

It's possible to simplify your code by doing everything on the PHP side and storing the clicks counter in $_SESSION. The first time it's going to be zero ($_SESSION["clicks"] = 0;), when user clicks the link, "deals.php" will be executed, and the value will be increased (and database updated), example :
main.php
<?php
session_start();
if ( ! isset( $_SESSION[ "clicks" ] ) ) // FIRST TIME.
$_SESSION[ "clicks" ] = 0;
?>
<html>
<body>
Click Me!
<input type="text" value="<?php echo $_SESSION['clicks'];?>"/>
</body>
</html>
deals.php
<?php
session_start();
$_SESSION[ "clicks" ]++; // INCREASE COUNTER.
// <=== UPDATE DATABASE HERE.
header( "Location: main.php" ); // RETURN TO MAIN.PHP.
?>
If you create two files with the given names (main.php, deals.php) and paste previous codes, it will work like you want : every click will be stored in database.

Related

post isset($_POST['next'] is not set after submit /refresh page. Need to be press twice for it to be set how to fix?

<script>
function refreshPage()
{
document.forms[0].submit();
}
</script>
<?php
foreach($values as $value)
{
?>
<input type = "checkbox" name = "food[]" value = "<?php echo($value['dinner']);?>"
<?php if(isset($_POST['food'])) echo "checked='checked'"; ?> > // note this is still part of
input
<?php
}
?>
<button name = "pass" onClick = "refreshPage()">refresh</button>
<?php
if(isset($_POST['pass'])
{
// do a lot more stuff but I have this for temp info
echo("hello");
// I am printing all the check box values in here I do not
// have the code for it yet but I think ik how to do it
// but since i do not have code for it now it is just empty
}
?>
hi so everytime I click on the button refresh. the isset($_POST['pass']) does not work. I have to click on it a second for it to be set which would then print the hello and table of check items part.
I want it so that if you click on it once it will print the hello. Not twice. How do i fix my code? FYI I know you could do isset($_POST['food']) for it to work. But that will break other parts of my code.
I need the button to set the isset($_POST['pass']) to be True (after one click) after I press the refresh button one time.

Changing query variable, then executing it again

I am working on a PHP page that shows a table with query results. I want 2 buttons, with 'next' and 'previous', which change a variable used in this query:
SELECT les.lesuur, les.clustercode, les.lokaal, les.leraar, les.status
FROM les, zitin
WHERE zitin.leerlingnummer='$dimGebruiker'
AND zitin.clustercode=les.clustercode
AND les.dag='$huidigedag'
ORDER BY les.lesuur
$huidigedag is the one that should be changed. This is what I have in the beginning of the PHP code:
session_start();
if (!isset($_SESSION["huidigedag"])){
$_SESSION["huidigedag"] = 1;
}
$huidigedag = $_SESSION["huidigedag"];
Then, I added a link to the two buttons (arrow images):
<a href="volgende.php">
(volgende means next)
This is volgende.php:
<?php
$_SESSION["huidigedag"] = $_SESSION["huidigedag"] + 1;
header("location:leerlingrooster.php");
?>
However, when I click the button, nothing happens. I echo'd $huidigedag, and noticed it stayed on 1, without changing.
try to add session_start() to the beginning of volgende.php
I would change volgende.php to:
<?php
session_start();
$_SESSION["huidigedag"] = (!isset($_SESSION["huidigedag"])) ? 1 : ($_SESSION["huidigedag"] + 1);
header("location:leerlingrooster.php");
exit;
?>

Pass data from php mysql to pop up on same page

I have a link in a php while loop
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
The pop up requires the product id to search the database but hash tag is client side. I tried to use javascript window.location.hash but the outcome was not very reliable.
Does anyone know a method preferably server side I could use to retain the active product id while I call the pop up, attain the product id, use it to query the database and output it in the pop up.
I have a session already started and tied to a different condition.
I tried to call the product id directly from the pop up but because of the loop I only get either the first or last in the array.
<?
while ($i < $num) {
$product_id=mysql_result($result,$i,"prod_id");
$title=mysql_result($result,$i,"lTitle");
//main page
echo "<b>" , $title;
echo "<a href = '#$product_id' onclick = 'pop_up()' id = 'linker'>See more</a>";
?>
<!------pop up--------->
<script type="text/javascript">
function pop_up(){
document.getElementById('pop').style.display='block';
}
</script>
<div id="pop">
<p style='color:#6F0A0A; font-size:15px;'><? echo $product_id; ?></p>
</div>
<?
$i++;
}
?>
I'll try answering but to be honest the question is very vague and the code is a bit messy.
First off, you can simply send the product_id as a GET variable to the new popup and read it in PHP. Something like this will work:
echo "<a href = 'http://www.mydomain.com/popup.php?product_id=$product_id' onclick="window.open(this.href, 'popup_win',
'left=100,top=100,width=500,height=500,toolbar=1,resizable=0'); return false;" id = 'linker' >See more</a>";
On your popup.php file (the popup page) you will get the product_id with the PHP $_GET method:
$product_id = $_GET['product_id'];
and then do whatever MySQL query you want, now that you know $product_id.
I hope this helps, if that's not exactly what you meant please add more details so I can revise my answer.
Well, you could first load all this records first and place them into the popup content or, make an ajax request, open the popup, and when the request is done successfully place the values returned into the popup content. Better with JQuery

how to unsave if page refreshed

I got a code here that if I refreshed the page it automaticaly save the data....can anyone help me that it will only save if the submit button is clicked.
current code:
<?php
ob_start();
?>
<html>
<head>
<title>test</title>
</head>
<body>
<?php
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
?>
<form method="post" action="index.php" >
<input type="text" value="batch<?php echo $var; ?>" />
<input type="submit" name="save">
</form>
</body>
</html>
The code you show is from your "handling" page. That page handles the post, it checks if there was a parameter "save" and if so, it saves.
If the user refreshes that page, he visits the page again, sending again a "save" parameter, so the INSERT is done twice.
To avoid this, you should use the POST-REDIRECT-GET model, where your handling page gets the data, saves it, and then redirects the user to a "GET" page (no post, no insert) that just shows the data. If the user then hits refresh, he only refreshes the "GET" page.
Offcourse, a user can always keep using the BACK button to go to the actual insert page. His browser will warn him "you are resubmitting form data...", but if he chooses to, he can. If you really want to handle this, you can work with session keys: have an extra field "submitID" on your form, and on INSERT, first check if that ID was already "used". You'll need an extra table/column "submitID" somewhere to ensure a form can only be submitted once.
The problem is the form is getting submitted again, you can make header redirect to this same page,
header("location: index.php) after updating your database and this will solve your issue.
Create one button in html
<input type="submit" name="submit"/>
In php Code, you can write like
<?php
if(isset($_POST['submit']))
{
//place your total code here
}
?>
As soon as the form is submitted once it has got the $_POST-Array in the site request. When you reload the page after the first submit, it will always send the data again.
You got multiple possibilities to resolve this problem:
1)
Reload the page after the execution of the PHP code. To do so put the PHP code at the top of the page (before writing anything in HTML) and reload the page after the execution of the query:
if(isset($_POST["save"])) {
/* MySQL Query */
$back = $_SERVER['HTTP_REFERER'] ; // the site who called this site
header("Location: $back") ; // Link back to this site
}
2)
Personally I prefer to execute my PHP scripts with an Ajax call, which would look as follows in jQuery.
function ajaxCall()
{
$.ajax({
type: "POST",
url: "handler.php",
data: {save: 1, textfield: $("#textfield").val()}
}) ;
}
Don't forget, that the forms action isn't the redirect to another site anymore, it is the call to this function ajaxCall. If you want more fields to submit, have a look at the serialize-function. The handler.php-file contains only your php-Code:
<?php
ob_start();
include('include/connect.php');
$query = mysql_query("SELECT DISTINCT count(batchcode) as batchcode1 FROM batchcodes");
while( $rows = mysql_fetch_array($query)) {
$code=$rows['batchcode1'];
}
if(isset($_POST['save'])){
$var = $code+1;
$sql = mysql_query("INSERT INTO batchcodes(batchcode) VALUES (". $var .")");
}
exit(0) ;
?>
In the ajax function you could also handle what happens when the call is successful (e.g. redirect). Have a look at the $.ajax-reference of jQuery. If you want you could also use ajax without jQuery.
3)
You could also make your page in action similiar to the handler.php in the second possibility.
<form action="handler.php" method="POST"></form>
In this case you had to replace the exit-statement with the $back and header-call in possibility 1 (similar to the response of Konerak).

how to navigate user to correct page?

<?php
$pages = array('Text1.php', 'Text2.php', 'Text3.php', 'Text4.php', 'Text5.php');
// Track $latest in either a session variable
// $current will be dependent upon the page you're on
$latest = $_SESSION['latest'];
$current = basename(__FILE__);
$currentPages = array_search($current, $pages);
$latestPages = array_search($latest, $pages);
if ($currentPages - $latestPages > 1 ) {
?>
<div class="boxed">
Continue
<br/>
Create New
</div>
<?
} else {
// let user do their step
}
?>
I have an array which contains five pages. Now this page steps.php is externalized and stored in an an include() which is stored in 5 php pages, the same php pages stored in the array above in the array.
Now what I am trying to do is the user is suppose to follow the page structure. So if the user is on one of the pages in the array, they cannot access another page until they have submitted the page they are currently on.
But my question is that if the user click on the Continue link, how can I get the link </a> to link to the correct page so it navigates the user to the page they should be correctly on.
If you mean how you can direct the user to the correct 'next' page when they click on Continue, you can output the next page using the currentPages index + 1
<? if ($currentPages - $latestPages > 1 ) { ?>
<div class="boxed">
Continue
<br/>
Create New
</div>
<? } ?>
As much as I understand, you are trying to implement something like pagination? You should put current, previous, and next pages in the SESSION variable, so in every request you can check whether the user is in the SESSION['current'] page, and tries to go to the SESSION['previous'] or the SESSION['next'] page, also you should send a 'hiddenfield' value to the server in order to check if the user 'submitted' the page(but of course, one can simply read your html and find the 'hidden' field). Or you can simply check whether the submit button's 'name' is in the POST(or GET)? (if($_POST['NAME_OF_SUBMIT']){}) - but again it is simple to falsify, too.

Categories