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();
Related
I'll over simplify the problem in order to make it easier. I'm using the following Ajax script to call another .php file and have it return the results to the original page. I'm using Apache offline and the page is unfortunately returning blank.
<html>
<head>
<script>
function showInfo(str) {
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("result").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","practice.php?q="+str,true);
xmlhttp.send();
}
window.onload = function() { showInfo('bleh'); };
</script>
</head>
<body>
<div id="result"></div>
</body>
//Then the code below is another file called practice.php, which corresponds the ajax above
<?
$test = $_GET['q'];
echo $test;
?>
I am pretty sure $_GET is a case-sensitive variable name on most OSes, so $_Get would be empty.
I would comment if I could -
What happens when you try to hit the page directly (ie put practice.php?q=test) in the browser?
Also I can't find any documentation (it's hard to google it), but it wouldn't hurt to make the opening tag <?php instead of just <?
I am trying to use AJAX on a form so that the user doesn't have to leave the current page to submit their name. I have got the function to work when the user types their name; it changes automatically while they're typing. What I'm struggling with is the onClick to submit the name. I am not receiving any response from the PHP file and I do not know why. Here is my code:
The form page: (The submit function sends the name through a global variable via the GET request)
<script type="text/javascript">
//Decalre the variables of name as Global variable
var name;
//For IE 5 + 6
function httpReq(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function nameTest(str) {
if (str.length==0) {
document.getElementById("nameTest").innerHTML="Please enter your name.";
return;
}
httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("nameTest").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","nameTest.php?q="+str,true);
xmlhttp.send();
return name = str;
}
// function to submit the users details to the database
function submit(str) {
httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("submitted").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mailing-list.php?name="+name, true);
xmlhttp.send();
}
</script>
Name: <input type="text" onkeyup="nameTest(this.value)">
<span id="nameTest">Please enter your name.</span>
<input style="width: 100px; height: 40px;" type="button" onclick="submit" value="Join!">
<span id="submitted"></span>
The PHP page which doesn't give a response (Just echoing something simple until I get a response):
<?php
$name = $_GET["name"];
echo "Hello There " + $name;
?>
Can't seem to figure out why there is no response. Any help appreciated!
var name;
//For IE 5 + 6
function httpReq(){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
} else {
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function nameTest(str) {
if (str.length==0) {
document.getElementById("nameTest").innerHTML="Please enter your name.";
return;
}
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("nameTest").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","nameTest.php?name="+str,true);
xmlhttp.send();
window.name = str;
}
// function to submit the users details to the database
function submit() {
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("submitted").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mailing-list.php?name="+window.name, true);
xmlhttp.send();
}
You haven't assigned a value to xmlhttp, probably the console tells you it is undefined, you should check it.
Sorry, there are a lot of errors inside your code. I edited it, you should try now.
submit() doesn't get params, it just get the name from the global variable name(window.name), which was set before by the function nameTest(str).
Last thing: you should check compatibility between what you want client and server side. You used "?q=" instead of "?name=" in your query string, pay attention to these things!
According with LightStyle, you should use the return of httpReq() method to retrieve your requestObject.
var xmlhttp = httpReq();
xmlhttp.onreadystatechange=function() {...}
You have to modify
onclick="submit"
into onclick="submit();" to make it called.
This PHP script will return 0, the concatenation operator is . in PHP :
<?php
$name = $_GET["name"];
echo "Hello There " . $name;
?>
Value "name" in your function submit(str) is unknown, and thus empty. change that into
xmlhttp.open("GET","mailing-list.php?name="+str, true);
and call your function like this:
submit("NameToShow");
BTW: Using jQuery would make this alot easier for you.
I am new to AJAX and looking for better way to do this. I have search box which searches for string in a array of about 10,000 strings. Code is given below but is way too slow. Of course there is a better way. What is it ?? Here is the HTML and javascript
<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>
<body>
<h3>Start typing a name in the input field </h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
Here is the php code:
include_once("array.php"); //array.php contains array of 10,000 strings
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
After half an hour of chat on IRC someone has convinced me that the best way would be to use a search engine like
sphinx search
elastic search
I am new to programming and its my first time to learn AJAX with PHP.
I got a working sample code from internet and studying it but there are some codes that I don't understand and I am really frustrated.
In the index.php, I am so confused about the code xmlhttp.open("GET","gethint.php?q="+str,true);. I dont know what the q stands for. As far as I understand, q should stand for an html element with a name q. For example I have <input type="text" name="q" /> then I know that I have a textbox name q. But in this example I can't find any element that has a name q. Pls help...
index.php
<html>
<head>
<script type="text/javascript">
function showHint(str)
{
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>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)" size="20" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
gethint.php
<?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=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
In your example, q is a parameter that is passed to gethint.php with the value contained in the variable str.
The variable gets its value from the "First name" input element, whenever a key is pressed and released (the onkeyup event).
The value of q is then accessed in the PHP file by the line $q=$_GET["q"];.
You can name the parameters passed to the PHP page however you like, they don't need to correspond to HTML elements.
q is name of parameter of HTTP GET request:
Hypertext_Transfer_Protocol#Request_methods
its a LIKE A URL parameter which is simmilar to
php,
gethint.php?q=mYstring
echo $_GET['q'];// output as mYstring
In js,
var str ='mYstring';
"gethint.php?q="+str
echo $_GET['q'];// output as mYstring
i thing u can get if any problem accour add comments..pal
(DO it always)
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>