JSON data not populating bootstrap table properly - javascript

Been trying to get a work around for this for hours now, but I just can't get my bootstrap table to being populated in a correct way. Here is my HTML:
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css">
<link rel="stylesheet" href="https://v40.pingendo.com/assets/bootstrap/bootstrap-4.0.0-beta.1.css" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.css" type="text/css">
</head>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="sha384-vFJXuSJphROIrBnz7yo7oB41mKfc8JzQZiCq4NCceLEaO4IHwicKwpJf9c9IpFgh" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.11.1/bootstrap-table.js"></script>
<script src="client.js"></script>
<table class="table" id="maintable">
<thead>
<tr>
<th data-field="queue">#</th>
<th data-field="nation_name">Nation</th>
</tr>
</thead>
</table>
</body>
</html>
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
$con = mysqli_connect('localhost','root','','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db");
$sql = "SELECT queue, nation_name FROM nations WHERE queue IS NOT NULL ORDER BY queue ASC";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo json_encode($row);
}
} else {
echo "0 results";
}
mysqli_close($con);
?>
JS:
url = "ws://localhost:8080";
ws = new WebSocket(url);
// event emmited when connected
ws.onopen = function () {
console.log('websocket is connected ...');
// sending a send event to websocket server
ws.send('connected');
}
// event emmited when receiving message
ws.onmessage = function (ev) {
console.log(ev.data);
}
$.ajax({
type: 'POST',
url: 'getqueue.php',
data: {},
success: function(response) {
alert(response);
$(function () {
$('#maintable').bootstrapTable({
data: response
});
});
},
error: function() {
//something
}
})
The JSON data that is sent to the page from PHP looks exactly like this:
{"queue":"1","nation_name":"Afghanistan"}{"queue":"2","nation_name":"Sweden"}
But when the page is loaded this is the result:
Screenshot
Why is the JSON data not being populated the way I want it? Ie, two rows containing 'queue' and 'nation_name'

The issue is this code returning multiple JSON strings in one:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo json_encode($row);
}
}
Instead you need to build one JSON string as an array of rows, and return it:
if (mysqli_num_rows($result) > 0) {
$output = array();
while($row = mysqli_fetch_assoc($result)) {
$output[] = $row;
}
echo json_encode($output);
}

The fix to your next problem is that you are not using the bootstrap library correctly. You must set columns and tell it what fields to use or else it has no idea what to put where. Fix what #Matt S told you to do for the PHP side, then make my edits for the client side. (I'll make an edit in his answer that he can peer review if he wants). On top of setting the columns you can actually get rid of your ajax request entirely as bootstrapTable supports giving it a url directly.
$('#table').bootstrapTable({
url: 'getqueue.php',
columns: [{
field: 'queue',
title: '#'
}, {
field: 'nation_name',
title: 'Nation'
}]
});

Related

pass data from mysql to javascript

Is this the right way to retrieve data from mysql using jquery? The php side is working fine ($data gets printed onto the page) but jquery doesn't seem to be receiving the variable at all.
Besides that, is there a way to get the jquery function to run after the page AND after the google maps initMap() function has finished loading? Is it possible to include jquery code inside a standard javascript function?
admin.php
<?php
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
echo json_encode($data);
?><!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
What I've tried
js/admin.js
$(document).ready(function() {
$.ajax({
url: '../admin.php',
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
})
});
I received a "404 Not found" error in the console
The 404-Error indicates that you are using a wrong URL in your jQuery code to get the data. Try to enter not just the filename but the whole URL like https://example.com/admin.php for the url parameter.
Besides your problem getting the data via jQuery, what happens when you open admin.php directly in your browser? Are you getting the $data AND your HTML Code? If thats the case I would recommend you to wrap the whole PHP-Code inside an if-statement:
if($_SERVER['REQUEST_METHOD'] === 'POST'){
header('Content-Type: application/json');
require 'private/database.php';
$sql = "SELECT * FROM latlng";
$result = mysqli_query($conn, $sql);
$data = array();
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
}
die(json_encode($data));
}
else{ ?>
<!DOCTYPE html>
<html>
<head>
<link type="text/css" rel="stylesheet" href="css/admin.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="js/admin.js"></script>
<script type="text/javascript" src="js/maps.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?key=(mykey)&callback=initMap&libraries=places&v=weekly"
></script>
</head>
<body>
<div id="map"></div><br>
</body>
</html>
<? } ?>
Now, if its a POST-Request like from your js, the PHP will return the data as JSON. Also the right header will be set. If its not a POST-Request the PHP will return your HTML.
To your other question: Yes, it is possible to use jQuery in a normal JavaScript function.

