How do I pass multiple returned mysql rows through json to the below jquery script? With the code I have written so far I can’t get the jquery success callback function to execute when i pass 2 or more to it. How would I go about accomplishing this?
jQuery, Js code:
$("#projects").click(function() {
jQuery.ajax({ type: "POST", dataType: "JSON",
url: "<?=base_url()?>index.php/home/projectsSlider",
json: {returned: true}, success: function(data) {
if (data.returned === true) {
$("#content").fadeOut(150, function() {
$(this).replaceWith(projectsSlider(data.projectId, data.projectName, data.startDate, data.finishedDate, data.projectDesc, data.createdFor, data.contributors, data.screenshotURI, data.websiteURL), function() {
$(this).fadeIn(150);
});
});
}
}
});
});
Php code:
function projectsSlider() {
$query = $this->db->query("SELECT * FROM projects ORDER BY idprojects DESC");
foreach ($query->result() as $row) {
$projectId = $row->projectId;
$projectName = $row->projectName;
$startDate = $row->startDate;
$finishedDate = $row->finishedDate;
$createdFor = $row->createdFor;
$contributors = $row->contributors;
$projectDesc = $row->projectDesc;
echo json_encode(array('returned' => true,
'projectId' => $projectId,
'projectName' => $projectName,
'startDate' => $startDate,
'finishedDate' => $finishedDate,
'projectDesc' => $projectDesc,
'createdFor' => $createdFor,
'contributors' => $contributors));
}
$query1 = $this->db->query("SELECT * FROM screenshots s WHERE s.projectId = '{$projectId}' ORDER BY s.idscreenshot DESC");
foreach ($query1->result() as $row2) {
$screenshotURI = $row2->screenshotURI;
$websiteURL = $row->websiteURL;
echo json_encode(array('screenshotURI' => $screenshotURI,'websiteURL' => $websiteURL));
}
}
You are echoing two different JSON strings. That will not a be a valid JSON. Hence (although I have not tested it), the ajax call will fail.
I suggest you merge the two JSONs and return just one valid JSON from the “projectsSlider()” function.
Like so:
Then access each of the rowsets from within the ajax callback method by using “data.Projects” and “data.Screenshots”.
Like so: