Reputation: 333
I have a PHP script, which connects to the DB, does a simple select and returns a single number back. The script works fine, I can test it by adding
action="search_ODtime.php" method="POST"
to my form. But the whole thing does not work. The whole page is getting refreshed and I am getting nothing back. I killed the whole day trying to figure out what is wrong here. Does anyone have any idea?
My html file:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#time_search').bind('submit', function() {
var origin = $('#origin').val();
var destination = $('#destination').val();
alert(origin);
$.ajax({
type: "POST",
url: "search_ODtime.php",
data: 'origin=' + origin + '&destination=' + destination,
success: function(data) {
$('#search_results').html(data);
}
});
});
});
</script>
</head>
<fieldset style="font-size:11pt; opacity: 1; color: white;">
<form id="time_search">
Orinig:
<input name="origin" id="origin" type="number" value="1" min="1" max="97">
<br>
Destination:
<input name="destination" id="destination" type="number" value="1" min="1" max="97">
<br>
<input type="submit" value="Get travel time" name="submit" id="submit" style="border-radius: 5px; display: block; margin: 10px auto 10px 0;">
</form>
Travel time:
<div id="search_results">
</div>
</fieldset>
</body>
</html>
Upvotes: 2
Views: 31
Reputation: 805
Some things to mention:
First:
When submitting a form via AJAX you need to prevent the browser from its default submitting behaviour and thus from refreshing the page.
('#time_search').bind('submit',function(e) {
e.preventDefault();
Second:
Try sending your data in the JSON format eg. {"origin": origin, "destination": destination}
Upvotes: 0
Reputation: 23379
What's happening is your form is getting submitted. You can either: a) remove the form entirely and change the submit button to a regular button, then bind your event to the button instead of the form, or b) prevent the form from submitting.
jQuery passes the event object to every event handler. The event object has a method called preventDefault()
which prevents, well, the default action, whether it's submitting a form or linking to a page or whatever.
You need to pass the event into the function by adding a variable for it, and then call it's preventDefault()
method to prevent the form from submitting and your page being refreshed.
$('#time_search').bind('submit',function(event) {
event.preventDefault();
var origin = $('#origin').val();
var destination = $('#destination').val();
alert (origin);
$.ajax({
type:"POST",
url:"search_ODtime.php",
data: 'origin='+origin+'&destination='+destination,
success: function(data){ $('#search_results').html(data); }
});
});
Upvotes: 1