AJAX Help needed - php

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>

Related

PHP Ajax showhints as user starts typing

I am trying to understand and apply Ajax functionality to my site. But i faced with some questions and I need some explanation . Here is a code that I get from w3school.com:-
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
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","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" name="fname" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
// and here is gethint.php code
<?php
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
// get the q parameter from URL
$q=$_REQUEST["q"]; $hint="";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len = strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name,0,$len))) {
if ($hint==="") { $hint=$name; }
else { $hint .= ", $name"; }
}
}
}
// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint==="" ? "no suggestion" : $hint;
?>
But I have the following questions:
why we use str.length==0? because I thought it should be
fname.length==0
what is the use of q="+str in "gethint.php?q="+str part?
why we use $q=$_REQUEST["q"]? because I thought it should be
$q=$_REQUEST["fname"]
1: str.length==0 will check if entered string should at least 1 character long or not null.
2: q="+str" in gething.php?q="+str" --- it means once you enter any character from this url it will start looking entered character in database by passing(appending) str as parameters in the url.
3: $q=$_REQUEST["q"] .. would get the value passed in url as parameters.
Hope this would help you.
str.length==0? its optional. if you feel its needy then use it else abort .actually this is for showing the result to the innerHTML
q="+str in "gethint.php?q="+str part? bcz xmlhttp.open("GET","gethint.php?q="+str,true); in this xmlhttp.open pass varible in two methods like GET or POST
SO it need to pass the variable where your full data is stored like q from here it pass the value and showing results by use of xmlhttp.send();

Change an image using AJAX

I want to create a login page.
So I put a captcha picture in the login form with following html code:
<img name="captcha" id="captcha" src="captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5"/>
and I put a button that users can click on to change captcha if it is unreadable as follow :
<input type="button" name="new_Captcha_button" onClick="new_captcha()"/>
and I wrote a script as follow which work just in chrome :
<script type="text/javascript">
function new_captcha()
{
document.images["captcha"].src = "captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5";
}
</script>
but it doesn't work in other browsers, so I replace the previous code with the following :
<script type="text/javascript">
function new_captcha()
{
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)
{
document.getElementById("captcha").src = xmlhttp.responseText;
  }
}
xmlhttp.open("GET","captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5",true);
xmlhttp.send();
}
So please tell me what changes I need to do in my code to make it correct. I think I need to change just following line :
document.getElementById("captcha").src = xmlhttp.responseText;
Thanks a lot.
<script type="text/javascript">
function new_captcha()
{
document.getElementById('captcha').src = 'captcha/CaptchaSecurityImages.php?width=90&height=28&characters=5&_t=' + Math.random(1);
}
</script>
Do not need to use ajax, function new_captcha() is ok as it is.
You may try to do this
login.php
<div id="captcha_container"></div>
<input type="button" id="btn_recaptcha" value="Recaptcha">
<script>
function ajax_loadpage(loadUrl,output_container)
{
$.post
(
loadUrl,
{language: "php", version: 5},function(responseText){$(output_container).html(responseText);},"html"
);
}
ajax_loadpage("captcha_page.php","#captcha_container");
$('#btn_recaptcha').click(function(){
ajax_loadpage("captcha_page.php","#captcha_container");
})
</script>
______________________________________________________________________________________
captcha_page.php
<img width="212" height="53" src="captcha.php">
captcha.php contains my captcha code, it contains a header ("Content-type: image/gif"); code, so i needed an extra php file on where i can save the image file, thus using my captcha_page.php.
Worked for me :)

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

How to implement hit counter with light box

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.

Categories