<!DOCTYPE html>
<html>
<head>
<title>Ajax call with JSON Response</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$(':submit').on('click', function() {
var button = $(this).val();
$.ajax({ // ajax call starts
url: 'result.php', // JQuery loads serverside.php
data: 'button=' + $(this).val(), // Send value of the clicked button
dataType: 'json',
})
.done(function(data) {
$('#show_data').html(''); //
if (button == 'all') { //
for (var i in data.red) {
$('#wines').append('Red wine: ' + data.red[i] + '<br/>');
}
for (var i in data.white) {
$('#wines').append('White wine: ' + data.white[i] + '<br/>');
}
}
else if (button == 'red') {
for (var i in data) {
$('#wines').append('Red wine: ' + data[i] + '<br/>');
}
}
else if (button == 'white') {
for (var i in data) {
$('#wines').append('White wine: ' + data[i] + '<br/>');
}
}
});
/* .fail(function() {
alert("Sorry! Data not fetched.")
})
*/
return false; // keeps the page from not refreshing
});
});
</script>
</head>
<body>
<form method="post" action="">
<button value="all" type="submit">Get All!</button>
<button value="red" type="submit">Get Red!</button>
<button value="white" type="submit">Get White!</button>
</form>
<div id="show_data">
</div>
</body>
</html>
Trending Tutorials