Use ajax to get json data from a php file - php

Right Im using php to generate a json file
<?PHP
header('Content-type: application/json');
include 'includes/db/connect.php';
$category = $_REQUEST['catname'];
$sql = "SELECT `CDID`, `CDTitle`, `CDYear`, `pubID`, `CDPrice` FROM `tiptop_cd` INNER JOIN tiptop_category ON tiptop_cd.catID=tiptop_category.catID WHERE catDesc = '{$category}'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
while($row = mysqli_fetch_array($result)){
$returned[] = $row;
}
echo json_encode($returned);
?>
and I want my php page to use a select box that gets the categories from the database
<?php
$result = mysqli_query($con,"SELECT * FROM tiptop_category");
// echo "<table>";
echo "<select id=\"catname\">";
while($row = mysqli_fetch_array($result))
{
?>
<option name="<?=$row['catDesc']?>"><?=$row['catDesc']?></option>
<?php
}
echo "</select>";
?>
now im trying to use this ajax to output my data
<script type="text/javascript">
var catname = "Classical";
$.ajax({
type: "GET",
url: "./json.php?catname=" + catname,
accepts: "json",
dataType: "json",
success: function(data, status, jqXHR){
someFunction(data);
},
error: function(jqXHR, status, HTTPerror){
alert(HTTPerror);
}
});
function someFunction(data){
console.log(data);
var list = "<ul>";
for (var i = 0; i < data.length; i++) {
list += "<li><ul>";
for (var j = 0; j < data[i].length; j++) {
list += "<li>" + data[i][j] + "</li>";
};
list += "</ul></li>";
};
list += "</ul>";
$('#wrapper').append(list);
}
</script>
<div id="wrapper">
</div>
but all i get is an empty bulleted list

From how the db query looks like, you should get a list of associative arrays, which are encoded as objects:
var list = "<ul>";
for (var i = 0; i < data.length; i++) {
list += "<li><ul>";
for(var key in data[i])
if(data[i].hasOwnProperty(key))
list += "<li>" + data[i][key] + "</li>";
list += "</ul></li>";
};
list += "</ul>";

Related

PHP and Ajax pagination. Why GET method always returns empty value?

I'm trying to add pagination, even though the code it seems correct, the page displays only the first 10 results (10 results i want per page). As you can see below, the problem seems to be created in the $_GET method.
Here is the ajax:
function displayAllTopics() {
$.ajax({
url: "requests.php",
type: "GET",
data: {
keyPagination: "displayAllTopics"
},
dataType: "json",
success: function(response) {
$("#topicArea").append(response.response_message);
$("#pagination").append(response.pagination);
}
});
}
Here is the requests.php file:
if(isset($_GET['keyPagination'])) {
if($_GET['keyPagination'] == "displayAllTopics") {
$sql = "SELECT * FROM travel";
$result = mysqli_query($conn, $sql);
$count_topics = mysqli_num_rows($result);
if($count_topics < 1) {
exit('There are no topics yet.');
}
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page = 1;
}
//results per page
$results_per_page = 10;
//number of pages
$offset = ($page-1) * $results_per_page;
$number_of_pages = ceil($count_topics / $results_per_page);
$sql_pagination = "SELECT * FROM travel LIMIT $offset, $results_per_page";
$results_pagination = mysqli_query($conn, $sql_pagination);
$response_message = "";
$pagination = "";
while($row = mysqli_fetch_assoc($results_pagination)) {
$user_id = $row['user_id'];
$travel_subject_id = $row['travel_subject_id'];
$travel_subject_date = $row['travel_subject_date'];
$travel_title = $row['travel_subject_title'];
$travel_body = $row['travel_subject_body'];
$travel_comments_count = $row['travel_comments_count'];
$travel_views = $row['travel_subject_views'];
$travel_subject_date_format = date('j M y H:i', strtotime($travel_subject_date));
$sql_user = "SELECT * FROM forum_users WHERE user_id='$user_id'";
$result_user = mysqli_query($conn, $sql_user);
if($row_user = mysqli_fetch_assoc($result_user)) {
$username = $row_user['username'];
$response_message .= "<tr>
<td><a href='travel_subject.php?id=".$travel_subject_id."' onclick='countview(".$travel_subject_id.");'><img src='topic.png' class='img_first'>$travel_title</a></td>
<td><img src='comment.png' class='img_second'><p>$travel_comments_count</p></td>
<td><a href='profile_user.php?id=".$user_id."'><img src='avatar.png' class='img_third'>$username</a></td>
<td><p><img src='views.png' class='img_four'>$travel_views</p></td>
<td><p>$travel_subject_date_format</p></td>
</tr>";
}
}
for ($i = 1; $i <= $number_of_pages; $i++) {
$pagination .= "<a href='forum_index.php?page=".$i."&limit=".$offset."'>$i</a>";
}
$data = array('response_message' => $response_message, 'pagination' => $pagination);
echo json_encode($data);
exit();
}
}
Note: Variable $page is always 1, so it seems that cannot set the $_GET['page'] and as a result from that, the page below displays always the first 10 results. Why is that?
and here is the php file, that i want to display the results:
<div class='display-subjects'>
<table class='display-subjects-table' cols='5'>
<tbody id="topicArea">
</tbody>
</table>
</div>
<div id='pagination'>
<?php
if(isset($_GET['page'])) {
$page = $_GET['page'];
}
else {
$page = 1;
}
?>
</div>
Where is the wrong part? Thanks in advance.
displayAllTopics() needs to take the page number as a parameter, and then pass it in the data option.
function displayAllTopics(pageNum) {
$.ajax({
url: "requests.php",
type: "GET",
data: {
keyPagination: "displayAllTopics",
page: pageNum
},
dataType: "json",
success: function(response) {
$("#topicArea").append(response.response_message);
$("#pagination").append(response.pagination);
}
});
}

