How to fetch data using ajax call in php?

Click on the button to get related data using ajax call:

File name : index.php

<!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>

result.php

<?php

// Get value of clicked button
$button = $_GET['button'];

// Red wine table
$red = array('Chianti', 'Barolo', 'Pinot Noir');
$white = array('Chardonnay', 'Cava', 'Chablis');

// Combine red and white tables into one multidimensional table
$winetable = array(
"red" => $red,
"white" => $white,
);

// Finally depending on the button value, JSON encode our winetable and print it
if ($button == "red") {
print json_encode($red);
}
else if ($button == "white") {
print json_encode($white);
}
else {
print json_encode($winetable);
}

?>





Previous Next


Trending Tutorials




Review & Rating

0.0 / 5

0 Review

5
(0)

4
(0)

3
(0)

2
(0)

1
(0)

Write Review Here