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)
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'm just starting out with AJAX. I'm trying to create a test where I enter some text into a text input box, click a submit button on a form, and have that text display on my page. The immediate error that I am getting is a 404 error ( www.mysite.com/ajaxFunction() ), but I'm sure that there are others yet to be discovered. Can anyone please help me correct this to get me started out with AJAX? I'm spinning my wheels trying to get started. Also, please realize that I am calling a php script since this is what my ultimate goal will require, which is why I'm not just using JavaScript itself. Thanks!
Here is the html:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.action = getFeedback();
}
function getFeedback() {
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("feedback").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","scripts/handle_feedback.php",true);
xmlhttp.send();
}
//-->
</script>
<div id="leftsidebox"></div>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
</body>
</html>
handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
return $mytext;
?>
EDIT: Here is my latest html code. I made the change to the php (switching 'return' to 'echo')
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
window.onload = function ajaxFunction() {
document.myform.onsubmit = getFeedback;
}
function getFeedback() {
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("feedback").innerHTML=xmlhttp.responseText;
}
}
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textbox,true);
xmlhttp.send();
}
//-->
</script>
<div id="textboxdiv">
<form name="myform">
Text Here: <input type="text" name="textbox" id="name" />
<button type="submit">Submit</button>
</form>
</div>
<div id="feedback">
</div>
scripts/handle_feedback.php
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
This won't do what you're expecting it to do:
document.myform.action = getFeedback();
You're probably expecting it to make it call getFeedback when the form is submitted. That's not actually what happens. When the browser tries to run that code, it will realize: “oh, hey, we're assigning action. But wait, on the right hand side, there's a function call! I've got to evaluate that function call in order to find the return value to set action to!” And so your browser dutifully calls getFeedback immediately. Since getFeedback doesn't return anything, it sets action to undefined. Boy, that was helpful.
If we want a JavaScript function to be called when the form is submitted, setting action is not the right way to do it. So what is the right way? An event listener. The most common way of attaching an event listener is using addEventListener, but since your use case is rather simple, we're going to use a simpler, often neglected way: setting onsubmit:
document.myform.onsubmit = getFeedback;
Note that we do not have parentheses after getFeedback. This is intentional. We want to set onsubmit to the getFeedback function itself, not its return value.
You're also using textbox without defining it. Sure, it exists in the document, but that doesn't mean it's a variable available in the script. To access it, you'll need to first get the element and then get that element's value:
document.getElementById('name').value
Another thing that might be getting you is the same origin policy. Rather than using a complete URL to open, just pass a relative URL:
xmlhttp.open("GET", "something.php" /* ... */, true);
It should be echo not return. return is used in function to return the data.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
Also you have to send the parameter to php file
xmlhttp.open("GET","scripts/handle_feedback.php?textbox=your_value",true);
First point : you missed request parameters from client end.
Send parameters in querystring for GET request.
var textvalue = document.getElementById("name").value;
xmlhttp.open("GET","scripts/handle_feedback.php?textbox="+textvalue ,true);
for more reference read here.
And second point is :
'return' statement is used with functions/methods. Since you don't have any function here, so instead of that use 'echo' or 'print' statement.
<?php
$mytext = $_REQUEST['textbox'];
echo $mytext;
?>
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'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>
I am trying to figure out how to submit a form in a page being accessed by AJAX?
Here are some code snippets to help demonstrate what I am trying to say.
HTML BODY - THIS IS WHAT THE USER WILL SEE:
<html>
<head>
<script language="javascript" src="linktoajaxfile.js">
</head>
<body onLoad="gotoPage(0)">
<div id="fillThis">
</div>
</body>
</html>
Ajax file:
var xmlhttp
function gotoPage(phase)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="pageofstuffce.php";
url=url+"?stg="+phase;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("fillThis").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
PAGE OF DATA:
<?php
$stage = $_GET['stg'];
if($stage == 0)
{
echo '<a onClick="gotoPage(1)">click me</a>';
}
elseif($stage == 1)
{
<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>
}
elseif(somehow can reach here)
{
show data from form.
}
?>
How to get past the form and display the data in the same page?
I have tried submitting the form to itself (same file) and that destroyed the AJAX link, and opened the page. I have also tried just having the button move the page onto another step, but the $_POST variable is empty.
hey u can go through this link
http://www.ajaxlines.com/ajax/stuff/article/how_to_submit_a_form_with_ajax_in_jquery.php
let me know if any issues regarding this
I think there's a bug in your code. You are not setting the stage variable anywhere.
Look at:
url=url+"?stg="+phase;
Probably you'll have to change stg => stage.
Don't see any other issue with it.
Hi for displaying the result or form in the same page u can use
form method ="POST" action =
or if u want to use ajax then write one function in jquery something like this
function call() {
$.ajax({
type:'POST',
url:'path to same file name?action=submit',
// data u want to pass
data:',
success:function() {
}
});
}//function ends
and ur php code
check if $_GET['action'] is there then execute ur function
Thanks
Here are the scripts that you are looking for.
pageofstuffce.php
<?php
$stage = $_GET['stg'];
if($stage == 0)
{
echo '<a onClick="gotoPage(1)">click me</a>';
}
elseif($stage == 1)
{
echo '<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>';
}
else
{
echo 'show data from form.';
}
?>
Your HTML
<html>
<head>
<script type="text/javascript" language="javascript" src="linktoajaxfile.js"></script>
</head>
<body onload="gotoPage(0)">
<div id="fillThis">
</div>
</body>
</html>
Javascript for making Ajax Calls linktoajaxfile.js
var xmlhttp
function gotoPage(phase)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
var url="pageofstuffce.php";
url=url+"?stg="+phase;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("fillThis").innerHTML=xmlhttp.responseText;
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
Hope this will Help!
Thanks!
Hussain.