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
Related
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();
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.
This is a very simple function if one where to use an input tag, unfortunately i have to use a link tag since i'm working with alphabet grouping that would retrieve the values on a different page.
here's a code i found for link tag to hold a value to be submitted to ajax
echo '<a onclick="passPagination(\'3\');passLetter(\'S\')">NEXT</a>';
i want to call all letters "s" page "3" from the other page.
function passLetter(str)
{
if (str=="")
{
document.getElementById("retail_group").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("retail_group").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","otherpage.php?letter="+str,true);
xmlhttp.send();
}
function passPagination(str)
{
if (str=="")
{
document.getElementById("retail_group").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("retail_group").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","otherpage.php?pageno="+str,true);
xmlhttp.send();
}
also i want to call again the letter that was passed to the otherpage so that i would make it as a reference for my pagination links that is also being hold in this page.
echo 'NEXT';
i am really at lost here since i am not familiar with link tag and ajax working together, also as you may have noticed i am not also that good with ajax judging from my very long ajax code.
Your help is greatly appreciated, Thank You.
i am really new at ajax. :)
The solution is to make a function with multiple arguments:
function passPaginationAndLetter(page, letter)
{
if (page=="" || letter == "")
{
document.getElementById("retail_group").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("retail_group").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","otherpage.php?letter="+letter+"&pageno="+page,true);
xmlhttp.send();
}
You can now call this with
echo '<a onclick="passPaginationAndLetter(\'3\',\'S\')">NEXT</a>';
The difference is that you are not calling two AJAX methods, just one.
I'm not pretty sure if i got what you mean, but i guess you want to something like that
echo '<a onclick="get(\'S\', '. ($_GET['page'] + 1) .')">NEXT</a>';
function get(letter, page) {
if (!letter) {
document.getElementById("retail_group").innerHTML="";
return;
}
if (!page) {
page = 1;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("retail_group").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","otherpage.php?letter=" + letter + "&pageno=" + page,true);
xmlhttp.send();
}
if it's really that, don't forget to validate the variables got from $_GET before use that, i just didn't because it's not the point...
I think this is what you're looking for:
html
PREVIOUSNEXT
javascript
var current = {
page: 0,
letter: a
};
function ajax(url) {
var xmlhttp = window.XMLHttpRequest || new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function(xmlhttp) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByI("retail_group").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function next() {
ajax("otherpage.php?letter=" + current.letter + "&pageno=" + (++current.page));
}
function previous() {
ajax("otherpage.php?letter=" + current.letter + "&pageno=" + (--current.page));
}
This code is not complete of course, it doesn't check for the max/min values of the pages, and there's no way of replace the letter, but it should point you in the right direction.
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'll get to the point, assume my PHP script returns an array with two values, how would I address them within javascript?
<script type="text/javascript">
function ValidateCard(cardno)
{
if (cardno.length==0)
{
document.getElementById("txtprice").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("txtprice").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","coding/validation/validatecard.php?cardno="+cardno,true);
xmlhttp.send();
}
</script>
As you can see whatever is returned is send to display within a div tag, how would I differentiate between data?
Thanks
You could use json to serialize it so that javascript can read it.
So, in php json_encode($arr);
http://www.php.net/manual/en/function.json-encode.php
Then in javascript.
you should be able to do something like jsarr[key] to get the values
<?php
$result = array('success'=>1, 'messgae'=>"the message you want to show");
echo json_encode($result);
?>
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
result = xmlhttp.responseText.evalJSON(true);
//you can use result as array to get the information you want to check
if (result['success']) {
document.getElementById("successs").innerHTML=result['message'];
}
}
}