How to implement hit counter with light box - php

I want to count the number of hit on an image and also the image will show in a lightbox.
here is my code:
//image-show-content.php
<script>
function hitcounter(imgid)
{
//alert(imgid);
var imgid = imgid;
window.location.href ="image-show-content.php?img_id="+imgid;
}
</script>
<?php
if(!empty($_REQUEST['img_id']))
{
$show = "SELECT * FROM `tbl_image_gallery` WHERE image_id =".$_REQUEST['img_id']." ";
$result_show = mysql_query($show);
$row = mysql_fetch_array($result_show);
$new_click_count = $row['click_on_image'] +1;
$update_sql = "UPDATE `tbl_image_gallery` SET click_on_image =".$new_click_count." WHERE image_id=".$_REQUEST['img_id']."";
$result_sql= mysql_query($update_sql);
}
//image...
<img src="uploadedimage/gallery/thumble/<?=$val['gallery_image']?>" onclick="hitcounter('<?=$val[image_id]?>')"/>
?>
My problem is when I click on an image it return an error.
please help to solve it.Thanks in advance.Can you refer some other option to show light box and hit counter together.

Problem is, when your page loads. Lightbox javascript is already generating dynamic node for your tag.
To achieve this you can try with onclick function into . In that function you should call AJAX call with your image id. It would be possible that your onclick function may call after lightbox call OR before lightbox call. So please debug for this too.
This would be only one way to achieve this as per my opinion.

Place your php code in one another file called, hit_image.php and place your code there,
<?php
if(!empty($_REQUEST['image_id']))
{
$show = "SELECT * FROM `tbl_image_gallery` WHERE image_id =".$_REQUEST['image_id']." ";
$result_show = mysql_query($show);
$row = mysql_fetch_array($result_show);
$new_click_count = $row['click_on_image'] +1;
$update_sql = "UPDATE `tbl_image_gallery` SET click_on_image =".$new_click_count." WHERE image_id=".$_REQUEST['image_id']."";
$result_sql= mysql_query($update_sql);
}
Now your HTML file should be like follow,
<script type="text/javascript">
function counter(imageId)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","hit_image.php?image_id="+imageId,true);
xmlhttp.send();
}
</script>
<a onclick="counter(<?=$val[image_id]?>)" rel="lightbox[100,200]" title="<?=ucfirst($val['category_name'])?>"><img src="uploadedimage/gallery/thumble/<?=$val['gallery_image']?>" onclick="hitcounter('<?=$val[image_id]?>')"/></a>
This is just overview code for your hints.

Related

Javascript document.getElementById concatenating

I'm struggling with some JavaScript code that I have used countless times across my pages just tweaking as I go. The problem I have is concatenating part of the form elements id and a string variable defined elsewhere in the page to make my ajax call dynamic.
Im am using the following code which works perfect when the element is hard coded as below(only works for the item coded and not dynamically so no good after testing)
<script type="text/javascript">
function edttodo(str)
{
if (str=="")
{
document.getElementById("todoitemwr").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("todoitemwr(2)").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","todo/edt_todo.php?q="+str,true);
xmlhttp.send();
}
</script>
So you understand what my need is for the dynamic aspect of the code I have a mysql query undertaken which is as follows:
<?php
//Get Current To-Do Items
//select database
mysql_select_db("jbsrint", $con);
//query users_dash_user
$result1 = mysql_query("SELECT * FROM todo WHERE todo_user_id_fk= '".$_SESSION['user_id']."' AND todo_item_status='1'");
while($row1 = mysql_fetch_array($result1))
{
echo"<div class=\"todoitemwr\" name=\"todoitemwr(". $row1['todo_id'] .")\" ID=\"todoitemwr(". $row1['todo_id'] .")\"><span class=\"todoitem\">" . $row1['todo_item'] . "</span><span class=\"rmv\" onclick=\"rmvtodo(". $row1['todo_id'] .")\" onmouseover=\"className='rmvon';\" onmouseout=\"className='rmv';\">X</span><img src=\"images/edit.png\" class=\"edt\" onclick=\"edttodo(". $row1['todo_id'] .")\"></img></div>";
}
?>
</div>
As you can see the div id is dynamically named based on the id of the information that has been retrieved. The use of my ajax code above is to be able to edit the text that is retrieved in-situ and once corrected/altered it can then be re-submitted and update that record.
I'm sure that it is simply a case of understanding how JavaScript requires me to combine the text and str value in the document.getElementById("todoitemwr(2)") part.
As usual any help is much appreciated.
Alan.
Instead of using id="todoitemwr(2)" write id="todoitemwr_2".
That's because braces are not allowed in ID attributes.
The code would become:
document.getElementById('todoitemwr(' + str + ')')

Insert MySQL record with PHP and AJAX

trying to insert a record in my DB using AJAX for the very first time. I have the following...
Form
<form>
<input type="text" id="salary" name="salary">
<input type="button" onclick="insertSalary()">
</form>
AJAX
<script type="text/javascript">
function insertSalary()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('current-salary').innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","insert_salary.php",true);
xmlhttp.send("salary=" + document.getElementById("salary").value);
}
</script>
PHP
$uid = $_SESSION['oauth_id'];
$monthly_income = mysql_real_escape_string($_POST['salary']);
#Insert a new Record
$query = mysql_query("INSERT INTO `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;
Nowmy data is being inserted into the table BESIDES the 'salary' which is being inputted as '0'
Once inserted I also have a div 'current-salary' that should then be populated with there inputted value only it isnt, Can anybody help me to understand where im going wrong?
If you want to save your self a lot of time, effort, and heartache, use the jquery library for your ajax requests. You can download it at http://jquery.com/
After adding a reference(Script tag) to the jquery script your javascript for the ajax request would become:
function insertSalary()
{
var salary = $("#salary").val();
$.post('insert_salary.php', {salary: salary}, function(data)
{
$("#current-salary").html(data);
});
}
Also keep in mind that using "insert_salary.php" as the url means it is a relative path and must be in the folder of the current running script.
Your php script needs to echo whatever you would like to be injected into your current-salary tag also.

Auto-save textarea every so many seconds

I need help with "auto-saving" a textarea. Basically, whenever a user is typing in the textarea, I would like to save a "draft" in our database. So for example, a user is typing a blog post. Every 15 seconds I would like for the script to update the database with all text input that was typed into the textarea.
I would like for this to be accomplished thru jQuery/Ajax but I cannot seem to finding anything that is meeting my needs.
Any help on this matter is greatly appreciated!
UPDATE:
Here is my PHP code:
<?php
$q=$_GET["q"];
$answer=$_GET["a"];
//Connect to the database
require_once('mysql_connect.php') ;
$sql="UPDATE english_backup SET q".$q."='".$answer."' WHERE student_id = {$_COOKIE['student']} LIMIT 1";
$result = mysqli_query($dbc, $sql);
?>
Here is my javascript code:
<script type="text/javascript">
function showUser(str, answer)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getuser_english.php?q="+str+"&a="+answer,true);
xmlhttp.send();
}
</script>
function saveText() {
var text = $("#myTextArea").val();
// ajax call to save the text variable
// call this function again in 15 seconds
setTimeout(saveText, 15000);
}();
I think you want something like ajax... I'm using ajax jQuery so you will need jQuery Library for it to work. Download it. You can find tutorials on the documentation tab of the website.
//in your javascript file or part
$("textarea#myTextArea").bind("keydown", function() {
myAjaxFunction(this.value) //the same as myAjaxFunction($("textarea#myTextArea").val())
});
function myAjaxFunction(value) {
$.ajax({
url: "yoururl.php",
type: "POST",
data: "textareaname=" + value,
success: function(data) {
if (!data) {
alert("unable to save file!");
}
}
});
}
//in your php part
$text = $_POST["textareaname"];
//$user_id is the id of the person typing
$sql = "UPDATE draft set text='".$text."' where user_id='".$user_id."'"; //Try another type of query not like this. This is only an example
mysql_query($sql);
if (mysql_affected_rows()==1) {
echo true;
} else echo false;
Hey everyone I'm still having a problem please see here https://stackoverflow.com/questions/10050785/php-parse-html-using-querypath-to-plain-html-characters-like-facebook-twitter

Onbeforeunload - popux box will not display or trigger

I am building a website with user-profiles. I am at the picture part at the moment. When a person upload their image with no problem, the picture will be stored in 4 different folders. One for size 25, 100, 150 and normal size. After this they will be redirected to the same page, with new content. This is the part, where they need to crop their picture. Crop part works great, but I have a problem. When they leave the site without cropping, the pciture they just uploaded is still stored in the folders, and that's not what i want. So i mate some checks with AJAX, and it will unlink the 4 files sotred already. My problem is, that this shall only happen, when they leave the site(onbeforeunload.)
This works very great in IE, but not in Chrome.(Only two browsers i've tested yet.)
Here is what I'm doing:
function unfinished(album,img){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
}
The function above get information from "uncl/unfinished.php" by the query string. And it all works well.
Code on unfinished.php:
session_start();
require('../dbconnect.php');
$sql = "SELECT * FROM users WHERE username='".$_SESSION['username']."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$username= $row['brugernavn'];
}
$album = $_GET['a'];
$img = $_GET['i'];
$sourcex = "../users/".$username."/images/".$album."/x-x/".$img;
$source25 = "../users/".$username."/images/".$album."/25/".$img;
$source100 = "../users/".$username."/images/".$album."/100/".$img;
$source150 = "../users/".$username."/images/".$album."/150/".$img;
if(unlink($sourcex)){
}
if(unlink($source25)){
}
if(unlink($source100)){
}
if(unlink($source150)){
}
echo "Error 908. The picture didn't get cropped, and neither saved. Try again.";
The AJAX code and unfinished.php deletes the images withpout any problems. I've tested that already. Now my problem:
I am running the AJAX code by
The code should be running inside this:
//function warn(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = unfinished(album,img);
}
// For Safari
return unfinished(album,img);
};
//}
But when i try to return xmlhttp.responseText, the popup box doesn't popup, and i am not able to see the response.
But if i add "Hello world"(or some text) to the return like return Helloworld!''; or e.returnValue = 'Hello world!';, instead of the xmlhttp.responseText value, it pops up, and display the message. But it doesn't display the xmlhttp.responseText, because it doesn't run the unfinished() function.
any solutions how i can run the AJAX when user leaves page?
If it helps here is the HTML code:
if($_POST['where'] == "newalbum"){
$nameonalbum = $_POST['nameonalbum'];
}else{
$nameonalbum = $_POST['existingalbum'];
}
$filenamenew=time().'.gif';
?>
<body onload="warn('<?=$nameonalbum?>','<?=$filenamenew?>')">
Solved it by myself. Did like this:
function unfinished(album,img){
window.onbeforeunload = function (e) {
e = e || window.event;
var response = '';
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
response = xmlhttp.responseText;
}
}
xmlhttp.open("GET","incl/unfinished.php?a=" + album + "&i=" + img,true);
xmlhttp.send();
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = response;
}
// For Safari
return response;
}
}
But now i have another problem... 1st of all the unload function works great, but I don't want it to trigger when the "Save crop" button is clicked. Any ideas how to do this?
Save button html:

AJAX Help needed

I've recently stumbled upon a small issue. Basically I'm trying to give my users the ability to search thru a certain category on my site, but the search is done via AJAX and will not reload the page, simply the content that is being searched through.
The following codes is what I came up with so far, but the only time where it will change something is when there will be no value in the textbox, other than that the content isnt being updated (I checked the PHP file manually and there is no erros & with HTTP Direct addon for Firefox I made sure the call to my php file is made)
My code:
category.php:
<script type="text/javascript">
function showCat(str, cat)
{
if (str=="")
{
document.getElementById("showCategory").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("showCategory").innerHTML=xmlhttp.responseText;
}
}
url="../cat_search.php?q="+str+"&cat="+cat
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
<input type="text" name="showCat" onkeyup="showCat(this.value, <?=$id?>)" style="width: 140px;" />
<div id="showCategory">
## Stuff is being listed here on the load of the page & then should be updated with Ajax
</div>
cat_search.php:
<?php
include("config.php");
include("global.php");
$q=$_GET["q"];
$cat=$_GET["cat"];
$search = $q;
$q = "%".$q."%";
$sql="SELECT * FROM games WHERE title like '$q' AND category = '$cat'";
$result = mysql_query($sql);
if(mysql_num_rows($result) == 0) {
echo "<center><div class=\"redbox\" style=\"width: 110px;\">No match</div></center>";
}
while($row = mysql_fetch_array($result)) {
echo '......';
} ?>
The $id is the actual category ID.
Let me know if you would have the slighest idea of what my problem could be, I use almost the same exact code for another type of search and it works like a charm.
Thanks you!
Use jQuery for AJAX. Seriously. It's very simple and painfulless. And WTH is that?
$q=$_GET["q"];
$search = $q;
$q = "%".$q."%";
Why not just?
$q = '%'.$_GET['q'].'%';
And, for example, a code in jQuery:
<script type="text/javascript">
$(document).ready(function(){
$('input[name=showCat]').keyup(function(){
showCat($(this).val(),$(this).attr('id'));
});
});
function showCat(str,cat) {
if (str == '') {
$('#showCategory').html('');
return;
} else {
$.get('../cat_search.php',{q:str,cat:cat},function(data){
$('#showCategory').html(data);
});
}
}
</script>
<input type="text" name="showCat" id="<?=$id?>" style="width: 140px;" />
<div id="showCategory">
## Stuff is being listed here on the load of the page & then should be updated with Ajax
</div>

Categories