I've got a database including uploaded documents. The link to an uploaded document is:
<a href="http://<?php echo $_SERVER['HTTP_HOST'];
htmlout('/database/docs/'.$cand['id'].'/'.$docs['filename']);?>">
<img src="http://<?php echo $_SERVER['HTTP_HOST'];?>/database/img/cv.png" border="0">
</a>
I want to call a function which writes to an activity log when a link like that is clicked, e.g. writelog($userid, $msg) so I can see what user has viewed what document.
What would be the easiest way to do that?
I would add a js/jquery click event on the image and have that make an ajax call to your php writelog function. Whether this is the best method is up for debate but that is how I would accomplish the task.
<a class="clicked_link">
$(".clicked_link").click(function() {
var file_name = .....
$.ajax({
...
})
});
Here is a non-js version:
Have the link load a php page that loads the image and then every time that page is called have it display the image and call the writelog function
<a href="load_image.php?filename=PHPCODE">
<php
$file = $_GET['filename'];
writelog(one, two);
You should use ajax function to send request to PHP Script when user click on anchor i.e.
Note: This code requires jQuery
$(function(){
$('a').click(function(e){
e.preventDefault();
$.post('<URL_TO_PHP_FILE>', { data: { userid: 1, message: 'clicked' }, function(){
alert('Log has been written');
} });
});
});
In PHP, you can write your code to save log.
Related
I'm using the code below to load the results from a database query in a PHP page:
click me
$('.item > a').click(function(){
var url = $(this).attr('href');
$('.item-popup').fadeIn('slow');
$('.item-content').load(url);
return false;
});
All works fine right now, but the next bit of functionality is a problem. Inside results.php which ajax loads into .item-content, I have another link that is supposed to update and increment click counts for that link, also without refreshing. The functional PHP bits all work fine. My only problem is the jQuery/AJAX aspect of things.
Maybe I'm going about it the wrong way, but what I really want to do is have a page with a container that loads the result of of a database query from a PHP page, but also in that container, I have a link/button whose click count I want to be able to save and update all without refreshing.
EDIT
I guess the most important question I need answering is: When the ajax on index.php loads the content of results.php into the container in index.php, do browsers treat the newly loaded ajax content as part of the parent page (index.php) or is it still treated as a different page loaded into the container like an iFrame?
If say for example it is click event then you need to write
$('input element').on('click',function() {
// write code over here
})
Dont know for sure if you want this, When returning the data in the load function you will have to add a link like this in the resultant HTML which will be clickable:
Now in javascript you need to catch the click event of the link like this:
<script type="text/javascript">
$(function(){
$(".item-content").on("click", ".clickable", function(){
var counter = $(this).data('counter');
var id = $(this).data('id');
$.ajax({
url : //your url here,
data : {'id' : id, 'counter' : counter },
type : 'POST',
success : function(resp){
//update the counter of the current link
$(this).data('counter', parseInt( $(this).data('counter') )+1 );
//whatever here on successfull calling of ajax request
},
error : function(resp){
}
});
});
});
</script>
I want to execute a php code when a user click on a given link , i've tried the following code
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("up.php");
return false;
}
</script>
</head>
<body>
<center>
Click Me!
</center>
</body>
</html>
where up.php is a php code that implement android GCM mechanism similer to the one in the link : GCM with PHP (Google Cloud Messaging)
but unfortunately when the link is clicked nothing happens , the php code not executed ,and only the url of the page change form *****.com/test.html to *****.com/test.html# , and by the way I've tested the php code and its works fine so it is not a problem in php code , so what i have missed here? why the code is not executed?
i found the solution , the problem that the jquery library is not included probably in my code
you are using jquery. $.get() will be something like below.
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
for further help check http://api.jquery.com/jQuery.get/
Sometimes, you may need to call some JavaScript from within a link. Normally, when user click on a link, the browser loads a new page (or refreshes the same page).
This might not always be desirable. For example, you might only want to dynamically update a form field when the user clicks a link.
To prevent the load from refreshing, you could use the JavaScript void() function and pass a parameter of 0 (zero) as below.
<a href="JavaScript:void(0);" onclick="return doSomething(); " />Click Me!</a>
Now if you want to use href="#", make sure onclick always contains return false; at the end.
OR
Use href="javascript:void(0)"
You can also use jQuery Load
function doSomething() {
$('#result').load('up.php', function() {
alert('Load was performed.');
});
}
When you are using Jquery should be :
function doSomething(){
$.get('up.php', function(data) {
$('.data').html(data);
});
}
Link
To stop page refreshing, you can use the javascript void() function and pass parameter of 0.
Click Me!
<div class="data"></div>
This div is used to display up.php result.
Ok start of by using fire bug and watch the console and network panels
Ensure the browser is trying to get something and not returning a 404 or a php error on the get
Look into prevent default http://api.jquery.com/event.preventDefault/
To stop the original link functionality working
If you still want them to move to the link use a window location or...
Look into bootstrap link buttons
http://twitter.github.com/bootstrap/base-css.html#buttons
( the link button )
I asked a question about this but the post degenerated into confusion which lost the gist of the problem. Basically I'm trying to set up ajax so that a "like" or "unlike" link updates a database and shows the new status without having to refresh the page.
So I have a "view.php" page with links which are produced by a PHP loop. They look like this:
<div class="tools">
like
</div>
<div class="tools">
unlike
</div>
Note that each link has two classes: firstly a "like" class, and then either a "do_like" class or a "do_unlike" class, according to whether it's a link to "like" or a link to "unlike" respectively. (Originally I only had the "do_like" and "do_unlike" classes, which I was using to transform the link via css into a rollover-type image/icon, but I added the "like" class as well, for the ajax - see below.)
When a user clicks one of these links, the receiving processor.php script takes the variable-value pairs from the query string, and uses them to update a database, and then build a new form of the link, which it echoes out. The new form of the link is such that a "like this" link turns into an "unlike this" link, and vice-versa. So for the first "like" link above, the database returns:
processor.php?c=cars&p=2&s=d&u=d&pid=999999990
It's the "u" variable in the query string which determines whether or not the processor.php page will either insert the data into the database in the case of a "like" (u=i), or delete the data from the database in the case of an "unlike" (u=d). (I'm using prepared PDO statements for the database inserts/deletions.)
I'm using jquery/ajax to insert this newly built link in place of the one that was clicked, without having to refresh the page.
To do this, in the "view.php" page I included jquery.js and used the following javascript function:
<script type="text/javascript">
$(function() {
$("a.like").click(function(e){
e.preventDefault();
var link = $(this);
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
});
});
});
</script>
The problem is, although this function sends the data to the processing script OK, and changes the link's href attribute in the page without a page refresh (I can see it's doing this OK by copying the link in the browser after a click), it doesn't change the link's text, class or title. So I as it is, I have to refresh the page to see any visual cues that the link has in fact changed (I might as well just use a header redirection in the processor.php page).
How can I modify the function (or change it) so that it also replaces the link's text, class and title? So that (for example, transforming a "like" link):
like
becomes:
unlike
?
You need to change the class and the title then also:
[...]
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
link.toggleClass('do_like do_unlike');
link..attr('title', 'change title here');
});
Use an if condition to check the current state and update the attributes.
$(function () {
$("a.like").click(function (e) {
e.preventDefault();
var link = $(this);
var alreadyLiked = (link.text() == "UnLike") ? true : false;
$.get(link.attr('href'), function (data) {
link.attr('href', data);
if (alreadyLiked) {
link.removeClass("do_unlike").addClass("do_like").text("Like").attr("title", "Click to LIKE this photo");
}
else {
link.removeClass("do_like").addClass("do_unlike").text("UnLike").attr("title", "Click to UN LIKE this photo");
}
alreadyLiked = !alreadyLiked;
});
});
});
This code will work. Tested. Assuming every time the get request gives you the url (for deleting/inserting ) correctly.
This is based on both Shyju's and Pitchinnate's responses (so thanks to both!), and it works a treat using the css rollover link-transformation method (I also included a fade effect):
<script type="text/javascript">
$(function() {
$("a.like").click(function(e){
e.preventDefault();
var link = $(this);
$.get(
$(this).attr('href'),
function(data){
link.attr('href',data);
link.toggleClass('do_like do_unlike');
var titleState=(link.attr("title") == "Click to LIKE this photo") ? "no" : "yes";
if(titleState=="yes")
{
link.attr('title', 'Click to LIKE this photo');
}
else
{
link.attr('title', 'Click to UNLIKE this photo');
}
});
$(this).parents('div.tools').fadeOut(1000);
$(this).parents('div.tools').fadeIn('slow');
});
});
</script>
Why does the JQuery script I use in all my pages seems to only works before beginning to browse my tabs if the content of my tabs is the same everywhere ?
I have a tab view web page built with JQuery and AJAX.
This is my JQuery functions:
$(document).ready(function(){
$(".box .more").click(function(event){
alert('test');
});
$("a.linkTab").click(function(event){
var tabID = $('.linkTab')[0].toString().split('#')[1];
$.ajax({
url : "loadPage.php?tabID=" + tabID,
success : function (data) {
$('#body').html(data);
}
});
});
});
This is my body web page:
<div id="header">...</div>
<div id="body">
<div class="box">
<p class="more">LinkLike</p>
</div>
</div>
<div id="footer">9</div>
loadPage.php only include needed page that Ajax script sent.
My tab system works perfectly, I can navigate in the page I want. Before navigating, When I click on the LinkLike, the alert appears. But, when I browse tabs, When I click, there is nothing.
Why does the JQuery script seems to only works before beginning to browse.
Important, the file I imports from php contains exactly the same body than the first one. The file contains:
<div class="box">
<p class="more">LinkLike</p>
</div>
try
$(document).delegate(".box .more","click",function(event){
alert('test');
});
the reason probably is you can generating the link dynamically, and event handlers do not attach themselves to the dynamically inserted elements to the DOM. Previously .live was used but that now is deprecated, if you are using jquery version 1.7+ you can use the .on method or else you can use the delegate method to attach the event handler to the dynamic content. However you can also re-bind the events in the success callback of ajax request
$.ajax({
url : "loadPage.php?tabID=" + tabID,
success : function (data) {
$('#body').html(data);
$(".box").bind("click");
}
});
jQuery.on version1.7+
jQuery.delegate
You are replacing the entire body of the page when your click event fires; therefore, you will need to re-bind your click events once the new content is loaded.
$(document).ready blocks will only fire when the initial document loads, so the AJAX-ed in content will not cause the click events to be bound again, you'll have to do this in the success callback of the click event that replaces the body content.
function init() {
$("a.linkTab").click(function(event){
var tabID = $('.linkTab')[0].toString().split('#')[1];
$.ajax({
url : "loadPage.php?tabID=" + tabID,
success : function (data) {
$('#body').html(data);
init(); // re-bind events again
}
});
});
}
NOTE: This method will work, but it's probably a bit naive. Check out this jQuery page for more details on how to use the "delegate" jQuery method. The delegate method will bind click events both now as well as in the future.
Here is an example using "on", which supersedes "delegate" as of jQuery 1.7+:
// I'm not sure if you're referring to "body" the body tag or "body" the id of your div.
// Please adjust accordingly.
$("body").on("click", "a.linkTab", function() {
var tabID = $('.linkTab')[0].toString().split('#')[1];
$.ajax({
url : "loadPage.php?tabID=" + tabID,
success : function (data) {
$('#body').html(data);
}
});
});
I am trying to create an HTML link that changes the PHP session id. Basically I need to call the session_regenerate_id(); when a link is clicked. The problem is that it can't run on the page that I am linking to. There is an upload form that reloads after upload so the function cannot be on the page I am linking to.
Can I do an AJAX post to a separate PHP file?
In your php file called regenerate.php:
<?php session_regenerate_id(); ?>
And then with jquery.
$.POST('url/to/regenerate.php', function() {
// callback
});
Then to run it:
$(function() {
$('#postNew').click(function(e) {
e.preventDefault(); // stops the link from going anywhere
$.POST('url/to/regenerate.php', function() {
// callback
});
});
});