Hi I was able to display a json data(List of conversation result) but I want to display them just like how I display records from database like this:
foreach(res->fetchAll(PDO::FETCH_ASSOC) as result):
$username = $result['username'];
$message = $result['message'];
endforeach;
are there any similar procedure like this but with json_encode() ?
here is my php script
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT * FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$rows = $stmt7->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
This php script are getting its data from my ajax script below
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.ajax({
url: "includes/getChat.php",
type: "GET",
data: data,
dataType: 'json',
success: function(result){
var container = $("#clog");
$.each(result, function(i, message) {
$.each(message, function(key, value) {
container.append($('<p />').html(key + ':' + value));
});
});
}
});
The php and javascript are working fine the JSON are being displayed.. But I'm trying to figure out if there is a way that I can display only the username and the message just how I use the foreach statement that I mentioned above...
I may be misunderstanding, but you should be able to filter what is displayed by adding a condition with an if
$.each(result, function(i, message) {
$.each(message, function(key, value) {
if (key == "username" || key == "message")
container.append($('<p />').html(key + ':' + value));
});
});
Related
I have this php
include_once($preUrl . "openDatabase.php");
$sql = 'SELECT * FROM dish';
$query = mysqli_query($con,$sql);
$nRows = mysqli_num_rows($query);
if($nRows > 0){
$dishes = array();
while($row = $query->fetch_assoc()) {
$dishes[] = $row;
}
}else{
$dishes = "cyke";
}
echo json_encode($dishes , JSON_FORCE_OBJECT);
and this ajax (in framework7)
myApp.onPageInit('dailyMenu',function() {
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.log(data);
});
});
What i get in the ajax data is
{"0":{"idC":"2","title":"helloWorld1","subtitle":"hellsubWorld","price":"16.5","img":"img/testeImg.jpg","soldout":"0"},"1":{"idC":"3","title":"helloworld2","subtitle":"hellosubWorld2","price":"20.5","img":"img/testeImg.jpg","soldout":"1"}}
I already tried data.[0]; data.['0']; data.0; data0 when i use data["0"] just gives me the '{'.
I want to acess the title and the rest inside that 0. to do a cicle for where i will print multiple divs where i only change the array position in a html page.
Exemple
for(...){
innerhtml += <div clas="">
<div class""> data(position i).title </div>
<div> data(position i) subtitle</div>
</div>
}
try this one (after callback add type: json)
$$.post('url', {}, function (data) {
var obj = JSON.parse(data);
console.log(obj);
alert(obj["1"].title);
});
or maybe you can use JSON.parse(data);
Since you are receiving a json data as response, you should use this:
$$.post('http://theIP/eatsServer/dailyMenu.php', {}, function (data) {
console.dir(data);
},'json');
Pay attention to },'json');on end of the code, now the $$.post is reading the response as a JSON.
If you aren't doing any update to data base, you could use:
$$.getJSON('http://theIP/eatsServer/dailyMenu.php',{}, function (data) {
console.dir(data);
});
This is the way with $$.ajax:
$$.ajax({
url: "url_here",
method: "POST",
dataType:"json",
data: {},
success: function(r){
// response r.
}, error: function(error){
//error
}
});
I have following code to execute a query on the Database. it returns a list of objects, one for each row result from the query:
function getcontent()
{
var data = {
"id": "<?php echo $stournid; ?>"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php",
data: data,
success: function(response) {
//**************************** HERE!!!!
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
return false;
}
The response.php file contains this:
<?php
$id = "";
if (is_ajax()) {
if (isset($_POST["id"]) && !empty($_POST["id"])) { //Checks if action value exists
$id = $_POST["id"];
querydata($id);
}
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function querydata($id){
require_once('dbconfig.php');
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($mysqli->connect_error) {
die('Errore di connessione (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
$myArray = array();
if ($games = $mysqli->query("my query is here.. pretty long but working correctly.")){
while($row = $games->fetch_array(MYSQL_ASSOC)) {
$myArray[] = $row;
}
echo json_encode($myArray);
}
}
?>
here is the returned data:
[{"id":"1435","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|6|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":"57","id_gamer2":"55","called":"2","callreadytime":"13:08:07","starttime":"22:12:19","endtime":"22:20:03","id_winner":"57","id_loser":"55","playsequence":"00001","tabsequence":"A00010001","dest_winner":"B00010001-1","dest_loser":"C00010001-1","connectionname":"","p1name":"Calamante Lorenzo","p2name":"Badiali Maurizio"},
{"id":"1436","location":"Merano","date":"2017-01-26","eventname":"Collaudo","machines":"|4|","id_tournament":"2","allowedcat":"|A||B||C||D|","category":"test 1","chartsize":"8","exclusive":"0","subscriptionsactive":"0","maxsubscriptions":"512","autoplay":"3","machinespergame":"1","id_subtournament":"14","id_gamer1":null,"id_gamer2":null,"called":"0","callreadytime":"00:00:00","starttime":"00:00:00","endtime":"00:00:00","id_winner":"0","id_loser":"0","playsequence":"00015","tabsequence":"W00010001","dest_winner":"","dest_loser":"1","connectionname":"","p1name":null,"p2name":null}]
What I would like to do, is in the Javascript, go through all the returned lines one by one and updated some div's accordingly. I am having difficulties on how to iterate the returned lines.
Any help appreciated.
Thanks
success: function(response) {
// redponse is an array of objects (so lets loop through it using forEach)
response.forEach(function(row) {
// row is a row (object) from the array
var id = row.id;
var location = row.location;
var date = row.date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
Note: Array.prototype.forEach is like a loop but better. Check the docs.
Don't want to use forEach?
If you don't want to use forEach, you can use an old for like this:
success: function(response) {
// using for is not very pretty, hein?
for(var i = 0; i < response.length; i++) {
// response[i] is the i-th row of the array
var id = response[i].id;
var location = response[i].location;
var date = response[i].date;
// ... you get the idea
// do something with the current row (maybe create a div or table row ...)
});
},
I want php file to return data (from the database) on ajax call. Ajax call returns an error alert everytime. I tried everything, but have no idea how to return array from PHP to ajax call
So far, I made this..
ajax call
function dohvatiPrveTriAkcije(id){
var url = 'http://localhost/ljekarna/model/akcija.php';
$.ajax({
type: "POST",
url: url,
cache: false,
data: { "kategorija": id},
dataType: "json",
success: function (data) {
document.getElementById("kat_id").innerHTML += 'aaa';
},
error: function () {
alert('Pojavila se greška pri dohvacanju akcija za odabranu kategoriju');
}
});
return null;
}
php class
<?php
require_once 'baza_model.php';
$akcija = new Akcija();
if (isset($_GET['kategorija'])) {
echo $_GET['kategorija'];
$akcije = $akcija->dohvatiPrveTriAkcijeZaKategoriju($_GET['kategorija']);
echo $akcije;
}
class Akcija{
private $baza;
static function dohvatiPrveTriAkcijeZaKategoriju($kategorija){
$baza = new Baza();
$akcije = array();
$upit = 'SELECT lijek.naziv, akcija.postotak, akcija.datum_zavrsetka FROM akcija join lijek on akcija.lijek = lijek.id
join kategorija on lijek.kategorija = kategorija.id
where akcija.datum_zavrsetka > CURDATE() AND kategorija.id = ' . $kategorija . ' AND akcija.status = 1
ORDER BY akcija.datum_zavrsetka ASC LIMIT 3';
$rez = $baza->selectDB($upit);
while($red = $rez->fetch_assoc()){
echo "id: " . $red["id"];
$akcije[] = $red;
}
return $akcije;
}
}
I also tried this...
You need a json formatted string returned by the server. Use json_encode() instead of trying to echo out your array (which is what's giving you your array to string error).
I cant find answer to my problem...the truth is im new to jQuery and JSON.
On login page i want to display top customers and top tracks, when page loads.
Iv displyed them via echo from php, but i want to create JSON object and send it to login ...loop there and display it in unordered list.
Can you guys help me with creating JSON and displaying it in jquery.
Here's my code:
jQuery:
/* Function to load top Customers */
function loadCustomers() {
/* Create data string to call functions in php*/
var dataString ="function1=loadCustomers&function2=loadTracks";
$.ajax({
type:"GET",
url: "login.php",
data: dataString,
dataType: "json",
success: function(data) {
$("#error").show();
$("#errormsg").html(data.FirstName);
//how can i display Json data in unordered list ? #customerList
},
error: function() {
$("#error").show();
$("#errormsg").text("cant display data");
}
});
}
PHP :
}else if ($_SERVER["REQUEST_METHOD"] == "GET") {
//JSON customers array
$customers = array();
if ($_GET["function1"] == "loadCustomers") {
try {
$customerStmt = $conn->prepare("Select customer.FirstName, customer.LastName, customer.City, sum(invoice.Total) from invoice INNER JOIN customer on invoice.CustomerId = customer.CustomerId group by invoice.CustomerId order by sum(invoice.total) DESC LIMIT 5");
$customerStmt->execute();
$customerRows = $customerStmt->fetchAll();
//how to create JSON data to send it
header("Content-type: application/json");
echo json_encode($customerRows);
}catch (PDOException $e) {
$e->getMessage();
}
}
Well, from the code it looks like you are responding with multiple customers, but in jQuery you are accessing the data directly without accessing the array. So it should look like this
$.ajax({
type:"GET",
url: "login.php",
data: dataString,
dataType: "json",
success: function(data) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#customerList" );
},
error: function() {
$("#error").show();
$("#errormsg").text("cant display data");
}
});
The problem was i couldn't recive JSON data from PHP.
After hours of googling and trying diffrent solutions i finally found an error..
When you read from database you have to set it to utf-8 charset.
I was fixing this problem in code with utf8_encode function...
You have to set it in new definition of PDO object :
$conn= new PDO("mysql:host=$server;dbname=$database;charset=utf8", $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
After this change im sending JSON data .
I'm doing an calendar, and i created a page to show the events from a certain day.
I'm using Ajax because i dont want my users to reload the page everytime that a new event is created.
So, i'm using Json encode to get the values from an array, and everytime that i print a day with two events, i receive this:
[{"event_day":"9","event_name":"test"}, {"event_day":"9","event_name":"test2"}]
But when i try to print the elements in JQuery to put inside an element, i receive [object Object]
I inserted the array inside a while loop because i'm getting multiple rows from my database table.
PHP function
function eventPrint($list_day, $month, $year){
$select = mysql_query("SELECT * FROM events WHERE event_day = '".$list_day."' AND event_month = '".$month."' AND event_year = '".$year."'") or die(mysql_error());
$data = array();
while($row = mysql_fetch_assoc($select)) {
$event_day = $row['event_day'];
$event_name = $row['event_name'];
$data[] = array('event_day' => $event_day,
'event_name' => $event_name
);
}
echo json_encode($data);
}
Ajax
$.ajax({
type: 'get',
url: "modules/groups/new.php",
data: {
'list_day': getday,
'month': getmonth,
'year': getyear,
'action': 'selection'
},
success: function (response) {
var obj = jQuery.parseJSON(response);
$('.' + getmonth).html(obj.event_day);
}
});
Your code should be:
success: function( response ) {
var obj = response[0] ? response : jQuery.parseJSON(response);
$('.' + getmonth).html(obj[1].event_day);