views:

98

answers:

2

Hi all,

I'm using the PHP code below to get results to return to an autosuggest / autocomplete. The problem is that if an earlier SQL query takes longer to return from the database than the most recent SQL query then the results of the older query will be displayed in the autosuggest results box. So if you start searching for Thomas, it might show the results for Tho if that SQL query takes longer. I was wondering if there is a way to cancel previous queries once a new one is implemented, or to make sure that the most recent query is used?

Best David

<?php
// begin XML output
$xmlStr = <<<XML
<?xml version='1.0' standalone='yes'?>
<authors>
XML;

// open database connection
$mysqli = new mysqli("localhost", "user", "pass", "library");      
if (mysqli_connect_errno()) {
    printf("Connect failed: %s
", mysqli_connect_error());
    exit();
}

// retrieve author list matching input
// add to XML document
$q = $mysqli->real_escape_string($_GET['query']);
$sql = "SELECT AuthorName FROM author WHERE AuthorName LIKE '" . $q . "%' ORDER by AuthorName";
if ($result = $mysqli->query($sql)) {
  while ($row = $result->fetch_row()) {
    $xmlStr .= '<author name="' . $row[0] . '"></author>';
  }
  $result->close();
}

// clean up
// output XML document
$mysqli->close();
$xmlStr .= '</authors>';
header("Content-Type: text/xml");
echo $xmlStr;
?>
A: 

You might want to synchronize the AJAX calls. Like having a few seconds delay after the key up event and then make the AJAX call. Setting asynchronous = true can also help.

rubayeet
A: 

you can abort the ajax call by calling the abort method: XmlHttpRequest.abort() before making the new request

andho