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.

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

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

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

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

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?

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

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!

I think I should just redo the search script huh?

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

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?

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

I get no alert at all

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

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

Okay, I get three alerts now.

1) results.php
the search URL
POST

2) ERROR: error

3) COMPLETE: error

:(

Thank you for helping me!

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

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.

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

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"

Any idea on how I can go around this? It should be set if I'm getting errors if I comment that part of the code out right?

Andrew,

Create a new php file with a stripped out version of your php - no search and no search results - just have it return the single word "SUCCESS!!!". Now adjust your form's action attribute to call the new page.

When you've got it working, build the page up by progressively adding code in from your original php file. Findout at which point it breaks. Be inventive in the way you add the code back in and where you place your "SUCCESS!!!" message.

Airshow

Yeah I'll give that a try!

Thank you!

okay i'm stupid -_-

So I tried doing a testing.php with echoing out testing and saving it with the same files as my results.php

and I found out that my form action should be

<form action="includes/results.php"

before I didn't have the includes....

but now when I test my alerts, I get div tag alerts in my SUCCESS alert, and for COMPLETE: success

Wow, that's seriously good progress!!!!

Now comment out all the alerts to allow the original code to do its suff unhindered.

What do you get?

Airshow

When I comment out of the alerts, I don't get any results. its just blank again.

Andrew,

I think it's tmie for you to post your javascript code again so I can see exactly what you have after all the changes.

Airshow

This is my javascript code. I commented out the alerts.

$(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 = "GET";//$(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;
  });

});

Andrew,

There's a problem at lines 4 and 15, which are incompatible with eachother. var ajax_div = $(this).attr("id")+"_results"; returns an instance of jQuery, whilst $("#"+ajax_div).html(data); attempts to make another one from it.

Try replacing line 15 with ajax_div.html(data); .

Airshow

I tried what you suggested, it seems like it still gives me a blank result.

Its weird because I was able to echo out "testing" when I tried a new testing.php page with just echoing out that word.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.