Reputation: 1058
I am trying to figure out how to get JSON results and show them in a template I have built.
I have a page that has checkboxes, when the check boxes are checked the script refines the search. So far I have a created a script that checks to see if a user has checked a box. A separate PHP script then runs a query on an SQL database - returning the results live.
I have so far managed to get this to return the results as JSON in the console and 'stringified' in the webpage.
How do I take the JSON results and show them neatly on the webpage? i.e
Name: 'name', Locale: 'locale'
Name: 'name', Locale: 'locale'
Name: 'name', Locale: 'locale'
This is my Ajax code at the moment:
var ajaxResult=[];
function updateEmployees(opts){
$.ajax({
type: "POST",
url: "search.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success:function(data) {
ajaxResult.push(data);
}
});
}
This is the javascript checkbox code:
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
console.log(ajaxResult)
var myJSON = JSON.stringify(ajaxResult);
document.getElementById("demo").innerHTML = myJSON;
});
updateEmployees();
Thanks for your help in advance. I've spent a couple of days trying to figure this out!
EDIT - PHP script I am using
<?php
$pdo = new PDO('mysql:host=localhost;dbname=myDB', '**', '**');
$select = 'SELECT name, locale, website';
$from = ' FROM theList';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("pub", $opts)){
$where .= " AND pub = 1";
}
if (in_array("bar", $opts)){
$where .= " AND bar = 1";
}
if (in_array("restaurant", $opts)){
$where .= " AND restaurant = 1";
}
if (in_array("club", $opts)){
$where .= " AND club = 1";
}
if (in_array("locale-a", $opts)){
$where .= " AND locale = 'south'";
}
if (in_array("locale-b", $opts)){
$where .= " AND locale = 'west'";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
Upvotes: 1
Views: 77
Reputation: 707
There are a couple of things going on here.
1. Your results set will grow every time a checkbox changes since you're pushing a new element to the results array. If you're fetching the full dataset every time, this is unnecessary.
2. AJAX performs asynchronously, your code is written with expectation that it's synchronous.
This...
console.log(ajaxResult)
var myJSON = JSON.stringify(ajaxResult);
document.getElementById("demo").innerHTML = myJSON;
});
updateEmployees();
...is expecting data that doesn't exist yet.
The process goes:
*user clicks checkbox*
submit selections to server to query database
wait for response
handle result when response received
However, the above code is already on step 4 before step 3 has completed. You need to tell the ajax call what to do when it's received the response:
// send selections to server
function updateEmployees(){
$.ajax({
type: "POST",
url: "search.php",
dataType : 'json',
cache: false,
// serialize checked boxes to a query string like "check1=on&check2=on"
data: $('input:checkbox').serialize(),
success: handleResults
});
}
// handle filtered results
function handleResults(data) {
// same as document.getElementById('demo').innerHTML
$('#demo').html(
JSON.stringify(data)
);
}
// add events to checkboxes
$('input:checkbox').change(updateEmployees);
Upvotes: 1
Reputation: 94
try to use stringify method with these params:
var myJSON = JSON.stringify(ajaxResult, null, 2);
Upvotes: 0