1,105,333 Community Members

using ajax for search engine result not working?

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hello, I was wondering what could be wrong? There is this ajax code that I'm trying to work on and its supposed to show the results in a div tag when submitting a search form, but theres no results.

here's my code

$(document).ready(function(){

  $("form.ajax").submit(function(){
     var ajax_div = $(this).attr("id")+"_results";
     var data = $(this).serialize();
     var url = $(this).attr("action");
     var type = $(this).attr("method").toUpperCase();
     $.ajax({
        url: url,
        data: data,
        type: type,
        success: function(data){
            $("#"+ajax_div).html(data);
        }
     });
     return false;
  });

});

my form code

<form action="results.php" name="form" method="post" id="search" class="ajax" style="float:right;width:650px;height:60px;margin-right:30px;" onSubmit="return searchLocations();" >
<table style="float:right;"><tr>
<td>
  <label for="testinput"><b>Search</b> </label><br />
  </td>

  <td>
  <label for="testinput"><b>Location</b> </label><br />
  </td></tr>
  <tr>
  <td>
  <input name="search_term" id="search_term" type="text" style="height:23px; margin-right:20px;font-size: 16px" value="<?PHP echo $search_term; ?>" size="36" autocomplete="off"/></td>
  <td>
  <input name="addressInput" id="addressInput" type="text" style="height:23px;margin-right:10px;font-size: 16px" value="<?PHP echo $location_term; ?>" size="36" autocomplete="off"/></td><td>
  
  <select id="radiusSelect">

      <option value="25" selected>25</option>
      <option value="100">100</option>

      <option value="200">200</option>

    </select>
    </td><td>

 <input type="submit" name="search_button" style= "padding: 5px; font-family: Arial, Helvetica, sans-serif; font-size: 12px;" value="Search" onClick="searchLocations();" />
  
  </td></tr></table>
</form>

Here's my results page

<?php include("search_query.php");?>

<?PHP
 
if($results != 0)
{
?>  
<table style="width:950px;"><tr><td style="float:left">Results for <?PHP echo "<i><b><font color=#000000>".$search_term."</font></b></i> "; ?></td>


<td style="float:right">Results <b>
<?PHP echo ($first_pos+1)." - ";
      if(($RESULTS_LIMIT + $first_pos) < $results) echo ($RESULTS_LIMIT + $first_pos);
      else echo $results ; ?>
    </b>
      out of <b><?PHP echo $results; ?></b>
      for(<b><?PHP echo sprintf("%01.2f", $time_search); ?></b>)
      seconds </td>
</tr>
</table>

<?php require("filter.php");?>

<table style="float:left;position:relative">

  <?PHP   
    while($row = mysql_fetch_array($sql_result_query))
    {
    ?>
      <tr align="left">
        <td colspan="2" style="padding-right:30px;"><?PHP echo $row['product']; ?></td>
        <td colspan="2"><?PHP echo $row['location']; ?></td>
      </tr>
  <?PHP
    }
    ?>
</table>

<?PHP
}
elseif(isset($sql_query))
{
?>
<table border="0" cellspacing="2" cellpadding="0">
    <tr>
        <td align="center">No results for   <?PHP echo "<i><b><font color=#000000>".$search_term."</font></b></i> "; ?></td>
    </tr>
</table>
<?PHP
}
?>
<div style="float:left;position:relative;">
<?php require("includes/pagination.php");?>
</div>

with my search query php code

