954,566 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

using ajax for search engine result not working?

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>
  </td>

  <td>
  <label for="testinput"><b>Location</b> </label>
  </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.

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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

Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

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

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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

Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

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

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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?

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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

Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

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!

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

I think I should just redo the search script huh?

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 
Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

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?

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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

Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

I get no alert at all

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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

Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

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

Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

Okay, I get three alerts now.

1) results.php
the search URL
POST

2) ERROR: error

3) COMPLETE: error

:(

Thank you for helping me!

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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

Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

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.

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 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

Airshow
WiFi Lounge Lizard
Moderator
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
 

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"

andrewliu
Junior Poster
188 posts since Jul 2010
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: