OK, so I’ve installed jQuery on my GoDaddy hosting account. I need to display a result in a text box and have done my HTML, which gets a user input, a button click and a results area (div id=status). I want to simply put the result in a box without having to refresh the page. I’m trying this json thing and AJAX to accomplish this and I’m trying to figure out what is wrong with my attempt. Here is the HTML.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1 /DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<script language='JavaScript' type='text/javascript'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
</head>
<body>
<p>Miles <input name="miles" id="miles" type="text" /> <button type="button" name="getdata" id="getdata">Submit</button></p>
<p></p>
<div id="status">
</div>
<script type="text/javascript" language="javascript">
$('getdata').click(function(){
$.ajax({
url: 'process.php',
type:'POST',
dataType: 'json',
success: function(output_string){
$('#result_table').append(output_string);
}
));
});
</script>
</body>
</html>
and it should be sent to process.php file:
<?php
$hostname = 'myhost.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) {
$output_string .= '<input type='text' name='answer' value='" . $row['ratepermile'] . "'>';
}
}
echo json_encode($output_string);
catch (PDOException $e) {
echo $e->getMessage();
throw($e);
}
?>
I tried to use an example to construct this and nothing happens…not even the HTML form. What is wrong with this?
Thanks for having a look.
Your selector is wrong
$('getdata')should be$('#getdata'), you have to prefix the id with a#to select an element with its id. Also you have to pass the parameters to the post request