My php file does this:
<?php include('connection.inc.php'); ?>
<?php header("Content-type: application/json"); ?>
<?php
$sth = mysql_query("select * from ios_appointments a join ios_worker w join ios_partners p where a.workerid_fk = w.workerid and w.partnerid_fk = p.partnerid and p.code = 'DEMO6003'");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
?>
It returns this JSON output:
[{"appointmentId":"25","start":"2013-01-07 14:45:00","end":"2013-01-07 15:45:00","workerid_fk":"1","userid_fk":"22","isActive":null,"workerid":"1","prename":"Sarah","lastname":"Gonzalez","avatar":"megan.jpg","lineup":"Herren\/Damen","languages":"DE EN","partnerid_fk":"6","partnerid":"6","code":"DEMO6003","partnerName":"Demo Partner","street":"bla 1","zipCode":"bla","city":"bla","workers":"n\/a","email":"test#test.com","phone":"+41414441111","slogan":"Demo Partner zum Erkunden der App"},{"appointmentId":"26","start":"2013-01-10 11:15:00","end":"2013-01-10 12:15:00","workerid_fk":"1","userid_fk":"22","isActive":null,"workerid":"1","prename":"Sarah","lastname":"Gonzalez","avatar":"megan.jpg","lineup":"Herren\/Damen","languages":"DE EN","partnerid_fk":"6","partnerid":"6","code":"DEMO6003","partnerName":"Demo Partner","street":"bla 1","zipCode":"bla","city":"bla","workers":"n\/a","email":"test#test.com","phone":"+41414441111","slogan":"Demo Partner zum Erkunden der App"}, ...]
Now I try to parse the JSON output in a html file with this script:
<script type="text/javascript">
$.getJSON('<link to php file>', function(data) {
$.each(data, function(i, appointment) {
alert('entered each()');
var id = appointment.appointmentid;
console.log('appointmentid ' + id);
});
});
</script>
$.getJSON is called, but data is null. What am I doing wrong?
You just need to capitalize the i in appointment.appointmentid;
appointment.appointmentId; // <-- since your property has it capitalized
Related
I'm trying to make my own api using a JSON and PHP script, which is successfully working (api.mystem.tk/product), however I want to convert that data to an html table with the columns: id, name and date.
My question, how? I've got my code included and you can watch the JSON output in the console of api.mystem.tk/product. I've deleted all the private details in the scripts and replaced them with #______.
api.php:
<?php
$connect = mysqli_connect('#host', '#user', '#password', '#db');
if(!isset($_GET['function'])) {
die('Some error occurred!');
}
function GetProducts($db) {
$sql = mysqli_query($db, 'SELECT * FROM php_test ORDER BY Id ASC LIMIT
0, 10');
$data = array();
if (mysqli_num_rows($sql) > 0) {
while ($row = mysqli_fetch_array($sql)) {
$data[] = $row["Id"];
$data[] = $row["Name"];
$data[] = $row["Date"];
}
}
$data = json_encode($data);
echo $_GET['jsonCallback'].'('.$data.')';
}
if (function_exists($_GET['function'])) {
$_GET['function']($connect);
}
echo $data;
?>
function.js:
$(function(){
var functionName = 'GetProducts';
function LoadData() {
$.getJSON("http://api.mystem.tk/product/api.php?
function="+functionName+"&jsonCallback=?", function(data) {
var all_data = [];
$.each(data, function(k, name){
var array_data = '<div class="names">'+name+'</div>';
all_data.push(array_data);
});
$('#data').append(all_data);
console.log(data);
});
}
LoadData();
});
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<title> API TEST </title>
<meta name="viewport" content="width=device-width,initial-
scale=1,maximum-scale=1,user-scalable=0">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
</head>
<body>
<div id="data"></div>
<script type="text/javascript" src="function.js"></script>
</body>
</html>
so i've tried using $.parseJSON instead of $getJSON, but without succes
console:
Uncaught SyntaxError: Unexpected token <
at m (jquery-3.3.1.min.js:2)
at Function.globalEval (jquery-3.3.1.min.js:2)
at text script (jquery-3.3.1.min.js:2)
at Ut (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
and i've changed this:
$data[] = $row["Id"];
$data[] = $row["Name"];
$data[] = $row["Date"];
to this:
$data[] = array(
'id' => $row["Id"],
'name'=> $row["Name"],
'date'=> $row["Date"]
)
to be a little bit more specified...
You'll need to parse JSON data in your function.js using jQuery.parseJSON() jQuery function.
You can read brief documentation from: jQuery.parseJSON()
Added code:
<script>
var obj = JSON.stringify([
{
"id":'1',
"name":'Jhon Doe',
"date":'April 14,2018'
},
{
"id":'2',
"name":'Coder',
"date":'April 23, 2018'
}
]);
var jsontoparse = JSON.parse(obj);
var i = obj.length;
var j=0;
while(j<=i){
console.log(jsontoparse[j].id);
j = j+1;
}
</script>
I got the following problem. I want to display a multi array via ajax.
Javascript:
function getContent(HSID,HSname){
$.ajax({
url: 'ajax/script.gethandlungslogContent.php',
type: "POST",
data: { HSID : HSID },
dataType : "json",
success: function(data) {
document.getElementById('wartungslogHead').innerHTML = HSname;
document.getElementById('wartungslogContent').innerHTML = data.hl_aenderung;
document.getElementById('wartungslogID').value = data.HSID;
//document.getElementById('wartungslogID').value = data.KentID;
document.getElementById('buttonEdit').style.display = 'inline';
document.getElementById('buttonDelete').style.display = 'inline';
}
});
}
PHP Script:
<?php
include_once('../classes/class.mysql.php');
if (isset($_POST['HSID'])){$HSID = $_POST['HSID'];};
$HSID = 2;
$mydb3 = new DB_MySQL('localhost','','','');
$query3 = "SELECT * FROM hosting_handlungslog WHERE HSID = '$HSID'";
$mydb3->query($query3);
while ($row3 = $mydb3->fetchRow()){
echo json_encode($row3);
}
?>
The return of the php script looks like this:
{"HLID":"1","HSID":"2","hl_datum":"2014-01-19","hl_info":"n","hl_aenderung":"Windows-UpdatesJava Update"}
{"HLID":"2","HSID":"2","hl_datum":"2014-02-02","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"}
{"HLID":"3","HSID":"2","hl_datum":"2014-03-03","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"}
{"HLID":"4","HSID":"2","hl_datum":"2014-04-13","hl_info":"y","hl_aenderung":"Windows-UpdatesTomcat-Update auf 6.0.39Apache Update 2.4.8 (OpenSSL auf 1.0.1g)"}
{"HLID":"5","HSID":"2","hl_datum":"2014-04-14","hl_info":"n","hl_aenderung":"Zertifikatsaustausch wegen Heartbleed Bug"}
{"HLID":"6","HSID":"2","hl_datum":"2014-04-27","hl_info":"y","hl_aenderung":"Java Update auf 7.0.58"}
{"HLID":"7","HSID":"2","hl_datum":"2014-06-08","hl_info":"y","hl_aenderung":"Windows-UpdatesTomcat-Update auf 6.0.41Apache Update auf 2.4.9 (OpenSSL auf 1.0.1h)Java Update auf 7.0.60"}
{"HLID":"8","HSID":"2","hl_datum":"2014-07-21","hl_info":"y","hl_aenderung":"Apache Update auf 2.4.10Java Update auf 7.0.62"}
What to do here? Thanks in advance!
You must save it to another Array and show after gets all data from mysql.
<?php
include_once('../classes/class.mysql.php');
if (isset($_POST['HSID'])){$HSID = $_POST['HSID'];};
$HSID = 2;
$myjsonarray = null;
$mydb3 = new DB_MySQL('localhost','','','');
$query3 = "SELECT * FROM hosting_handlungslog WHERE HSID = '$HSID'";
$mydb3->query($query3);
while ($row3 = $mydb3->fetchRow()){
$myjsonarray[] = $row3;
}
echo json_encode($myjsonarray);
?>
And now you get this
[{"HLID":"1","HSID":"2","hl_datum":"2014-01-19","hl_info":"n","hl_aenderung":"Windows-UpdatesJava Update"},{"HLID":"2","HSID":"2","hl_datum":"2014-02-02","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"},{"HLID":"3","HSID":"2","hl_datum":"2014-03-03","hl_info":"n","hl_aenderung":"Windows-UpdatesTomcat-UpdateApache-Update"},...]
Example show in php...
<?php
echo $myjsonarray[0]["HLID"];
echo $myjsonarray[1]["HLID"];
?>
In jquery you may use "for"
for(i=0;i<data.lenght;i++){
mydata = data[i];
alert(mydata["HSname"]);
}
Change your PHP to :
$tempArray = array();
while ($row3 = $mydb3->fetchRow()){
tempArray[] = $row3;
}
echo json_encode($tempArray);
Then in javascript:
success: function(data) {
$.each(data, function(index, item){
// Now loop through e.g.
$('body').append('<div class="wartungsLogID">' + item.HSID + '</div>');
});
}
In your javascript, in the success callback, you need to parse the json (var data).
If you have a table element, you can fill it with your data.
First you need a table and cycle:
var t = document.getElementById(mytableId);
for (var i = 1; i < data.length; i++)
...
inside the loop you need to create a row for every object inside your json:
var tr = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = data[i].hl_aenderung;
tr.appendChild(td);
t.appendChild(tr);
and repeat this for every field (every object's propery (hl_datum,hl_info,etc.)).
Within the Ajax Success callback you must loop through the array to display each object individually.
Below is an example, including some best practice techniques:
success: function(data) {
var textToDisplay = '';
$.each(data, function(i, item){
textToDisplay += '<li data-id="'+item.HLID+'">'+item.hl_aenderung+'</li>'
});
$('ul').append(textToDisplay);
}
Here's a working fiddle which you can expand on.
<?php require_once('Connections/root.php'); ?>
<?php $q = mysql_query("SELECT * FROM performer"); ?>
<script> $(document).ready(function () {
$(function() {
var availableTags = ["<?php while($r = mysql_fetch_assoc($q)) { echo $r['username']; } ?>"];
$("#search_box").autocomplete({
source: availableTags
});
});
});
</script>
the script works but it displayes : User1User2User3
and i want it to display:
User1
User2
User3
How do i add a new line after every user and where do i add the line feed
if i make it like this
var availableTags = ["<?php while($r = mysql_fetch_assoc($q)) { echo $r['username'] . " <br />"; } ?>"];
i get User1User2User3 and the br as a string
Separate your PHP logic from your Javascript code. Up top, build a PHP array first:
$tags = array();
while($r = mysql_fetch_assoc($q)) {
$tags[] = $r['username'];
}
Then in your javascript, echo the array JSON encoded:
var availableTags = <?php echo json_encode($tags); ?>;
Note: You are using deprecated mysql_* functions and should switch to mysqli_* or PDO.
As mentioned, your availableTags array has only 1 string variable.
You need to push the string to the Array.
You can try this:
var availableTags = [];
<?php while($r = mysql_fetch_assoc($q)) { ?>
availableTags.push('<?php echo $r['username']; ?>');
<?php } ?>
The generated js array is not what you expect it to be. With your code, you obtain
var availableTags = ["User1User2User3"];
whereas what you need is
var availableTags = ["User1", "User2", "User3"];
Yous should adapt your PHP code to generate the right JS.
below is my $.ajax call to php
$(document).ready(function() {
$('ul.sub_menu a').click(function(e) {
e.preventDefault();
var txt = $(this).attr('href');
$.ajax({
type: "POST",
url: "thegamer.php",
data:{send_txt: txt},
success: function(data){
$('#container').fadeOut('8000', function (){
$('#container').html(data);
$('#container').fadeIn('8000');
});
}
});
});
});
my php code
if(mysql_num_rows($result) > 0){
//Fetch rows
while($row = mysql_fetch_array($result)){
echo $row['img'];
}
}
I m getting this output
images/man/caps/army-black.pngimages/man/caps/army-brown.pngimages/man/caps/army-grey.pngimages/man/caps/army-lthr.pngimages
these are basically image paths now how to loop over them in jquery and fit each image in image tag
any code will be useful
Plz Note I DONT NEED JSON
regards sajid
JSON is probably your best bet here. In PHP do something like this:
$ret = array();
while( $row = mysql_fetch_assoc( $result ) )
{
$ret[] = $row['img'];
}
echo json_encode( $ret );
This will output something like the following
["image1","image2","image3"]
jQuery has a function which can convert this information into a javascript array. So put this code in your success callback.
var result = jQuery.parseJSON( data );
alert( result[1] );
EDIT: A method which does not use JSON
In PHP place each image url on a separate line
echo $row['img'], "\n";
Then in javascript, split the response by the new line character
var result = data.split( "\n" );
simply change your php code:
`if(mysql_num_rows($result) > 0){
while($row = mysql_fetch_array($result)){
echo ""<img src='".$row['img']."' /><br />";
} }
Hey guys, I'm using jQuery's autosuggest plugin by using php to get the data. But it doesn't seem to work since I always get: No Results Found, even though I'm sure there are results:
Here's the php code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$input = mysql_escape_string($_GET["q"]);
$data = array();
$mysql=mysql_connect('localhost','***','***');
mysql_select_db('jmtdy');
$query = mysql_query("SELECT * FROM users WHERE username LIKE '%".$input."%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
And the script:
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest("suggestedf.php");
});
</script>
<script >
$(document).ready(function () {
$("#suggestedfriend").autoSuggest(
"suggestedf.php",
{
selectedValuesProp: "value",
selectedItemProp: "name",
searchObjProps: "name"
});
});
</script>
Add the above parameters, it will start to work :)
Just look at data, that server sends you back. If you use firefox you can watch it in network tab of firebug, or if you use chrome see it in resources.
The header must be in top of the file, right after the
<?php
header('Content-type: application/json');
include_once 'resources/dbconn.php';
$term = $_REQUEST['term'];
$query = "SELECT * FROM cds WHERE titel LIKE '%$term%'";
$result = $mysqli->query($query);
$arr = array();
while ($obj = $result->fetch_array()) {
$arr[] = $obj;
}
//for jsonp echo '('.json_encode($arr).')';
echo json_encode($arr);
?>
The JS/jQuery string
<script type="text/javascript">
$(function() {
var cache = {},
lastXhr;
$("#exercise").autocomplete({
minLength: 2,
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.getJSON("json_Search.php", request, function(data,status,xhr) {
cache[term] = data;
if (xhr === lastXhr) {
response(data);
}
});
}
});
});
</script>