Using database data to populate a graph

So I currently have graphs with have static data from JQ, I'm attempting to get the data from a DB using PHP. I've began the logic but struggling to move forward, Any ideas would be appreciated.. So far the graph outputs blank, only works when I use static data.
Used 0 in the output array as a test
PHP<?php
$userID = $_SESSION["userid"];
$days = array();
$query = "SELECT timeSpent
FROM gymTime
WHERE userid = '$userID'";
$result = mysqli_query($conn, $query);
$i=0;
while($row = $result->fetch_assoc()) {
$days[$i] = $row["timeSpent"];
$i++;
}
?
JQ <script>
// in php you simply need to create the two arrays and teh functionality will work
// monthly set to minutes
var myTimeMon = ;
var myMonths = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
// weekly data in mins
var myTimeWeek = [<?php echo $days[0]; ?>];
var myDays= ["Mon","Tue","Wed","Thur","Fri","Sat","Sun"];
// default values to be displayed when the page loads
var myLabels = myDays;
var mydata = myTimeWeek;
// store value of radiobutton
var currentValue = "m"
var displayData=[];
function contoMins(){
// change the values of the array
for(i=0; i<mydata.length; i++){
mydata[i]=mydata[i]*60;
}
destroyChart();
}
// destroy the chart so that it does not load on top of itself
function destroyChart(){
window.myBar.destroy();
buildChart();
}
function buildChart(){
displayData = mydata;
var barChartData = {
labels : myLabels,
//barValueSpacing : 25,
//barStrokeWidth : 40,
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: displayData
}
]
}
var ctx = document.getElementById("canvas").getContext("2d");
window.myBar = new Chart(ctx).Bar(barChartData, {
barValueSpacing : 10,
});
}
buildChart();
//sendData();
</script>
DB Structure
http://prntscr.com/avdg9r
Webpage
http://prntscr.com/avdgeq
This always sets $i equal to 0.
while($row = $result->fetch_assoc()) {
$i=0;
$days[$i] = $row["timeSpent"];
$i++;
}
Move $i = 0 outside the while loop.
$i=0;
while($row = $result->fetch_assoc()) {
$days[$i] = $row["timeSpent"];
$i++;
}
Also, loop through your $days array.
var myTimeWeek = [<?php echo $days[0]; ?>];
will only display the first element in $days. You need to loop through the array.
var myTimeWeek = [
<?php
$i = 0;
$total = 0;
foreach ($days as $day)
{
if ($i > 0) echo ', ';
echo '"' . $day . '"';
$total = $total + $day;
$i++;
}
?>
]
Move your $i outside the loop-block, otherwise the $i will be 0 for each iteration
$i=0;
while($row = $result->fetch_assoc()) {
$days[$i] = $row["timeSpent"];
$i++;
}

append result arrays in php codeigniter using ajax

