Log in

View Full Version : JavaScript only AJAX Search Function



BenRacicot
05-31-2013, 10:36 PM
Hello! Thanks for taking the time to read about my issue. I'm basically brand new to JS but I have been working on this script all week and can't get it...

Please help me understand why my text input does not POST its value to var sr -> send() -> PHP file. The PHP file has been tested and gathers/echoes JSON data perfectly from any search input with a post action. I cannot get this JS function to send my searchquery data to my parser.php. I'm sure its a basic issue.


function ajax_call(){
var results = document.getElementById("results");
var sr = document.getElementById("searchquery").value;
var params = "searchquery="+sr;

var hr = new XMLHttpRequest();
hr.open("POST", "parser.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.results == 200) {
var return_data = hr.responseText;
document.getElementById("results").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the results div
hr.send(params);
document.getElementById("results").innerHTML = "processing...";
}

The HTML:


<form>
<input name="searchquery" type="text" id="searchquery" size="40" maxlength="" placeholder="<?php if (isset($_POST['searchquery'])){echo $_POST['searchquery'];} ?>" size=50 speech x-webkit-speech>
<input name="button" type="submit" id="searchbut" onClick="javascript:ajax_call();">
</form>

The PHP



$searchquery = $_POST['searchquery'];

mainquery($searchquery);

function mainquery($query){

$PDO = new PDO("mysql:host=localhost;dbname=searchdb", "root", "");

$sql = 'SELECT *
FROM results
WHERE title LIKE :searchquery
ORDER BY date DESC';

$datas = $PDO->prepare($sql);
$datas->execute(array(':searchquery' => $query . '%'));

$resultset = $datas->fetchALL(PDO::FETCH_OBJ);
$results = json_encode($resultset);
// return $results;
echo $results;
}

jscheuer1
06-01-2013, 02:01 AM
I think you might need more headers, maybe not. But hr.results is undefined:



hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.results == 200) {
var return_data = hr.responseText;
document.getElementById("results").innerHTML = return_data;
}
}

What you want there would be:


hr.status

There could also be other problems.

Generally, for such a complex AJAX operation it's best to use a javascript library like jQuery which takes care of both of those issues for you (ensuring the correct headers, and getting the syntax right when testing for a successful request), and many more.

But if you want to do it "old school", that's certainly possible. See:

http://www.openjs.com/articles/ajax_xmlhttp_using_post.php