Combine JQuery/PHP to log clicks into database? - php

The attached picture shows the results page of the search engine that I'm building. For each return result, the user may click on the result (i.e. "Food Science") and it will expand out accordion-style to reveal information about that particular result.
I want to log each time the user clicks on a result (for learning/intelligence purposes) and store it in a database table that I have created which stores the session ID, the query, the position of the result, and the order in which the user clicked the item.
Using JQuery, I already have a function that will pull the title of the result that was clicked, and I have it set where I want to log the click, but I don't know how to do it since JQuery is client side and PHP is server side.
How can I use the JQuery to trigger a PHP function so that I can query the database to insert the click logs into my table?
Below is the JQuery function.
$(document).ready(function() {
$('.accordionButton').click(function(e) {
if($(this).next().is(':hidden') == true) {
$(this).addClass('on');
$(this).next().slideDown('normal');
$(this).next().slideDown(test_accordion);
// SEND CLICK ACTION TO LOG INTO THE DATABASE
alert($(this).find('h3:last').text()); // displays the title of the result that was just clicked
}
else {
$(this).removeClass('on');
$(this).next().slideUp('normal');
$(this).next().slideUp(test_accordion);
}
});
}

You can do something like this (untested):
Define a javascript variable to track the order of the clicks, outside your click function:
var order = 0;
Add this into your click function, at the bottom:
order++;
var sessionID = $("input[name='sessionID']").val(); // assuming you have sessionID as the value of a hidden input
var query = $("#query").text(); // if 'query' is the id of your searchbox
var pos = $(this).index() + 1; // might have to modify this to get correct index
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order});
In your php script called "logClick.php" (in the same directory):
<?php
// GET AJAX POSTED DATA
$str_sessionID = empty($_POST["sessionID"]) ? '' ; $_POST["sessionID"];
$str_query = empty($_POST["query"]) ? '' ; $_POST["query"];
$int_pos = empty($_POST["pos"]) ? 1 ; (int)$_POST["pos"];
$int_order = empty($_POST["order"]) ? 1 ; (int)$_POST["order"];
// CONNECT TO DATABASE
if ($str_sessionID && $str_query) {
require_once "dbconnect.php"; // include the commands used to connect to your database. Should define a variable $con as the mysql connection
// INSERT INTO MYSQL DATABASE TABLE CALLED 'click_logs'
$sql_query = "INSERT INTO click_logs (sessionID, query, pos, order) VALUES ('$str_sessionID', '$str_query', $int_pos, $int_order)";
$res = mysql_query($sql_query, $con);
if (!$res) die('Could not connect: ' . mysql_error());
else echo "Click was logged.";
}
else echo "No data found to log!";
?>
You can add a callback function as a third parameter for the $.post() ajax method if you want to see if errors occured in the script:
$.post("logClick.php", {sessionID:sessionID, query:query, pos:pos, order:order},
function(result) {
$('#result').html(result); // display script output into a div with id='result'
// or just alert(result);
})
);
EDIT: If you need the value of the order variable to persist between page loads because you paginated your results, then you can pas the value of this variable between pages using either GET or POST. You can then save the value in a hidden input and easily read it with jQuery. (Or you could also use cookies).
Example (put this in every results page):
<?php
$order = empty($_POST["order"]) ? $_POST["order"] : "0";
$html="<form id='form_session' action='' name='form_session' method='POST'>
<input type='hidden' name='order' value='$order'>
</form>\n";
echo $html;
?>
In your jQuery, just change var order = 0; to
var order = $("input[name='order']").val();
Then, when a user clicks on a page link, prevent the default link action, set the order value and the form action, and then submit the form using javascript/jQuery:
$("a.next_page").click(function(event) {
event.preventDefault();
var url = $(this).attr("href");
$("input[name='order']").val(order);
$("#form_session").attr('action', url).submit();
});
All the 'next' and 'previous' pagination links must be given the same class (namely 'next_page' (in this example).
EDIT: If your pagination is as follows:
<div class='pagination'>
<ul><li><a href='page1.url'>1</a></li>
<li><a href='page2.url'>2</a></li>
</ul>
</div>
then just change this:
$("div.pagination a").click(function(event) {
etc.

This one is pretty easy, you need a PHP-Script to handle AJAX requests which are sent from your Search page.
In your search page you'll need to add an .ajax to create an AJAX request to your Script.
Everything you need to know about AJAX can be found here: http://api.jquery.com/jQuery.ajax/
In your PHP-Script you'll handle the Database action, use GET or POST data to give the script an ID over Ajax.

Use Ajax. Write a simple php-script that writes clickes to the database. I don't know how you log the clicks in the database exactly, but you can send the clicked item unique identifier to a php script with ajax, for example via POST variables.
A little example, on click:
$.post(
'count_click.php',
{ id: "someid" },
function(data) {
// data = everything the php-script prints out
});
Php:
if (isset($_POST['id'])) {
// add a click in the database with this id
}

Send a request to a PHP page using jQuery AJAX. See here for more info (it is really simple):
http://api.jquery.com/jQuery.ajax/
In this particular case, as you do not need to return anything, it may be better to just use the POST or GET methods in jQuery:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
Something like:
$.ajax({
  type: "POST",
  url: "some.php",
  data: "name=John&location=Boston"
success: function(data){
alert('done');
});

Related

How to use onclick on a button with an insert function for multiple buttons php

I have a page with several buttons whose values and names are retrieved from the database. I'm trying to run an insert query on any button clicked, my code so far:
<?php
$sqlGetIllness = "SELECT * FROM illnissesandconditions ";
$resultGetIllness = $conn->query($sqlGetIllness);
while ($rowGetIllness= mysqli_fetch_array($resultGetIllness)){
echo "<div class='col-md-3'style='margin-top:20px;'><button onclick='insert(".$rowGetIllness['illness'].");' class='button button1' style=' color:white;' value='".$rowGetIllness['illness']."'>".$rowGetIllness['illness']."</button></div>";
}
function insert($value) {
$value='';
$sqlGetId = "SELECT commonID from common group by commonID DESC LIMIT 1 ";
$resultGetId = $conn->query($sqlGetId);
$r=mysqli_fetch_array($resultGetId);
$id=$r['commonID'];
$sqlGetIllness = "INSERT INTO medicalrecords (CommonID,Medical_Condition) VALUES (".$id.",'".$value."')";
$resultGetIllness = $conn->query($sqlGetIllness);
}
The value passed to the function inside onclick is correct when I inspect it in the browser, however nothing happens. I have a database connection on already, what could be wrong? Is it possible to do it like that in php without refreshing the page? Or do I need to use a client side lang like AJAX? Please note that I've never worked in AJAX btw.
New EDIT:
<script>
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
condition: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Condition Inserted!');
},
error: function(result) {
alert('error');
}
});
});
</script>
Solution:
I got it worked out, after writing the script, i retrieved the variable value on top of the page
if (isset($_POST['condition'])) {
$value=$_POST['condition']; }
inside $_SERVER['REQUEST_METHOD'] == 'POST' ) and now it inserts the value when ever any button is clicked, my next step is to give the clicked button a background color
Solution is in the post under Solution, was my first time trying ajax and it did work indeed, gave the button an id, and took its value ( any button clicked ) through this.val and sent via post, retrieved and used the value in a variable for the insert query.

jQuery AJAX request not firing when posting to a php script.

I have a database table which I am trying to retrieve data from using JQUERY AJAX. When my first page loads it does a php call to a table and populates a select form element. - This works
I then want to select one of the options submit the form and have the row returned via Ajax.
Previously I had the script working with just PHP files but am having trouble getting it to work. When submitting the form my URL is changing:
http://localhost/FINTAN/testertester.php?name=Specifics.
I am not getting anything back. In addition when looking at my console I get a jquery not defined
factory (jquery). I can find the line in question in my jquery ui.js. Not sure if this is the issue or my code has caused the issue. I have cleard the firefox cache and due to the fact I have not had a successful AJAX call via jquery method am guessing it my code.
To get the code below I have mixed and matched a book and an online tutorial and many other sources and this is not my first attempt. Ideally I would like to output table row. However just getting a request working and knowing its not a conflict or compatability issue would makeme feel better and not hindered before I start
<script src="jquery/jquery-ui-1.11.2/jquery-ui.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val;
}
}
$.post("addithandle1.php",
{
name:vname};
function(response,status){
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
}
}
</script>
</head>
<body>
<?php
include "config.php";
if (mysqli_connect_errno($con))
{
}
else
{
$result = mysqli_query($con, "SELECT * FROM script ");
echo " <Form method='post'> <label>Script :</label> <select id='name' name='name' >";
}
while($row = mysqli_fetch_array($result))
{
echo "<option value = '".$row['scriptname']."'>".$row['scriptname']."</option>";
}
echo "</select>";
echo "<button id='btn' class='btn-search'>Load Script </button></form>";
?>
</body></html>
This is my PHP file that I am trying to retrieve from
<?php
include 'config.php';
$batchtype2 = $_POST['name'];
$batchtype2 = mysqli_real_escape_string($con,$batchtype2);
$sql = "SELECT * FROM script WHERE scriptname = '".$batchtype2."' ";
$result = mysqli_query($con,$sql);
$count=mysqli_num_rows($result);
if($count==0 ){
echo "</br></br></br></br></br></br></br><p> No Matching results found</p>";
}
else{
while($row = mysqli_fetch_array($result)) {
echo '<tr><td>'.$row['scriptname'].'</td></tr>';
echo '<tr><td>'.$row['scripthours'].'</td></tr>';
echo '<tr><td>'.$row['scripttotal'].'</td></tr>';
}
}
mysqli_close($con);
?>
Thanks in advance for any help
By making the following corrections (you have some syntax issues as well as usage issues which should be revealed in your browser's console when you load this page) in your JavaScript/jQuery this will work like you expect -
Make sure to change this line -
var vname = $("#name").val;
to this -
var vname = $("#name").val(); // note the parentheses
in your function -
$(document).ready(function(){
$("#btn").click(function(e){
e.preventDefault(); // prevent the default action of the click
var vname = $("#name").val();
$.post("addithandle1.php", {name:vname}, function(response, status) { // POST instead of GET
// never use alert() for troubleshooting
// output for AJAX must be in the callback for the AJAX function
console.log("recieved data-------*\n\nResponse : " + response +"\n\nStatus : " + status);
$('#table').html(response); // put response in div
});
});
});
Now $_POST['name'] should get populated properly.
To get the table to appear in your requesting page first make sure that your PHP forms the table completely.
Add a div to your requesting page and modify the AJAX call above as shown.
<div id="table"></div>
Now, when you make a request the div on the requesting page will be updated with whatever comes back from the PHP script.
There are a couple of things about your script.
First make sure you write well structured code and that it is nothing in the wrongplace / broken.
You have in the $(document).ready(function(){ only the .click event of the button, but you left the ajax request outside, I imagine you did that so it will also make the ajax request in the first page load
The problem is that now it will only make it in the first page load, but not when you click the button, on clicking button you are only getting the value of name.
I recommend you to try something like this:
<script>
$(document).ready(function() {
// bind button click and load data
$("#btn").click(function(){
loadData();
return false; // prevent browser behaviour of the button that would submit the form
}
// load data for the first time
loadData();
};
function loadData() {
var vname = $("#name").val;
$.post("addithandle1.php", { name:vname }, function(response, status) {
alert("recieved data-------*\n\nResponse : " + response
+"\n\nStatus : " + status);
});
}
</script>
A few notes:
I would recommend always putting jquery code inside $(document).ready since that guarantees that jquery was loaded before running it
By default a form that has a submit button that you click, will get the form submitted by the browser, if you use ajax, you should prevent that behaviour, either on the button click event or on form with onsubmit="return false".

jquery AJAX requests not updating php variable

I have a comics website, Hitting Trees with Sticks, that allows a user to get next, previous, or random comic id by pressing next or simply pressing arrow keys.
Since images are stored in a database, the only way for me cycle through these images on the client side was to store them in a javascript array, and store the php $imgid in a javascript variable as imgIndex. Then I could alter that index on the client side when they press keyboard keys.
When the user presses a key, I'm using pushstate to alter the imgid in the URL, but that's not actually updating the server side $imgid. I need to update the server side $imgid because I'm associating a liking function with each specific ID... but currently, the total likes associated with an img ID won't refresh/update when I press a key to get a new image.
My solution was to not only use the PushState to update the URL, but when a key is pressed, I use a $.post, and send the updated imgIndex to the php script.
Here are snippets:
KeyInput.php: This is the client-side javascript:
<script type="text/javascript">
var imgArray = [<?php echo implode(',', getImages($site)) ?>];
var imgIndex = <?php echo $imgid ?>;
$(document).ready(function() {
var img = document.getElementById("showimg");
img.src = imgArray[<?php echo $imgid ?>];
$(document).keydown(function (e) {
var key = e.which;
var rightarrow = 39;
var leftarrow = 37;
var random = 82;
if (key == rightarrow)
{
imgIndex++;
if (imgIndex > imgArray.length-1)
{
imgIndex = 0;
}
img.src = imgArray[imgIndex];
window.history.pushState(null, null, '.?action=viewimage&site=comics&id=' + imgIndex);
$.post('./templates/viewimage.php', { _newImgId : imgIndex },
function(data) {
//alert(data);
}
);
}
viewimage.php This is the file that originally gets the $imgid, then it calls the keyInput.php script to accept key input... that alters the javascript imgid. For testing purposes, I've tried using $.post and $.get AJAX to send the updated imgid, as you can see below, that's $newID = $_POST['_newImgId];. When I echo out $newID, it says it's not defined.
<?php
/*
Controls display of comic on the viewComic template
*/
include 'include/header.php';
global $site, $imgid;
$cat = (isset($_GET['cat']) ? ($_GET['cat']) : null);
$site = (isset($_GET['site']) ? ($_GET['site']) : null);
$title = (isset($_GET['title']) ? ($_GET['title']) : null);
$imgid = $_GET['id'];
include './scripts/keyinput.php';
$newID = $_POST['_newImgId];
echo $newID; //THIS SHOULD ECHO THE UPDATED ID, but it says it is not defined
Any thoughts?
Thanks!
I think the problem with your code is that you are using your Ajax code after the page has already loaded, while trying to change the $_get variables for the initial page load. AFAIK, you need to update the entire page for the "Facebook like" button to change it's ID. Another option would be to use an Iframe. From what I can see, the button's data-href attributes always leads to http://hittingtreeswithsticks.com/ - and that can only be changed by reloading the page using a different attribute.
If you don't mind loading a page for each picture, this can work out for you:
<!-- This is the Like button code -->
<div [...] data-href="http://www.hittingtreeswithsticks.com/<?php echo $_get['id']; ?>"></div>
and the address for this page would be: http://www.hittingtreeswithsticks.com/?id=PAGE_ID
EDIT
Using AJAX, you are calling for data from the backend to be used in the client side, without having to reload the entire page. This data can then be used to alter the code in the client side. In your code, the data is being sent back to you but you are not using it at all, that's why it doesn't work:
$.get('./templates/viewimage.php', { _newImgId : imgIndex },
function(data) {
// This is where you should make use of the data received
}
);
EDIT #2
If you want to dynamically change the Like button's url, take a look at this answer.
Here is a fiddle of the working example:
http://jsfiddle.net/TkFma/4/

Count clicks on one button, save it to MYSQL and then display the current value (AJAX, PHP)

Here is what I want to accomplish on http://geheimprojekt.nomachines.org/
User clicks on "Nochmal!" Button (New word combination is generated)
Send the click to my MySQL database (withou reloading the page), increase "clicked" row by 1
Update the text in a paragraph "n Word combinations have been generated so far."
This is my first attempt to work with AJAX.
I have jQuery knowledge but i can't connect the dots it seems.
The SQL
CREATE TABLE IF NOT EXISTS `sggcount` (
`counter` bigint(20) NOT NULL DEFAULT '2'
) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_german2_ci;
--
-- Dumping data for table `sggcount`
--
INSERT INTO `sggcount` (`counter`) VALUES
(2);
To get this to work is very simple. You need some html for the future div where you want to place the couting:
<div id="counting"></counting>
Then right at the end of the generator() function you add this:
function generator(){
/*your code here...*/
var element = document.createElement("div");
element.setAttribute("id", "result");
element.appendChild(document.createTextNode(name));
document.getElementById("placeholder").appendChild(element);
/*the ajax code here*/
var url='urltophpfile/phpfile.php';
$.get(url,function(data){
$('#counting').html(data+' Word combinations have been generated so far.');
});
}
Now in your phpfile.php file you will need the code to increment the count. I guess you know how to do this part if now i can help with it too. I'll add some sample code here so you have an idea.
<?php
mysql_connect('localhost', 'db-sgg', 'password') or die('Cannot connect to database server');
mysql_select_db('db1152127-sgg') or die('Cannot select database');
$databasecall = mysql_query("SELECT counter FROM sggcount WHERE counter > 1");
/*so here you select the already stored value and then you make an update to increment it*/
mysql_query("UPDATE sggcount SET counter=counter+1");
$count = mysql_fetch_assoc($databasecall);
echo $count['counter']+1;
?>
By doing the echo above you will return the incremented value and the ajax will display it.
Update 1
Added more comprehensive php code
NOTE: if you add the jquery script please change the generator function to use jquery.
Using jQuery you could bind click event to your button and make ajax request.
JQuery ajax doc
On server side your PHP page should update SQL data.
Follow Javascript demo code
$(document).ready(function(){
$('button-selector').click(function(){
//use jquery ajax call to call php server page that update SQL data
$.ajax({
url: "updateClick.php",
context: document.body
}).success(function() {
//success callback
});
});
});
to send AJAX request on clicking use:
$('#button').click(function(){ // when user `click` element with `id="button"` (#button)
$.ajax({ // Start AJAX call
url: 'accept.php', // URL to send AJAX request
success: function(data) { // Function to execute on SUCCESS reply (reply data as paramenter)
var cc = $('#clicks_count').html(); // In your element with `id="clicks_count"` you store your click count (`<a id="clicks_count">21</a>`). Assign to `cc` javascript variable value of clicls_count
$('#clicks_count').html(cc + 1); // Increasing clicls_count on 1 and write it to `<a id="clicks_count">22</a>`
}
});
});
At accept.php use script increasing clicks counter by 1.

Refresh value from MySQL db on php page after clicking a submit button

So all i need to do is refresh a variable displayed on a php page which is stored in a MySQL db. This value is an int which is subtracted by 1 everytime the submit button from a form is clicked. As i've opted to use AJAX to post the form the page isn't being refreshed, therefore the value isn't being updated along with the form submission.
$qry = mysql_query("SELECT codes_remaining FROM users WHERE email= '".$_SESSION['email']."'");
while($row = mysql_fetch_array($qry)) {
if ($row['codes_remaining'] ==1 )
{
echo "You have ".$row['codes_remaining'].' code remaining';
}
else {
echo "You have ".$row['codes_remaining'].' codes remaining';
}
}
So this code just displays how many "codes" a person has left. I need this value to be refreshed once the submit button has been clicked from the form on the same page.
I'm using the following JavaScript to not refresh the page.
$("#form-submit").click(function(e) {
e.preventDefault();
$.ajax({
cache: true,
type: 'POST',
url: 'process-register.php',
data: $("#form-register").serialize(),
success: function(response) {
$("#output-div").html(response);
}
});
});
Thanks,
LS
If you'd like to update the value, do it like this (jQuery is easiest):
$(".submit").click(function(event) {
event.preventDefault();
$(this).load('file.php',function(val){
$('#output').text(val);
});
});
And in file.php:
<?php
connect_to_db();
$returned = get_info_from_db();
echo $returned;
?>
The jQuery will grab the info on file.php and put it into #output.
Maybe It's just me, but why not use jQuery .load function?
$("#form-submit").click(function(e) {
e.preventDefault();
$(this).load('process-register.php');
});
Maybe not ethical nor the correct way of doing this but everytime you click on #form-submit, it loads that file and therefore processes it everytime. Also note that if you load a file that uses MySQL connection yes has no mysql_connect or mysql_select_db configured, it obviously won't work. I've had that for quite some times.
In your 'success', you could possibly just throw in
$("#WhereYouWantTheOutput").load("process-register.php");
That way whenever your submit succeeds, it'll also load the output for you. Just replace #WhereYouWantTheOutput with the name of where you want the output placed.

Categories