<?PHP
global $search_term;
global $location_term;
global $results;
function getmicrotime()
{
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
$connection_string = "connectionstring.php";
require_once($connection_string);
mysql_select_db("chef") or die ( 'Unable to select database.' );
$RESULTS_LIMIT=5;
if(isset($_GET['search_term']) && isset($_GET['addressInput']) && isset($_GET['search_button']))
{
      $search_term = $_GET['search_term'];
	  $location_term = $_GET['addressInput'];
	  
    if(isset($_GET['first_pos']))
    {
		$first_pos = $_GET['first_pos'];
	}
	else
	{
        $first_pos = 0;
    }

    $start_search = getmicrotime();
    $sql_query = mysql_query("SELECT * FROM searchengine WHERE MATCH(product) AGAINST('$search_term') AND MATCH(location) AGAINST('$location_term')");

    if($results = mysql_num_rows($sql_query) != 0)
            {
                $sql =  "SELECT * FROM searchengine WHERE MATCH(product) AGAINST('$search_term') AND MATCH(location) AGAINST('$location_term') LIMIT $first_pos, $RESULTS_LIMIT";
                  $sql_result_query = mysql_query($sql);   
            }
    else
            {
                  $sql = "SELECT * FROM searchengine WHERE (product LIKE '%".mysql_real_escape_string($search_term)."%' AND location LIKE '%".mysql_real_escape_string($location_term)."%') ";
                  $sql_query = mysql_query($sql);
                  $results = mysql_num_rows($sql_query);
                  $sql_result_query = mysql_query("SELECT * FROM searchengine WHERE (product LIKE '%".$search_term."%' AND location LIKE '%".$location_term."%') LIMIT $first_pos, $RESULTS_LIMIT ");
            }
    $stop_search = getmicrotime();
    $time_search = ($stop_search - $start_search);
}
?>

<?PHP
 
if($results != 0)
{
?>  
<table style="width:950px;"><tr><td style="float:left">Results for <?PHP echo "<i><b><font color=#000000>".$search_term."</font></b></i> "; ?></td>


<td style="float:right">Results <b>
<?PHP echo ($first_pos+1)." - ";
      if(($RESULTS_LIMIT + $first_pos) < $results) echo ($RESULTS_LIMIT + $first_pos);
      else echo $results ; ?>
    </b>
      out of <b><?PHP echo $results; ?></b>
      for(<b><?PHP echo sprintf("%01.2f", $time_search); ?></b>)
      seconds </td>
</tr>
</table>

<?php require("filter.php");?>

<table style="float:left;position:relative">

  <?PHP   
    while($row = mysql_fetch_array($sql_result_query))
    {
    ?>
      <tr align="left">
        <td colspan="2" style="padding-right:30px;"><?PHP echo $row['product']; ?></td>
        <td colspan="2"><?PHP echo $row['location']; ?></td>
      </tr>
  <?PHP
    }
    ?>
</table>

<?PHP
}
elseif(isset($sql_query))
{
?>
<table border="0" cellspacing="2" cellpadding="0">
    <tr>
        <td align="center">No results for   <?PHP echo "<i><b><font color=#000000>".$search_term."</font></b></i> "; ?></td>
    </tr>
</table>
<?PHP
}
?>
<div style="float:left;position:relative;">
<!--require("includes/pagination.php")!-->

</div>

I know this is a lot of coding but I think whats giving me problems is the form code and the ajax.


I want to thank for those who are willing to help me out.

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

Andrew,

The only thing that jumps out at me is that the FORM has method="POST" while the PHP expects "GET".

If this doesn't fix it then you need a debug strategy. I suggest splitting the thing down the middle - test client-side and server-side independently.

1. TEST THE REQUESTING PAGE
a. Test against a hard coded test page in place of results.php . Create a page with the single line "*** TEST MESSAGE ***" and save as test.html , then edit your form tag to read <form action="test.html" ... .

b. Was the test message retreived and displayed properly in the target DIV?

2. TEST THE PHP
a. Comment out the whole $("form.ajax").submit(function(){ .... such that on form submission a regular (non-AJAX) request is made.
b. Are search results correctly returned and displayed in a new page?

3. If both tests (1 and 2) are successful, then you have an incompatibility between the AJAX request and the what the PHP expects. (You have already fixed POST/GET but there may be something else).

Airshow

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Hello,

Thank you for responding. I did change the $_GET to $_POST and I've messed around with my code and I think its in the results.php page. Because when I changed my

<form action="search_query.php"> to <form action="">

it pops up my original page. So I can conclude that my ajax code is correct? But I'm not sure what my problem is with my search_query.php

thanks again for your help

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

Andrew,

I did change the $_GET to $_POST and I've messed around with my code and I think its in the results.php page. Because when I changed my <form action="search_query.php"> to <form action=""> it pops up my original page. So I can conclude that my ajax code is correct? But I'm not sure what my problem is with my search_query.php

You can be confident that your ajax code is capable of issuing a null request and handling the response. You don't yet know that it composes the intended request correctly. Now that you are using GET, you can insert a javascript alert to observe the composed URL before it is sent.

Have you tried my tests 1 and 2 yet?

Airshow

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I'll try that. It might take me awhile to figure out what you're talking about, but I'll try it.

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I tested it and it works. I can display the testing results. and when I took out the ajax code, I can retrieve my data from mysql through a search.

I feel like its in my search_query.php that I have to change up?

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

So my tests 1 and 2 are successful? If so then I would guess that server-side is OK.

Before you do anything else, make sure the AJAX code is OK by adding a couple of debug statements :

$(document).ready(function(){

  $("form.ajax").submit(function(){
     var ajax_div = $(this).attr("id")+"_results";
     var data = $(this).serialize();
     alert(data);//debug statement (serialised form data)
     var url = $(this).attr("action");
     var type = $(this).attr("method").toUpperCase();
     $.ajax({
        url: url,
        data: data,
        type: type,
        success: function(data){
            alert(data);//debug statement (tabulated search results)
            $("#"+ajax_div).html(data);
        }
     });
     return false;
  });

});

Do you see the two alerts and do they contain what you expect?

Airshow

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I do get the alerts. I get the alerts of the links that are supposed to come out if I had the search engine.

So before the ajax code I had my search engine working. It would refresh the page and there would be the url of the search engine.

example: index.php?search_term=&location_term=

now I get the alert with the new alert debug code, and it pops up the end part of the url "search_term=&location_term="

thank you for helping me!

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I think I should just redo the search script huh?

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

I do get the alerts. I get the alerts of the links that are supposed to come out if I had the search engine.

So before the ajax code I had my search engine working. It would refresh the page and there would be the url of the search engine.

example: index.php?search_term=&location_term=

Presumably this appeared in the browser's address bar and the search results appeared in the document body?

If the search engine worked before, then you should need to do very little to make it work with AJAX. Just make sure it serves the HTML for just the results, without <!DOCTYPE> or <html></html>, <head></head> or <body></body> tags. Under AJAX, the results are inserted into the current page, so DOCTYPE etc. remain intact.

now I get the alert with the new alert debug code, and it pops up the end part of the url "search_term=&location_term="

It's unclear to me what each alert shows.

ALERT 1: "search_term=&location_term=" is correct if your search form has two fieds named "search_term" and "location_term". If you enter apple pear in the search form, then you should see "search_term=apple&location_term=pear"

ALERT 2: Should show the marked up search results (HTML).

Airshow

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Thanks for responding,

My search engine did work prior to using ajax. My search_query.php page does not have any DOCTYPE or any HTML tags. Its just strictly php coding.

The first alert did show the URL that I'm supposed to be getting. It does pop up whatever I type into the form. However, I don't get anything for ALERT 2?

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

Andrew,

... I don't get anything for ALERT 2

Do you mean you get an alert with a blank message, or no alert at all?

There's a big difference.

Airshow

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I get no alert at all

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

Let's try some more debug statements in the javascript

$(document).ready(function(){

  $("form.ajax").submit(function(){
     var ajax_div = $(this).attr("id")+"_results";
     var data = $(this).serialize();
     var url = $(this).attr("action");
     var type = $(this).attr("method").toUpperCase();
     alert([url, data, type].join("\n"));//debug alert
     $.ajax({
        url: url,
        data: data,
        type: type,
        success: function(data){
            alert("SUCCESS: " + data);//debug alert
            $("#"+ajax_div).html(data);
        },
		complete: function(XMLHttpRequest, textStatus){
            alert("COMPLETE: " + textStatus);//debug alert
		},
		error: function(XMLHttpRequest, textStatus){
            alert("ERROR: " + textStatus);//debug alert
		}
     });
     return false;
  });

});

What alerts do you get now?

Airshow

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

Let's try some more debug statements in the javascript.

$(document).ready(function(){

  $("form.ajax").submit(function(){
     var ajax_div = $(this).attr("id")+"_results";
     var data = $(this).serialize();
     var url  = $(this).attr("action");
     var type = $(this).attr("method").toUpperCase();
     alert([url, data, type].join("\n"));//debug alert
     $.ajax({
        url: url,
        data: data,
        type: type,
        success: function(data){
            alert("SUCCESS: " + data);//debug alert
            $("#"+ajax_div).html(data);
        },
        complete: function(XMLHttpRequest, textStatus){
            alert("COMPLETE: " + textStatus);//debug alert
        },
        error: function(XMLHttpRequest, textStatus){
            alert("ERROR: " + textStatus);//debug alert
        }
     });
     return false;
  });

});

What alerts do you get now?

Airshow

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

Okay, I get three alerts now.

1) results.php
the search URL
POST

2) ERROR: error

3) COMPLETE: error