The below is the json result I got in the console. But, appending it to my dropdown, shows only Physics,Chemistry and test subject. How to get Biology also.
[
[
{"id":"1","subject_name":"Physics"},
{"id":"2","subject_name":"Chemistry"},
{"id":"9","subject_name":"test subject"}
],
[
{"id":"7","subject_name":"Biology"}
]
]
Below is my ajax code
$.ajax({
type: 'POST',
dataType:"json",
// url:'<?php echo base_url()."SchoolAdmin/delete_electricUsage";?>',
url: '<?php echo base_url('SchoolAdmin/getclass_id'); ?>',
data: { class_std : class_std},
success: function (result) {
var listItems= "";
listItems+= "<option value='" + 'select' + "'>" +'Select' + "</option>";
for (var i = 0; i < result[0].length; i++){
listItems+= "<option value='" + result[0][i].id+ "'>" + result[0][i].subject_name + "</option>";
}
$("#subject").html(listItems);
}
});
Below is my controller function,
public function getclass_id()
{
$school_id = $this->session->userdata('school_id');
$sess_id = $this->session->userdata('userid');
$user_id = $this->session->userdata('user_id');
if(($sess_id))
{
$class_id=$this->security->xss_clean($this->input->post('class_std'));
$this->load->model('School_Model');
$cid=$this->School_Model->getclass_id($class_id,$school_id);
foreach ($cid as $r)
{
$rr=$r->id;
$data[]=array_merge($this->School_Model->getSubject($rr,$school_id));
}
echo json_encode($data);
}
else
{
redirect('admin');
}
}
Here is my model,
public function getclass_id($class_id,$school_id)
{
return $this->db->select('id')->from('class_table')->where('standard',$class_id)->where('school_id',$school_id)->
get()->result();
//echo $this->db->last_query();
}
public function getSubject($cid,$school_id)
{
return $this->db->select('id,subject_name')->
from('subject')->where('school_id',$school_id)->
where('class_id',$cid)->get()->result_array();
}
Your result is an array of arrays. You need to loop everything!
Biology is in result[1], but you're only looping result[0]
You could do it manually, like this:
for (var i = 0; i < result[0].length; i++){
listItems+= "<option value='" + result[0][i].id+ "'>" + result[0][i].subject_name + "</option>";
}
for (var i = 0; i < result[1].length; i++){
listItems+= "<option value='" + result[1][i].id+ "'>" + result[1][i].subject_name + "</option>";
}
Or, in one go:
for (var j = 0; j < result.length; j++){
// loops through all result arrays;
for (var i = 0; i < result[j].length; i++){
// loops the `j`th result for entries;
listItems+= "<option value='" + result[j][i].id+ "'>" + result[j][i].subject_name + "</option>";
}
}

Option list showing undefined values on ajax output

this is my code to show values in list box.
$.ajax({
type: "POST",
data: queryvalue,
url: "inputaction.php",
success: function (data) {
switch (action) {
case "GetMake":
console.log(data);
var select = $("#promake");
select.empty();
for (var i = 0; i < data.length; i++)
{
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
break;
}
}
});
i get the result of lot of undefined values in select field. and i have attached an console result in image file, in console output is correct how to rectify this problem.
Console Output
Page Output
$type = mysqli_real_escape_string($conn, $_POST['type']);
$make = mysqli_real_escape_string($conn, $_POST['make']);
$query = "select * from assetmodel where typeid = '".$type."' AND makeid = '".$make."' ORDER by model ASC";
$result = RunQuery($query, $conn);
while($row = mysqli_fetch_array($result)){
$re = array(
'id' => $row['id'],
'model' => $row['model']
);
}
echo json_encode($re);
this is my action page
You have to use "JSON.parse":
var select = $("#promake");
select.empty();
var parse = JSON.parse(json);
for (var i = 0; i < parse.length; i++)
{
select.append('<option value="' + parse[i].id + '">' + parse[i].make + '</option>');
}
decode the json in success
success: function (data) {
var data = $.parseJSON(data);
switch (action) {
case "GetMake":
console.log(data);
var select = $("#promake");
select.empty();
for (var i = 0; i < data.length; i++)
{
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
break;
}
}
You have to specify the dataType as json
$.ajax({
type: "POST",
data: queryvalue,
url: "inputaction.php",
dataType: "json",
success: function (data) {
switch (action) {
and set the MIME type of your response to application/json before sending the data:
header('Content-Type: application/json');
echo json_encode($re);
Simple fix in client-side is as below. Just a condition check inside your loop.
for (var i = 0; i < data.length; i++)
{
if (typeof data[i].id != "undefined" && typeof data[i].make != "undefined" ) {
select.append('<option value="' + data[i].id + '">' + data[i].make + '</option>');
}
}
If you want to have clean data from DB itself, you have to repair your query. That will eliminate the root cause.

php json jquery and select box

I have this php code
$jsonArray = array();
$sql = "SELECT ID,CLIENT FROM PLD_SERVERS";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$jsonArray[] = array('id'=>$row['ID'],'client'=>$row['CLIENT']);
}
echo json_encode($jsonArray);
And this js
function autosearchLoadServers()
{
$.post("php/autosearch-load-servers.php",function(data){
var toAppend = "";
for(var i = 0; i < data.length; i++){
toAppend += '<option value = \"' + data[i].id + '\">' + data[i].client + '</option>';
}
$("#serverSelect").empty();
$("#serverSelect").html(toAppend);
});
}
The problem is that i get only undefined values. How can this be? The values are in the JSON, i checked using firebug in mozilla so there has to be something with the data variable but i can't understand what. I tried different ways and no results.
Try specifying the datatype in the post call like this:
$.post("php/autosearch-load-servers.php",function(data){
var toAppend = "";
for(var i = 0; i < data.length; i++){
toAppend += '<option value = \"' + data[i].id + '\">' + data[i].client + '</option>';
}
$("#serverSelect").empty();
$("#serverSelect").html(toAppend);
}, "json");

Categories