Can anybody help me with this problem ? I am trying to display the array that I retrieve from PHP in HTML / Java form.
<?php
header("Content-Type: application/json; charset=UTF-8");
require('routeros_api.class.php');
$API = new routeros_api();
$API->debug = true;
$API->connect('1.1.1.1', 'admin', '123');
$API->write('/ip/firewall/filter/print');
$READ = $API->read(false);
$ARRAY = $API->parse_response($READ);
echo json_encode ($ARRAY);
$API->disconnect();
?>
output
[{ ".id":"*6",
"chain":"unused-hs-chain",
"action":"passthrough",
"log":"false",
"disabled":"true"},
{ ".id":"*5",
"chain":"input",
"action":"accept",
"log":"false",
"disabled":"true"},
{ ".id":"*2A",
"chain":"unused-hs-chain",
"action":"drop",
"log":"false",
"disabled":"true"}]
displayjava.html
<tbody id="myTable">
<script>
var xmlhttp = new XMLHttpRequest();
var url = "testdata2.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("get", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var outp = "<tbody>";
for(i = 0; i < arr.length; i++) {
outp += "<tr>" +
"<td>" + arr[i].id + "</td>" +
"<td>" + arr[i].chain + "</td>" +
"<td>" + arr[i].action + "</td>" +
"<td>" + arr[i].log + "</td>" +
"<td>" + arr[i].disabled + "</td>" +
"</tr>";
}
outp += "</tbody>"
document.getElementById("myTable").innerHTML = outp;
}
</script>
</tbody>
By the way I am displaying the data in a table form format in html file
At least two problems there:
You're outputting invalid JSON:
[
{
"Name": "*6",
"City": "unused-hs-chain",
"City2": "unused-hs-chain",
"City3": "unused-hs- chain",
"Country": "passthrough"
}{
"Name": "*5",
"City": "input",
"City2": "input",
"City3": "input",
"Country": "accept"
}{
"Name": "*2A",
"City": "unused-hs-chain",
"City2": "unused-hs-ch
You need commas between those objects (after each } and before the next {).
Don't generate the JSON manually. Instead, just build up an array of what you want to send back in PHP, then use json_encode so it handles the details for you.
You're using properties on the objects in the array that aren't in the JSON. Your code usese arr[i].id, arr[i].chain, and arr[i].action, but the objects in your JSON don't have id, chain, or action properties, they have Name, City, City2, and so on.
Why not just use json_encode() instead of building it manually.
$output = array();
foreach($ARRAY as $rs) {
$output[] = array(
'Name' => $rs['id'],
'City' => $rs['chain'],
'City2' => $rs['chain'],
'City3' => $rs['chain'],
'Country' => $rs['action'],
);
}
echo json_encode($output);
exit;
Your JSON string response right now has missing {}, commas.
Don't build manually use json_encode() function ,
Above code is
<?php
header("Content-Type: application/json; charset=UTF-8");
require('routeros_api.class.php');
$API = new routeros_api();
$API->debug = true;
$API->connect('1.1.1.1', 'admin', '123');
$API->write('/ip/firewall/filter/print');
$READ = $API->read(false);
$ARRAY = $API->parse_response($READ);
$outp = array();
foreach($ARRAY as $rs) {
$outp[] = array(
'Name' => $rs['id'],
'City' => $rs['chain'],
'City2' => $rs['chain'],
'City3' => $rs['chain'],
'Country' => $rs['action'],
);
}
$API->disconnect();
echo json_encode($outp);
?>
Related
I am trying to populate a HTML table using JQUERY, AJAX and PHP code. When I run my code, my table is displayed but it is filled with 'undefined'.
I have three pieces of code. Here is my HTML and jQuery:
var integer = $("#transfers_in").attr("name");
alert("integer: " + integer);
$.ajax('includes/test.php', {
type: 'POST', // http method
data: {
dataType: 'json',
myData: integer
}, // data to submit
success: function(response) {
var len = response.length;
for (var i = 0; i < len; i++) {
var name = response[i].name;
var amount = response[i].amount;
var tr_str = "<tr>" +
"<td align='center'>" + (i + 1) + "</td>" +
"<td align='center'>" + name + "</td>" +
"<td align='center'>" + amount + "</td>" +
"</tr>";
$("#money_in").append(tr_str);
}
}
});
<table id="money_in">
<tr>
<th>Name</th>
<th>Amount(Million £)</th>
</tr>
</table>
and here is my PHP Code:
<?php
if (isset($_POST['myData'])) {
$integer = $_POST['myData'];
if ($integer === "1"){
include 'db_connection.php';
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$return_arr = array();
$query = "SELECT * FROM `money_in_19_20`";
$result = mysqli_query($conn,$query);
while($row = mysqli_fetch_array($result)){
$name = $row['Name'];
$amount = $row['Amount'];
$return_arr[] = array("Name" => $name,
"Amount" => $Amount);
}
// Encoding array in JSON format
echo json_encode($return_arr);
}
}
The Json data is being received in the format of
{"Name":"Hazard","Amount":"103000000"}
You are returning object as Name,Amount and checking as name,amount
var name = response[i].name;
var amount = response[i].amount;
it should be
var name = response[i].Name;
var amount = response[i].Amount;
Hello there am trying to get the data from database using ajax posts but i didn't get any data properly. first column data is splinting in another columns(Member names are coming in image field and info field). Image also shared please check that. And also datatables are not working while fetching the data using Ajax. Help me out from this problem...
Thanks & Regards
<body>
<label>Party</label>
<select id='partydropdown' name='partydropdown' onchange="partyFunction();">
<option>--select a party--</option>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row["Id"];?>">
<?php echo $row["PartyName"];?>
</option>
<?php }}?>
</select>
<div id="showhide"></div>
</body>
<script type="text/javascript">
function partyFunction(){
debugger;
$("#showhide").empty();
$("#showhide").html('');
$("#showhide").append("<table class='table table-bordered text-center table-responsive' border='1px' id='example'>"+
"<tr>"+
"<th>PartyMemberName</th>"+
"<th>Image</th>"+
"<th>Info</th>"+
"</tr>"+
"<tbody id='partyBody'>"+
"</tbody>"+
"</table>"
);
$postdata = {};
$postdata["Id"]=$("#partydropdown").val();
console.log($("#partydropdown").val());
$.post('test_data.php',$postdata,function (data) {
debugger;
console.log(data);
console.log(data["data"][0].candiateName);
$("#partyBody").empty();
$("#partyBody").html('');
console.log(data["data"]);
console.log(data["data"].length);
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
$("#partyBody").append("<tr>"+
"<td id='resdata"+i+"'></td>"+
"<td id='resdata1"+i+"' ></td>"+
"<td id='resdata2"+i+"'></td>"+
"</tr>");
$("#resdata"+i).text(data["data"][i].candiateName);
$("#resdata1"+i).append("<img id='photo"+i+"'>");
$("#resdata2"+i).text(data["data"][i].Background);
$("#photo"+i).attr('src', 'http://aptsvotes.com/wp-content/themes/apts2019/img'+data["data"][i].Photo );
}
}
});
};
</script>
here is the test_data.php code
<?php
include_once "conn.php";
include_once "voterdbclass.php";
session_start();
$tbl_name2="Parties";
$dbObj = new Database1();
$values1 = array("all");
$querys = "SELECT c1.CandidateName,c1.Photo,c1.Background ,c1.Type FROM aptsv1_votes.Parties p1 LEFT JOIN aptsv1_votes.Candidates c1 ON c1.CurrentPartyId = p1.Id where p1.Id ='" . $_POST['Id'] . "' limit 21";
$res = $dbObj->SelectRecord($tbl_name2,$values1,"","$querys");
$data=array();
$i=0;
while ($rs = $res->fetch_array(MYSQLI_ASSOC)) {
$data[$i]['candiateName']=$rs['CandidateName'];
$data[$i]['Photo']=$rs['Photo'];
$data[$i]['Background']=$rs['Background'];
$i++;
}
$json_array= array(
"data" =>$data
);
echo json_encode($json_array);
?>
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
var imge = data["data"][i].Photo;
var name = data["data"][i].candiateName;
var bg = data["data"][i].Background;
$("#partyBody").append("<tr>"+
"<td id='resdata" + i + "'>" + name+"</td>"+
"<td id='resdata1" + i + "' ><img id= 'photo" + i + "' src='http://aptsvotes.com/wp-content/themes/apts2019/img'" + imge+"></td>"+
"<td id='resdata2" + i + "'>" + bg+"</td>"+
"</tr>");
}
}
You have to parse JSON data into the first script. While ajax result you posting with json_encode, I found missing
var data = $.parseJSON(data);
console.log(data["data"].length);
into code
$.post('test_data.php',$postdata,function (data) {
// debugger;
console.log(data);
var data = $.parseJSON(data); // Add this line in your code and verify
console.log(data["data"].length);
Thank you!
I'm trying to make jquery autocomplete input field with source from database, and the data is stored in json. I stored all data I got in one variable, it's look like this :
and when I set source to be value of that sinput field, I got the whole sentece (which is expect from my example)..but now I know to have three words (first - skijanje, second - vodopoad, third - more) so to have three options in my autocomplete. Here is my code for getting data using php:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($output);
Here is js code for reading that data :
<script>
var obj, dbParam, xmlhttp,x , txt = "";
var i = 0;
obj = { "table":"tourplan" };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "All data: " + this.responseText;
var myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x].title +" ";
}
document.getElementById("demo2").value = txt;
//document.getElementById("demo2").innerHTML = "Only one field: " + myObj[1].title;
}
}
xmlhttp.open("GET", "tourTitle.php?x=" + dbParam, true);
xmlhttp.send();
</script>
<p id="demo"></p>
<input type="text" id="demo2" value="">
for document.getElementByID('demo').innerHTML = "All data: " + this.responseText; I got this:
All data: [{"title":"skijanje","type":"zima"},{"title":"vodopad","type":"jesen - proljece - ljeto"},{"title":"more","type":"ljeto"}]
and here is for making autocomplete:
<script>
$( function() {
var otherPlaces = [
txt
];
$("#search-loged").autocomplete({
source: txt
});
});
</script>
ANy idea for correct that? thanks
Don't use pure ajax, try something like this:
jQuery Ajax
$( function() {
$("#search-loged").autocomplete({
source: 'tourTitle.php',
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
});
HTML
<p id="demo"></p>
<input type="text" id="demo2" value="" name='x'>
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
$response = array();
foreach($output as row){
$response[] = ["value"=>$row['title'],"label"=>$row['title']];
}
echo json_encode($response);
I am new in php . I have the following code to retrieve categorytype data from database?. I want to add them into php object for temporary using while loading page. First, I want to load all predefined data, then i will use it when i click function. Could you enlighten me how to create it
categoryDao.php
namespace category;
use Exception;
use PDO;
class categoryDao{
public function categorytype(PDO $connection){
$conn = $connection;
try {
$conn = $connection;
$sql="SELECT * FROM `tb_category` WHERE id != parent_id;";
$categorytype = $conn->prepare($sql);
$categorytype->execute();
$data1 = array();
while (
$result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
return $data1;
} catch (Exception $e) {
echo $e;
throw $e;
}
}
}
categoryservice.php
use category\categoryDao;
require '../dao/categoryDao.php';
require 'Dao.php';
class categoryService{
public function categorytype(){
$dao = new Dao();
$conn= $dao->connect();
$conn->beginTransaction();
$categoryDao = new categoryDao();
//$data1 = array();
$data1=$categoryDao->categorytype($conn);
return $data1;
$dao->disconnect($conn);
}
}
categorytypecontroller.php
<?php
require '../service/categoryService.php';
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
//$ctype = array();
$ctype = $category->categorytype();
$return["json"] = json_encode($ctype);
echo $return["json"];
Head.php
function categorytype() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname1 = window.location.protocol + "//" + window.location.hostname+ "/servicegateway/sgw/modules/controller/categorytypecontroller.php";
alert (hosname1);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname1 , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data1){
alert(data1);
var obj =data1;
// var leng = Object.keys(obj).length;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#c_type").html(areaOption);
}
});
}
A couple of things. If you want the data to be an array of records, you'll probably want to change this part:
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
as that is putting all the fields, one after the other, into a normal array.
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = array(
'id' => $result['id'],
'c_name' => $result['c_name']
);
}
That will create a small associative array of the id and name fields and put it into another array, with the other records. PHP associative arrays will turn into Javascript objects when sent via ajax.
Then, in Javascript, you'll want to make use of those objects to create your options, so:
areaOption += '<option value="' + obj[i].id + '">' + obj[i].c_name + '</option>'
Below are a couple of queries that ultimately build an array.
if(isset($_POST['getarray'])){
try{
$ret = array();
$stmt = $db->prepare('SELECT groupdate, groupid
FROM participationtemp
WHERE memberid = :memberid
AND groupid = :groupid
ORDER BY groupdate, groupid DESC');
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row){
$attenddate = $row[0];
$stmt = $db->prepare('SELECT h.clientid, attend, attend_date
FROM history AS h
INNER JOIN suspended AS s on s.clientid = h.clientid
WHERE h.memberid = :memberid
AND h.groupid = :groupid
AND attend_date = :attenddate
AND suspend = "N"');
$stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
$stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
$stmt->bindValue(':attenddate', $attenddate, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll();
foreach($result as $row ) {
array_push($ret, ['id' => $row[0], 'gdate' => $row[2]]);
}
}
echo json_encode($ret);
exit();
} catch (PDOException $ex){
mail_error($ex);
}
}
After returning to JQuery, alert(re); shows I successfully created the array.
success:function(re){
alert(re);
But I'm having trouble accessing the array data. Without success, this is what i've tried:
data = $.parseJSON(re);
$.each(data, function(i, val) {
alert(i + "=" + val);
});
and this:
data = $.parseJSON(re);
$.each(data, function(i, val) {
if(i == "id"){
alert(i + "=" + val);
}
if(i == "gdate"){
alert(i + "=" + val);
}
});
I've also tried dot notation.
$.each(re.id, function(i, val) {
alert(i + "=" + val);
}
});
$.each(re.gdate, function(i, val) {
alert(i + "=" + val);
});
I've never used JSON before and don't understand why I can't retrieve the array data. Any help will be appreciated. Thanks.
The following code checks whether re is a string, or an object. The latter is possible if jQuery.ajax() method is used with "json" dataType. Also, jQuery is capable of parsing JSON automatically, if the response MIME type is application/json (the Content-Type HTTP header), particularly. So it is a good idea to check if re has been parsed by jQuery.
var d = typeof re === 'string' ? JSON.parse(re) : re;
var i;
for (i = 0; i < d.length; i++) {
console.log("id = ", d[i].id,
"gdate = ", d[i].gdate);
}
I'd recommend returning the appropriate content type from PHP:
header ('Content-Type: application/json');
echo json_encode($ret);
exit();
$.each(re, function(i, val) {
alert(val.id + "=" + val.gdate);
});
Try this code :)
// Json in string format
var jsonString = '[{"id":"1", "gdate":"2016-10-13"},{"id":"2", "gdate":"2016-10-13"},{"id":"3", "gdate":"2016-10-13"},{"id":"4", "gdate":"2016-10-13"},{"id":"5", "gdate":"2016-10-13"},{"id":"6", "gdate":"2016-10-13"}]';
// Convert string to json object
var json = JSON.parse(jsonString);
// Iterate over json object
jQuery.each(json, function(index, value) {
console.log(index, value);
});
// Simple access to attribute in json object
console.log('json[1][\'id\'] = ', json[1]['id']);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>