Dispose submit button with ajax-jquery and php
Dan Costinel’s Question:
I have the following code, for learning porpose. In short, I want to grab some data from a database, with the help of a drop-down menu. My problem is that now I’m using a submit button to make the submit action. And the improvement that I want, is to get rid of the submit button, and grab the infos when the drop-down changes.
I’ve tried to make a function for the code between line 1 and 12, and call it with: <body onload="process()">
, but it’s not working. Then I tried to put the onchange="this.form.submit()"
attribute to the <select>
element, but this doesn’t work also, because it sends the data to process.php like any normal submission when not using ajax.
Anyone know any fix? Thank you!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body onload="viewdata()">
<form action="process.php" method="post" id="form">
<select name="select" id="select">
<option value="">Choose</option>
<option value="1">supervizor</option>
<option value="2">sef locatie</option>
<option value="3">muncitor</option>
<option value="0">toti</option>
</select><br/>
<input type="submit" value="Go"/>
</form>
<script type="text/javascript">
var frm = $('#form'); // **LINE 1**
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('#show').html(data);
}
});
ev.preventDefault();
}); // **LINE 12**
function viewdata(){
$.ajax({
type: "GET",
url: "process.php"
}).done(function( data ) {
$('#show').html(data);
});
}
</script>
<br/><br/>
<div id="show"></div>
</body>
</html>
You need to bind your processing on the change event of your drop down box.
$("#select").on("change", function(ev) {
// Your ajax processing
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('#show').html(data);
}
});
ev.preventDefault();
});