:(

Thank you for helping me!

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

Andrew,

I posted a reply here 12 hours ago but it's disappeared!!!

The problem appears to be "POST" which I thought we had gotten rid of.

Never mind, the easiest thing is to hard-code "GET" in the function:

Replace

var type = $(this).attr("method").toUpperCase();

with

var type = "GET";

Airshow

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I changed all my $_POST to $_GET and changed

<form method="post">

to

<form method="get">

and I changed the var type like you suggested,

and I get the same messages except now for the first alert, instead of POST its GET.

Member Avatar
Airshow
WiFi Lounge Lizard
2,798 posts since Apr 2009
Reputation Points: 333 [?]
Q&As Helped to Solve: 393 [?]
Skill Endorsements: 11 [?]
Team Colleague
 
0
 

Hmmmm, looks like we have to start looking server-side at the php.

Looking at this line,

if(isset($_GET['search_term']) && isset($_GET['addressInput']) && isset($_GET['search_button'])){

see if you can devise a test to see if all three variables are set. If any of them are not set then the search clearly won't work. I seem to recall that jquery.ajax() chooses not to pass on the value of a submit button by default so that's something you might consider changing (ie delete && isset($_GET['search_button']) from the if clause above).

Airshow

Member Avatar
andrewliu
Junior Poster
186 posts since Jul 2010
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

If I don't set those variables, my code doesn't work. I start getting errors like

"Undefined index: search_term in C:\wamp\www\nootri\includes\search_query.php on line 16"

and

"Undefined index: addressInput in C:\wamp\www\nootri\includes\search_query.php on line 17"

You
This question has already been solved: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: