been trying to figure out how to echo a query result to a textbox in a div. I have a form (see below) and it does place the result in a textbox as I want but is not echoing back to the div (which is called ‘content’). I’ve updated the code for my HTML here after some edits:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
</head>
<body>
<form id="search" method="post" action="rating.php">Miles <input name="miles" id="miles" type="text" /> <input name="search1" id="search1" class="btnButton" value="Search" type="submit" /></form>
<div id="content"></div>
<script type="text/javasript" src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">// <![CDATA[
$(document).ready(function(){
//jquery click event
$("#search").on("submit", function(e){
//disable default form submit postpage
e.preventDefault();
//make ajax call to the search.php parsing the search textbox value as query string
$.get("rating.php?miles="+$("#miles").val(), function(result){
//Result will be dumped in the div
$("#content").html(result);
});
});
});
// ]]></script>
</body>
</html>
The value of miles is now passed to rating.php where I want it to do a query and then format the result in a textbox format that is displayed in the div:
<?php
$hostname = 'somehost.com';
$username = 'ratetable';
$password = 'mypassword';
$miles = (int) $_POST['miles'];
try
{
$db = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
foreach($db->query("SELECT * FROM rates WHERE mileage<={$miles} ORDER BY mileage DESC LIMIT 1") as $row) {
$result= "<input type='text' name='answer' value='" . $row['ratepermile'] . "'>'";
echo $result;
}
}
catch (PDOException $e) {
echo $e->getMessage();
throw($e);
}
?>
The result is formatted the way I want, except that it is not being echoed back to the script and placed where the result should be. Is there a way I can use div tags or otherwise ensure it’s going to a specific div?
Thank you for looking.
First thing comes to mind: you’re not including the jQuery library anywhere in the example.
Also, notice the comma on the following line should be a dot:
If that’s not the problem but just the result of hasty copy / pasting, are sure that your $.get() request is giving you any output at all?
You probably also want to change the following:
to something like:
because the reference of #search is pointing to your form-tag rather than to a button