Jump to content

Ajax Search Results


Manny

Recommended Posts

Take a look at my webpage:http://www.burndenaces.co.uk/video/To the right of the video, there is a search form and underneath, links to the most recently added videos.The problem I have is, when people are watching a video and want to search, they are taken to another page and the video starts from the beginning. What I want to be able to do is, even whilst the video is playing, a user can use the search facility and the DIV to the right is refreshed to show the results.Here is my current code for the right hand side:

<div id="relatedvideo">	<div id="search">		<p class="bigtext"><b>Search:</b></p>		<form name="search" onsubmit="return validForm(this)" action="<? echo $PHP_SELF; ?>" method="get" id="search">			<input type="text" name="s" id="s" size="30" value="Search..." onfocus="if (this.value == 'Search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search...';}" />			<input type="submit" value="Search" />		</form>	</div>		<p class="bigtext"><b>Related Videos:</b></p>		<?		$sqlstatement = "SELECT * FROM `videos` WHERE `MatchID` = '$matchid' AND `Key` <> '$key'";		$sql_result = mysql_query($sqlstatement,$connection) or die("<BR /><BR /><span class=\"c3\">Page could not be displayed.</span>");				//variables				while ($row = mysql_fetch_array($sql_result))		{		$relkey = $row["Key"];		$title = $row["Title"];		$date = $row["Date"];		$host = $row["Host"];		$length = $row["Length"];	?>										<div class="item">		<img src="/video/images/ball.gif" alt="" title="<? print "$title"; ?>" align="left" style="padding-right: 5px;" />		<a href="?v=<? print "$relkey"; ?>"><? print "$title"; ?></a><br />		Length: <? print "$length"; ?>, Added: <? print "$date"; ?><br />		<? require("/home/burndena/includes/video/sources.php"); ?>		<? if($relkey=="$key") print "<br />\n<font color=\"red\">Now Playing</font>"; ?>	</div>		<? } ?>	</div>

Link to comment
Share on other sites

I've only used it a couple of times, but not for things like this.What I would want to do is probably refresh the content below <p class="bigtext"><b>Related Videos:</b></p> with the results of the search form. All without resending the page.

Link to comment
Share on other sites

Right, so the first step is figuring out how to send the information to do the search. So you need to get whatever they entered and send it to a PHP script. Then the script needs to return the results, so you can either have it return the HTML markup directly, or return some JSON or something where you have Javascript arrange it on the page. If you just have it return HTML then you can use the innerHTML property to update whatever element you want to show the results in.

Link to comment
Share on other sites

I have a script which searches my database and displays the results. But at the moment, these results are shown on a seperate page.If you go to the link I put in the first post, type "Sunderland" and press search, this page will display. It is these results I want to show, but without refreshing the page. I thought AJAX would be the best thing to use.

Link to comment
Share on other sites

Yes, it will be the best thing to use. You need a new search page, one that only returns the HTML that you want to show up in the results box, and no other HTML. You send the request to that page using ajax to do the search, it returns the HTML, you update the page with the new HTML.

Link to comment
Share on other sites

What sort of code would I be looking at for the form then?I've had a look at the following tutorial, but it's the AJAX part where I become stuck.http://www.w3schools.com/PHP/php_ajax_database.aspI'm fine with the PHP side and the HTML side, just the AJAX to refresh the page I'm struggling with.

Link to comment
Share on other sites

You don't even really need a form, all you need is the text box and button. Instead of submitting the form, the button calls a Javascript function that gets the value in the text box, sends it to the search page, gets the result, and updates the page. You can put that in a form if you want and override the default submit action, but it's just as easy to leave out the form and just have the button call the Javascript.You'll need to understand how ajax works though. You create the XMLHttpRequest object like they show in the example, assign a function to handle the state change, give it a URL and send the data. The example shows that. You need to assign a function to handle the state change because Javascript doesn't wait for the response to come back from the server. But when it does come back, your state change function will get called and you can get the response from the XMLHttpRequest object and update the page. The example shows updating the page by setting the innerHTML property of an element on the page the same way you would need to do it.

Link to comment
Share on other sites

Ok, I've used the tutorial from W3Schools and edited parts of it for my use.Here is the code I have, but instead of refreshing the DIV, it is still moving to another page. What am I doing wrong? The "videoresults" div goes blank after pressing the submit button, but then a new page still loads.index.php (Search section only)

						<div id="relatedvideo">													<div id="videosearch">								<p class="bigtext"><b>Search:</b></p>																<form onsubmit="showResults(this.value)">									<input type="text" name="s" id="s" size="30" value="Search..." onfocus="if (this.value == 'Search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search...';}" />									<input type="submit" value="Search" />								</form>							</div>														<div id="videoresults">								 <!-- SOME CONTENT -->							</div>						</div>

searchresults.js

