I asked this question but did not explain it thoroughly. I have a regular link:
Click Me
I want the change the href after the link is clicked 10 times not by the individual use but clicked 10 total times by all users.My jquery is obviously flawed but here is what i have:
var count = 0;
$(document).ready(function(){
$('a').click(function(){
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
I am new to jQuery but from what ive read cookies and local storage store individual users information not the total websites information. So how could i use ajax with a database to do this? maybe even php?
You have a huge fundamental misunderstanding of how JavaScript works.
Firstly, when someone clicks that link, they're going to be navigated away from your page unless you do something to prevent that (e.preventDefault or return false in jQuery). Once they're navigated away, your counter is lost because is stored locally, in memory, for the life of the page.
Secondly, even if the counter wasn't cleared, or you stored the counter in a cookie, or localStorage, it will only count for a single user. If you want to count the clicks by all users, you're going to have to do that server side. i.e., in PHP.
So... how do we do that? Well, as I said before, when a user clicks that link, they're going to be sent to Google. Your site will have no knowledge of what has occurred.
We have two options to deal with this. We can intercept the click, and use AJAX (more appropriately "XHR") to send a request back to your server, where you can log the click, before forwarding them off to Google.
Or, you re-write the URL to something like /log_click.php?forward=http://google.com. Now when the user clicks the link, they will actually be sent to your log_click.php script, where you can log the click to your database, and then use $_GET['forward'] in combination with header('location: ...') to forward them off to their destination. This is the easiest solution. Through some JavaScript hackery, you can hide the link so that when they mouse over it, they won't even know they're being sent to your site (Google does this).
Once you've accumulated your 10 clicks, you again use PHP to write out a different HTML link the next time someone views that page.
HTML
<a href='http://www.google.com' data-ref='99'>Click Me</a>
Javascript
$("a").click(function() {
var _this = $(this);
var ref = $(this).data('ref');
$.ajax({
url: '/click_url.php',
type: 'POST',
data: {id:ref}
success: function(href) {
if(href != '')
_this.attr("href",href);
}
});
}
PHP (click_url.php)
if($_POST['id'] > 0){
$id = $_POST['id'];
//count increment
$sql = "UPDATE table SET count = count + 1 WHERE id = '$id'";
mysql_query($sql);
//get row count
$sql = "SELECT * FROM table WHERE id = '$id' LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
//if count > 10 , return new url
if($row['count'] > 10){
die($row['href']);
}
}
While clicking the link you can call an ajax request and increment the count in the server. So that u should remove link from href and call manually by using javascript window.location.href each time. Hope that helps
var count = 0;
$(document).ready(function(){
$('a').click(function(e){
e.preventDefault();
count++;
if(count > 10){
$('a').attr("href","https://www.yahoo.com");
}
});
});
and use ajax like below
//send set state request
$.ajax({
type: "POST",
contentType: "text/xml; charset=utf-8",
datatype: "xml",// you can set json and etc
url:"your php file url",
data: {test:test1},// your data which you want to get and post
beforeSend: function (XMLHttpRequest) {
// your action
},
success: function (data, textStatus, XmlHttpRequest) {
// your action },
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
for more deatils see Ajax
Mark's answer is more useful, even you want to implement for the sake of some constraints then try below with jQuery 1.9
I have implemented for 3 clicks, AFAIU you need to change the URL on every 3rd successive click
var c=0;
$(document).on('click', 'a#ten', function(e){
c++;
alert('clicked ' + c + ' times');
if(c%3 == 0) {
$('a').attr("href","https://www.yahoo.com");
alert('changed');
c = 0;
}
e.preventDefault();
})
working DEMO
You must save no of times that link has been clicked in the database with php. when you render the link(with php) check the no of times it has been called before and decide what link to render.
Click Me
write this javascript in the page wher you place your link
$(function()
{
$('.mylink').click(function()
{
$.ajax({
type: "POST",
url: "listening/end/point", // enter your counting url here
async: false
);
});
});
And in server on the listening end point write php script to store no of times that link has been called.
Related
I found a script on the net, which makes two PHP files interact.
Specifically, the first file (details.php) shows some statistical data of a football match. If the match is in progress, I show the live score by running another PHP file (live_score.php). The two files interact thanks to the following script, present in the details.php file
$(document).ready(function(){
setInterval(function() {
var id=<?php echo"$id"?>;
var x = "<?php echo"$cod"?>";
$("#risultato").load("live_score.php", {var:id, x});
refresh();
}, 5000);
});
from details.php, I call live_score.php passing it some parameters.
These parameters are used by the live_score.php file to retrieve the score and other information in real time.
To print the result on the screen in details.php, I use a simple ECHO inside the live_score.php file, but I would like to retrieve this data and the others in a different way, via ajax if possible, but I don't know if it can be done and how....can you help me please? Thank you
I think you have already solved half of your problem. From your code , you should first remove the "refresh()" to stop reloading the page every 5 seconds.
then make sure that the the payload is correct, because the word "var" is a reserved keyword in JavaScript.
HTML
<div id="risultato"></div>
Javascript
$.ajax({
url: "live_score.php",
type: "POST",
data: { id, x},
success: function(response) {
//this response will be the data from "live_score.php"
//now assuming that
// 1. you use vanilla javascript with plain html + css
// 2. the returning reponse looks like this
// [{"teamName": "theTeam1", "score": 10}, {"teamName": "theTeam2", "score": 10}]
//Clear the current score
$("#risultato").empty();
// Now iterate through the response,
$.each(response, function(index, item) {
var teamName = item.teamName;
var score = item.score;
var html = "<p><strong>" + teamName + "</strong>: " + score + "</p>";
// this code will append (add to the end) the data iterated
$("#risultato").append(html);
});
},
error: function(xhr, status, error) {
//if your code or ajax call had any problems ,
//you can debug here and write error handling logic here, like
if(error){
alert("failed to fetch data");
console.log(error);
}
}
});
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.
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');
});
I recently came upon a site that has done exactly what I want as far as pagination goes. I have the same basic setup as the site I just found.
I would like to have prev and next links to navigate through my portfolio. Each project would be in a separate file (1.php, 2.php, 3.php, etc.) For example, if I am on the 1.php page and I click "next project" it will take me to 2.php.
The site I am referencing to accomplishes this with javascript. I don't think it's jQuery:
function nextPg(step) {
var str = window.location.href;
if(pNum = str.match(/(\d+)\.php/i)){
pNum = pNum[1] * 1 + step+'';
if ((pNum<1) || (pNum > 20)) { pNum = 1; }
pNum = "".substr(0, 4-pNum.length)+pNum;
window.location = str.replace(/\d+\.php/i, pNum+'.php');
}
}
And then the HTML:
Next Project
I can't really decipher the code above, but I assume the script detects what page you are on and the injects a number into the next page link that is one higher than the current page.
I suppose I could copy this code but it seems like it's not the best solution. Is there a way to do this with php(for people with javascript turned off)? And if not, can this script be converted for use with jQuery?
Also, if it can be done with php, can it be done without dirty URLs?
For example, http://www.example.com/index.php?next=31
I would like to retain link-ability.
I have searched on stackoverflow on this topic. There are many questions about pagination within a page, but none about navigating to another page that I could find.
From your question you know how many pages there are going to be. From this I mean that the content for the pages themselves are hardcoded, and not dynamically loaded from a database.
If this is the approach you're going to take you can take the same course in your javascript: set an array up with the filenames that you will be requesting, and then attach event handlers to your prev/next buttons to cycle through the array. You will also need to keep track of the 'current' page, and check that incrementing/decrementing the current page will not take you out of the bounds of your page array.
My solution below does the loading of the next page via AJAX, and does not change the actual location of the browser. This seems like a better approach to me, but your situation may be different. If so, you can just replace the related AJAX calls with window.location = pages[curPage] statements.
jQuery: (untested)
$(function() {
var pages = [
'1.php',
'2.php',
'3.php'
];
var curPage = 0;
$('.next').bind('click', function() {
curPage++;
if(curPage > pages.length)
curPage = 0;
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
$('.prev').bind('click', function() {
curPage--;
if(curPage < 0)
curPage = (pages.length -1);
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
});
HTML:
<div id = "pageContentContainer">
This is the default content to display upon page load.
</div>
<a class = "prev">Previous</a>
<a class = "next">Next</a>
To migrate this solution to one that does not have the pages themselves hardcoded but instead loaded from an external database, you could simply write a PHP script that outputs a JSON encoded array of the pages, and then call that script via AJAX and parse the JSON to replace the pages array above.
var pages = [];
$.ajax({
url: '/ajax/pages.php',
success: function(json) {
pages = JSON.parse(json);
}
});
You can do this without ever effecting the structure of the URL.
Create a function too control the page flow, with an ajax call
function changePage(page){
$.ajax({
type: 'POST',
url: 'myPaginationFile.php',
data: 'page='+page,
success: function(data){
//work with the returned data.
}
});
}
This function MUST be created as a Global function.
Now we call the function on page load so we always land at the first page initially.
changePage('1');
Then we need to create a Pagination File to handle our requests, and output what we need.
<?php
//include whatever you need here. We'll use MySQL for this example
$page = $_REQUEST['page'];
if($page){
$q = $("SELECT * FROM my_table");
$cur_page = $page; // what page are we on
$per_page = 15; //how many results do we want to show per page?
$results = mysql_query($q) or die("MySQL Error:" .mysql_error()); //query
$num_rows = mysql_num_rows($result); // how many rows are returned
$prev_page = $page-1 // previous page is this page, minus 1 page.
$next_page = $page+1 //next page is this page, plus 1 page.
$page_start = (($per_page * $page)-$per_page); //where does our page index start
if($num_rows<=$per_page){
$num_pages = 1;
//we checked to see if the rows we received were less than 15.
//if true, then we only have 1 page.
}else if(($num_rows % $per_page)==0){
$num_pages = ($num_rows/$per_page);
}else{
$num_pages = ($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$q. = "order by myColumn ASC LIMIT $page_start, $per_page";
//add our pagination, order by our column, sort it by ascending
$result = mysql_query($q) or die ("MySQL Error: ".mysql_error());
while($row = mysql_fetch_array($result){
echo $row[0].','.$row[1].','.$row[2];
if($prev_page){
echo ' Previous ';
for(i=1;$i<=$num_pages;$i++){
if($1 != $page){
echo "<a href=\"JavaScript:changePage('".$i."');\";> ".$i."</a>";
}else{
echo '<a class="current_page"><b>'.$i.'</a>';
}
}
if($page != $num_pages){
echo "<a class='next_link' href='#' id='next-".$next_page."'> Next </a>';
}
}
}
}
I choose to explicitly define the next and previous functions; so here we go with jQuery!
$(".prev_link").live('click', function(e){
e.preventDefault();//not modifying URL's here.
var page = $(this).attr("id");
var page = page.replace(/prev-/g, '');
changePage(page);
});
$(".next_link").live('click', function(e){
e.preventDefault(); // not modifying URL's here
var page = $(this).attr("id");
var page = page.replace(/next-/g, '');
changePage(page);
});
Then finally, we go back to our changePage function that we built initially and we set a target for our data to go to, preferably a DIV already existing within the DOM.
...
success: function(data){
$("#paginationDiv").html(data);
}
I hope this gives you at least some insight into how I'd perform pagination with ajax and php without modifying the URL bar.
Good luck!
I'm building a site which allows users to log on to it, and uses jquery to dynamically update the page to show all users who are currently on.
I want to have a button beside each users name that would let another user select that person (a game match-making service, if you will.)
Currently I'm generating the names with a combination of jquery and php.
Jquery does long polling:
function waitForMsg(){
$.ajax({
url: "tictac_code1.php",
type: 'POST',
data: 'longpoll=1',
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:10000, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
$('#loggedinnames').empty();
$('#loggedinnames').append(data);
setInterval(waitForMsg, 10000);
//setTimeout(
// 'waitForMsg()', /* Request next message */
// 1000 /* ..after 1 seconds */
//);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
//alert("error in waitformsg.");
addmsg("error", textStatus + " (" + errorThrown + ")");
setInterval(waitForMsg, 10000);
//setTimeout(
// 'waitForMsg()', /* Try again after.. */
// "15000"); /* milliseconds (15seconds) */
}
});
};
$(document).ready(function(){
waitForMsg(); /* Start the inital request */
});
PHP does the sql queries and returns data to the jquery to be displayed.
if (isset ($_POST['longpoll'])) {
if (filter_input(INPUT_POST,'longpoll') == '1') {
$name = $_SESSION['name'];
$result = mysql_query("select name from tictac_names where logged_on='1' AND name!='$name'", $db);
$rowCheck = mysql_num_rows($result);
if ($rowCheck > '0') {
while ($row = mysql_fetch_assoc($result)){
foreach ($row as $val){
$spanid = 'sp_' . $val;
$buttonid = 'b_' . $val;
//echo "<br><span id=\"$spanid\">$val</span></br>";
//<input type ="button" id="nameButton" value ="OK"/><br>
echo "<br><span id=\"$spanid\">$val <input type =\"button\" id=\"$buttonid\" value =\"Button!\"/> </span></br>";
//echo "<br><p><span id=\"$spanid\">$val</span>Click here to play a game with this player.</p></br>";
}
}
} // end rowcheck
}
} //////////// end of the LONGPOLL if
So it successfully puts out the name and a button, but the button's ID is not unique. If I want it to be clickable, I'm sure that the ID will have to be unique, but then there will need to be additional jquery to catch the button click.
How can I make this work?
Should I take a different approach, perhaps names with radio buttons, and a single "Match us!" button?
An alternative to #Craig M 's answer would be to use the built in delegate features in jQuery.
$('#loggedinnames').delegate('span','click',function(){
alert($(this).text());
});
It does the same thing but you can use any selector, not just tag name, and you don't need to code all of the boiler plate delegation code.
You could remove the buttons, and use event delegation to figure out which username the person clicked on. Then do what you need to do with it in the click handler.
To do this, set a click handler on #loggedinnames like so:
$('#loggedinnames').click(function(e) {
if ($(e.target).is('span')) { //e.target is the element that was actually clicked.
alert($(e.target).text());
}
});
The advantage of this approach is that you only have one click handler and don't need to bind an event every time the list of logged in users changes.
What I usually do in this situation is to build the button in JavaScript rather than on the server. Then you can just keep a global variable that serves as a counter, increment it each time you add a button, and use that to put together your unique button ID.
I've used this approach in a lot of situations, and 90% of the time, it works every time.
Give all of your buttons the same class and unique ids. Write an event handler in JQuery using live() for your class where you get the id of this and use it in your code. This way the code works for ALL buttons (including new ones) and you do not have to duplicate any code.
$('#loggedinnames .button').live('click', function() {
someMethod($(this).attr('id')); //run your code here
});