Sending Post request by ajax to PHP page from select box

I've trying to set up a Question/Answer system and I've encountered with a couple of errors while setting up dependent select boxes
I wanna send the information of masters select box (Maters'id) to PHP file (DB.PHP) to handle a group of actions.
HTML Page
<?php
require_once "DB.php";
require_once "functions.php";
require_once "stuQuestion.php";
if(! isset($_SESSION['student'])){
redirect("stulogin/login.php");
die;
}
$date = userGets($connection , "students_questions" , $_SESSION['students_id']);
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#masters').on('change',function() {
var mid = $('#masters').val();
$.ajax({
url: 'DB.php',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: 'mid=' + mid
}).done(function(user){
console.log(user);
user = JSON.parse(user);
$('#topics').empty();
user.forEach(function(topic) {
$('#topics').append('<option>' + topic.topic + '</option>')
})
})
})
})
</script>
</head>
<select class="form-control" id="masters" name="masters" >
<option selected disabled>Choose Master</option>
<?php
//id='".$master['id']."' value = '".$master['id']."'
foreach($date as $master)
{
echo "<option id='".$master['id']."' value = '".$master['id']."'> ".$master['master']."</option>";
}
?>
</select>
<select class="form-control" id="topics" name="topics">
</select>
DB.php
function connectToDB() {
try {
$connect = new PDO("mysql:host=127.0.0.1;dbname=university","root","");
$connect->exec("set character set utf8");
$connect->exec("set names utf8");
$connect->setAttribute(PDO::ATTR_ERRMODE , PDO::ERRMODE_EXCEPTION);
return $connect;
}
catch (PDOException $e)
{
die($e->getMessage());
} }
$connection = connectToDB();
if(isset($_POST['mid'])){
$statment = $connection->prepare("SELECT topic FROM students_questions
WHERE user_id = " . $_POST['mid']);
$statment->execute();
$user = $statment->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($user) ;
}
else
var_dump("No Request");
function userGets($conn , $table , $user_id = null) {
$statment = $conn->prepare("SELECT DISTINCT master FROM {$table} WHERE
user_id = :user_id");
$statment->bindParam("user_id" , $user_id );
$statment->execute();
$master = $statment->fetchAll(PDO::FETCH_ASSOC);
return $master ? $master : false;
}
When I log in and redirect to stuIndex.php (The page which contains select boxes)I will encounter with "No Request"! and after 3 days hunting around for probable correct answers, I couldn't solve it so far:(
Thanks in advance for any help you are able to provide.
PS: if someone needs more information, please tell me I will send the complete source code or sharing more information.
Too many jQuery and bootstrap libraries and they are HTTPS and HTTP versions from different CDNs
Syntax error in data :
No need for parsing the JSON since it is default
No error handling for the request. If you do not want error handling do this
$(function() {
$('#masters').on('change', function() {
var mid = this.value;
if (val) {
$.post('DB.php', {"mid": mid}, function(user) {
$('#topics').empty();
$.each(user,function(topic) {
$('#topics').append('<option>' + topic.topic + '</option>')
})
})
}
})
})
using
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/popper.min.js"></script>

How do I create a C3 Chart Line Graph from JSON data?

I need help for a school project. I have been able to pull data from a mySQL database into an array and encoded into JSON, which displays fine. Now, I need help with passing the JSON data to C3 to produce a chart (if possible on the same page).
What I've done so far:
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
$data[] = $row;
}
echo json_encode( $data );
You need to create two separate array, one for your data and one for dates that you want to show on x-axis and then pass that array to java script.
here is full working example
<?php
$conn = mysqli_connect("localhost", "root", "", "test_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$strQuery = "SELECT production_date,oil FROM production WHERE well = '$h_well' AND production_date BETWEEN '$h_start' AND '$h_end' ORDER BY production_date ASC";
$result = mysqli_query($conn, $strQuery);
// Print out rows
$valuesArray = array();
$datesArray = array();
$valuesArray[] = 'Oil';
$datesArray[] = 'x';
while ($row = $result->fetch_assoc()) {
$datesArray[] = $row['production_date'];
$valuesArray[] = $row['oil'];
}
?>
<html>
<head>
<title>C3 Liner example</title>
<link href="c3_scr/c3.css" rel="stylesheet" type="text/css" />
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="c3_scr/c3.js"></script><!-- load jquery -->
</head>
<body>
<div id="chart"></div>
<script>
var xAxisArr = <?php echo json_encode($datesArray); ?>;
var dataArr = <?php echo json_encode($valuesArray, JSON_NUMERIC_CHECK); ?>;
var chart = c3.generate({
bindto: '#chart',
data: {
x: 'x',
columns: [
xAxisArr,
dataArr
]
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
}
});
</script>
</body>
</html>

CanvasJs dynamic Data with PHP, mySQL

screen shoot
Hello i have obstacle for my chart from CanvasJs.
I just put simple code to get simple chart with parameter target and actual, i found error in dataPoints: i think the problem just wrong statements.
this my error code:
dataPoints: [
<?PHP $mkmi3= mysql_query("SELECT * FROM monthkpimontindv WHERE idKpiDetIndv='$q'");
While ($mkmi4= mysql_fetch_assoc($mkmi3))
{
echo "{ label: ".$mkmi4['period'].", y: ".$mkmi4['actual']." },\n";
}
?>
]
Here is how we can display MySQL data in CanvasJS, Try like this.
Here, Create a PHP service that returns data in JSON format. HTML page that does AJAX request to the server and fetches the data. After getting the data, it renders a Chart.
PHP Service to return JSON Data
<?php
header('Content-Type: application/json');
$con = mysqli_connect("127.0.0.1","user","password","canvasjssampledb");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM sales");
while($row = mysqli_fetch_array($result))
{
$point = array("label" => $row['product'] , "y" => $row['total_sales']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
}
mysqli_close($con);
?>
HTML Page to Fetch Data and render Chart
!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title></title>
<script src="jquery.js"></script>
<script src="canvasjs.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: result
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="width: 800px; height: 380px;"></div>
</body>
</html>
Note:: IE8- is supported in v1.3 and above.

"$.get" for retrieving information

I'm trying to get a simple javascript popup script going anytime the database is updated in real-time. I'm not sure as to what to do next, because I'm still a newbie with jQuery and ajax, but the following code is what I have right now:
PHP MySQL query page:
<?php
$con = mysqli_connect('localhost','root','root','mydb');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"mydb");
$sql = "SELECT * FROM incoming_calls";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
//$callArray = array('phonenumber' => $row['phone_number'], 'id' => $row['phone_login_id']);
if(!empty($row)) {
$number = $row['phone_number'];
}
}
$sql="SELECT Username, Password FROM tblUsers WHERE PhoneHome='$number' OR PhoneCell='$number' OR PhoneWork='$number'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$userArray = array("username" => $row['Username'], "password" => $row['Password']);
//echo json_encode($userArray);
}
echo json_encode($userArray);
mysqli_close($con);
?>
HTML page:
<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
<title>Phone calls</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
function getCall(){
$.get("phonecall.php", function(data){
var loginInfo = jQuery.parseJSON(data);
var user = loginInfo.username;
var pass = loginInfo.password;
$('#username').html(user);
$('#password').html(pass);
});
/*$.getJSON("phonecall.php", function(data){
for (var i=0, len=data.length; i < len; i++) {
$('#username').html(data);
}
});*/
}
setInterval(getCall,5000);
</script>
<div id="username"></div>
<div id="password"></div>
</body>
</html>
One of the problems I am having is that when there are 2 or more users with the same phone number for say like a house phone, depending on where the json_encode is, will either return the last entry in the table, or return nothing at all. If the json_encode is in the while loop, I can check the console, it says the information is being retrieved, but something must not be right with my "$.get" syntax to allow more than one entry to be displayed. Any ideas?
You're only ever saving one row of data:
while($row = mysqli_fetch_array($result)) {
$userArray = array("username" etc...
^^^^---here
If you have multiple rows of data, each row you fetch will overwrite the previous row in $userArray.
You probably want
$userArray[] = array("username" etc...
^^---- note these
so you're creating an array of results.
You'll also have to modify your JS code to accept an array of arrays, since right now you only handle one username/password.

Categories

Resources