var xmlhttp;function showResults(str){xmlhttp=GetXmlHttpObject();if (xmlhttp==null)  {  alert ("Browser does not support HTTP Request");  return;  }var url="searchresults.php";url=url+"?s="+str;url=url+"&sid="+Math.random();xmlhttp.onreadystatechange=stateChanged;xmlhttp.open("GET",url,true);xmlhttp.send(null);}function stateChanged(){if (xmlhttp.readyState==4){document.getElementById("videoresults").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;}

searchresults.php

<?	$search = stripslashes($_GET['s']);	$query = "SELECT * FROM videos WHERE Keywords LIKE CONVERT( _utf8 '%" . mysql_real_escape_string($search) . "%' USING latin1 ) COLLATE latin1_swedish_ci ORDER BY VidID DESC $limit";	$result = mysql_query($query, $connection) or trigger_error("SQL", E_USER_ERROR);	$numrows = mysql_num_rows($result);		print "<p class=\"bigtext\">$search</p>	<br />\n";		//Process output of query		while ($row = mysql_fetch_array($result))	{	$searchkey = $row["Key"];	$title = $row["Title"];	$date = $row["Date"];	$host = $row["Host"];	$length = $row["Length"];	?>		<div class="item">		<img src="/video/images/ball.gif" alt="" title="<? print "$title"; ?>" align="left" style="padding-right: 5px;" />		<a href="?v=<? print "$searchkey"; ?>"><? print "$title"; ?></a><br />		Length: <? print "$length"; ?>, Added: <? print "$date"; ?><br />		<? require("/home/burndena/includes/video/sources.php"); ?>		<? if($recentkey=="$key") print "<br />\n<font color=\"red\">Now Playing</font>"; ?>	</div>	<?	} ?>

Link to comment
Share on other sites

If you're going to use a regular form you need the onsubmit handler to return false. If it doesn't return false the form will still submit after the Javascript finishes. Also, it's not going to work to pass this.value for the onsubmit handler. In that context, this refers to the form itself, which does not have a value. You need to refer to the text box instead. You can use document.getElementById to get the value of the text box. Finally, you need to encode the search text so that it doesn't mess up the URL:url=url+"?s="+ encodeURIComponent(str);Also, you can probably just leave out this line:url=url+"&sid="+Math.random();That's just to break the cache. If they're searching for the same thing, it probably doesn't matter if it's cached.

Link to comment
Share on other sites

Ok, so now I have this and it's still not doing what I'd hope.I'm really sorry if there is something obvious that I'm doing wrong, but I don't know what it is.index.php (Search form)

<form>	<input type="text" name="s" id="s" size="30" value="Search..." onfocus="if (this.value == 'Search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search...';}" onsubmit="showResults(this.value)" />	<input type="submit" value="Search" /></form>

searchresults.js

var xmlhttp;function showResults(str){xmlhttp=GetXmlHttpObject();if (xmlhttp==null)  {  alert ("Browser does not support HTTP Request");  return;  }document.getElementByID("s");var url="searchresults.php";url=url+"?s="+encodeURIComponent(str);xmlhttp.onreadystatechange=stateChanged;xmlhttp.open("GET",url,true);xmlhttp.send(null);}function stateChanged(){if (xmlhttp.readyState==4){document.getElementById("videoresults").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;}

Link to comment
Share on other sites

Text fields do not have an onsubmit action, forms do. You need to get the value from the text field inside the Javascript function. You can either use an onsubmit action on the form, or remove the form and put an onclick action on the button.

Link to comment
Share on other sites

Still no closer. Do you have any code which would better explain where I'm going wrong.index.php (Search Form) - Form tags removed and "onclick" action added to submit button

<input type="text" name="s" id="s" size="30" value="Search..." onfocus="if (this.value == 'Search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search...';}" /><input type="submit" value="Search" onclick="showResults(this.value)" />

searchresults.js is the same as my previous post.

Link to comment
Share on other sites

You keep trying to send this.value to the function. When you have that on the form in the onsubmit action, this refers to the form, which doesn't have a value. When it's on the button's onclick action, this refers to the button, so you're sending the function the value of the button, which is the word "Search".Don't send the function anything. Get the value of the text box inside the function using document.getElementById('s').value. You can also use a regular button instead of a submit button since the form is gone. e.g.:<button onclick="showResults();">Search</button>

Link to comment
Share on other sites

I replaced the submit button with the button code you suggested, but now it doesn't do anything at all.Search Form

<input type="text" name="s" id="s" size="30" value="Search..." onfocus="if (this.value == 'Search...') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search...';}" /><button onclick="showResults();">Search</button>

searchresults.js

var xmlhttp;function showResults(str){xmlhttp=GetXmlHttpObject();if (xmlhttp==null)  {  alert ("Browser does not support HTTP Request");  return;  }document.getElementByID("s").value;var url="searchresults.php";url=url+"?s="+encodeURIComponent(str);xmlhttp.onreadystatechange=stateChanged;xmlhttp.open("GET",url,true);xmlhttp.send(null);}MORE CODE BELOW...

Link to comment
Share on other sites

It probably has an error that says document.getElementByID is not a function (Javascript is case-sensitive).

function showResults(){  xmlhttp=GetXmlHttpObject();  if (xmlhttp==null)  {	alert ("Browser does not support HTTP Request");	return;  }  var url="searchresults.php";  url=url+"?s="+encodeURIComponent(document.getElementById("s").value);  xmlhttp.onreadystatechange=stateChanged;  xmlhttp.open("GET",url,true);  xmlhttp.send(null);}

Link to comment
Share on other sites

That seems to have done the trick. It loads the search results without reloading the page and the video continues playing.We got there in the end. Thanks for all your help!

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...