First things first, most of your question is not possible in the way you want it done. Specifically incrementing a variable in PHP such that you have $list[4] += 10
. I say this because when this script is run this won’t exist anymore, you’d have to load it in from where ever you happen to be storing data (assuming a DB).
So, a short example of what you’re trying to achieve you’ll need a couple of files.
index.php
– This is where your code happens that renders the page with the links on it.link_clicked.php
– This is called when a link is clicked.
You’ll add need this basic Javascript in your code (it uses jQuery because you mentioned it in your question). I’ve broken this snippet into many pieces which is not how you’d normally write or see jQuery written to explain what is going on.
$(function() {
// Select all elements on the page that have 'URL' class.
var urls = $(".URL");
// Tell the elements to perform this action when they are clicked.
urls.click(function() {
// Wrap the current element with jQuery.
var $this = $(this);
// Fetch the 'href' attribute of the current link
var url = $this.attr("href");
// Make an AJAX POST request to the URL '/link_clicked.php' and we're passing
// the href of the clicked link back.
$.post("/link_clicked.php", {url: url}, function(response) {
if (!response.success)
alert("Failed to log link click.");
});
});
});
Now, what should our PHP look like to handle this?
<?php
// Tell the requesting client we're responding with JSON
header("Content-Type: application/json");
// If the URL was not passed back then fail.
if (!isset($_REQUEST["url"]))
die('{"success": false}');
$url = $_REQUEST["url"];
// Assume $dbHost, $dbUser, $dbPass, and $dbDefault is defined
// elsewhere. And open an connection to a MySQL database using mysqli
$conn = new mysqli($dbHost, $dbUser, $dbPass, $dbDefault);
// Escape url for security
$url = conn->real_escape_string($url);
// Try to update the click count in the database, if this returns a
// falsy value then we assume the query failed.
if ($conn->query("UPDATE `link_clicks` SET `clicks` = `clicks` + 1 WHERE url="$url";"))
echo '{"success": true}';
else
echo '{"success": false}';
// Close the connection.
$conn->close();
// end link_clicked.php
This example is simplistic in nature and uses some unrecommended methods for performing tasks. I’ll leave finding how to go about doing this properly per your requirements up to you.
1
solved update PHP variable on click of html class [closed]