Reputation: 491
I have a form in an html file which sends data to a php file. That php file selects from the database, transforms the results into a json file and sends it back to the html file.
I would like to know how can I get the json from the php; I do get the reply (from the network tab in the inspection menu), but I don't know how to get it (to echo/alert/make a chart with it). Thanks in advance!
This is my code to send the data:
<script type="text/javascript">
$( function() {
$( ".datepicker" ).datepicker({
minDate: new Date(2015, 8 - 1, 25),
maxDate: "0"
});
});
$(function () {
// On form's submit, takes both input's values...
$('form').on('submit', function (e) {
var from = $("#from").val();
var to = $("#to").val();
// ...to compare them and displays an error if "to" is smaller than "from"
if(Date.parse(from) > Date.parse(to)){
alert("Invalid Date Range");
}
else{
e.preventDefault();
$.ajax({
type: 'post',
url: 'classes/Select.php',
data: $('form').serialize(),
success: function () {
alert('data sent');
}
});
}
});
});
</script>
And this is the php part that makes the json (left out all the mysql part and such):
while ($arr = $query->fetch(PDO::FETCH_ASSOC)) {
echo json_encode($arr);
Upvotes: 0
Views: 71
Reputation: 16122
Since you are using a loop in your php, create an array that will hold the results, when the loop finishes echo the results with json_encode
;
$results = [];
while ($arr = $query->fetch(PDO::FETCH_ASSOC)) {
$results[] = $arr;
}
echo json_encode($results);
Then in your javascript
$.ajax({
type: 'post',
url: 'classes/Select.php',
data: $('form').serialize(),
success: function(data) {
var results = JSON.parse(data); // convert the results to json
console.log(results);
}
});
Upvotes: 1
Reputation: 309
if you get a JSON string use json_decode($json) and you get the value you want:
$json = '{"key-example": 12345}';
$obj = json_decode($json);
print $obj->{'key-example'}; // 12345
Upvotes: 1
Reputation: 12355
In your javascript ajax call code, you probably have a success: key. Try:
success: function(data) { console.log(data); }
Upvotes: 1