I am trying to get all objects that are in a json string via $.getJSON and it works but I am having trouble showing them all (it only is showing the last object). I know its because its overwriting each entry via .$each but I've no clue on how to fix this, as I tried to append it but that just kept displaying each of the entries multiple times (I have it set to update every 5 seconds, to see if there are more entries available). Anyway, here is the code I have in place (both jQuery and PHP)
jQuery Code -
$(function() {
function buildOnlineFriendList() {
$.getJSON("/members/friends/get-friends-online")
.done(function(msg) {
if (jQuery.isEmptyObject(msg)) {
$('#friends-online').html("No friends are online.");
} else {
$.each(msg, function(key, value) {
// how to display each friend online without overwriting each one to only display the last. :/
$('#friends-online').html("" + value.name + "<br>");
});
}
}).fail(function(msg) {
$('#friends-online').html(msg.message);
});
}
setInterval(function() {
buildOnlineFriendList();
}, 5000);
buildOnlineFriendList();
});
PHP code -
public function getFriendsOnline()
{
$query = $this->connection->execute("SELECT members.username AS friend_username, friends_online.user_id AS fo_id FROM friends_online, friends, members
WHERE friends_online.user_id = friends.friend_id AND members.id = friends.friend_id AND friends.user_id = " . $this->getUserId()['id']);
if ($query->count() > 0) {
// get the id/username of the friend(s) online
foreach ($query as $values) {
$friends_online[] = array('id' => $values['fo_id'], 'name' => $values['friend_username']);
}
return $friends_online;
} else {
throw new FriendsException("No friends are online.");
}
}
Any help would be appreciated.
Thanks!
(I can try and provide more information if my question is unclear)
You already know it's overwriting the values when writing using $.each. The issue is it's writing the HTML for the friends-online element each loop. All you need to do is to set this value in a variable and update the variable in each iteration. Then after the loop is done, set the HTML for the element. I've modified your function to:
function buildOnlineFriendList() {
$.getJSON("/members/friends/get-friends-online")
.done(function(msg) {
// create a variable to hold the html string
var html = "";
if (jQuery.isEmptyObject(msg)) {
$('#friends-online').html("No friends are online.");
} else {
$.each(msg, function(key, value) {
// set the value of the html here
html += "" + value.name + "<br>";
});
// set the html here, after the loop.
$('#friends-online').html(html);
}
}).fail(function(msg) {
$('#friends-online').html(msg.message);
});
}
$("#friends-online")
.append(
$("<a>")
.attr("href", "/members/chat/" + value.id)
.attr("class", "chat-with")
)
.append($("<br>"));
Try replace this:
$('#friends-online').html("" + value.name + "<br>");
With this:
$('#friends-online').append("" + value.name + "<br>");
The .html() method will overwrite all existing HTML within the selected element.
The .append() method will add the content on to the end of the existing HTML
Try replacing $('#friends-online').html(... with $('#friends-online').append(.... At the moment this line is resetting the HTML of #friends-online over and over, whereas using append will add each new user to the element.
You will need to also add $('#friends-online').empty() as the first line of your timer, i.e.
setInterval(function() {
$('#friends-online').empty();
buildOnlineFriendList();
}, 5000);
Or in the function itself, i.e.
function buildOnlineFriendList() {
$('#friends-online').empty();
$.getJSON("/members/friends/get-friends-online") ...
Related
I'm trying to access each element stored as a Base64 image/blob in a JSON array constructed from a MySQL query.
The idea is to click a button that goes through each element and displays the image.
I have gotten it to display the first image however when i click again, the next image doesn't show.
Any help will be much appreciated.
AJAX:
$(function () {
$('#getimg1').on('click', function () {
$.ajax({
type:'GET',
dataType: 'json',
url: 'http://testing/api/getimg',
success:function(getinfo){
$.each(getinfo, function(i, displayimg){
$('#HTMLBox').prop('src','data:image/png;base64,' + displayimg.XXX ---- //Here I'm suspecting something?);
});
}
});
});
});
PHP:
$sql = "SELECT img from artistlocation";
try{
$db = new db();
$db = $db->connect();
$stmt = $db->query($sql);
$data = array();
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
$data[] = base64_encode($result->img);
}
echo json_encode($data);
}
catch(PDOException $e){
echo '{"error": {"text": '.$e->getMessage().'}';
}
I'm using just 2 images to test this.
Because the ajax call you make will return all of the image records, I think it would be more efficient to store that data in a variable and then just rotate through the images rather than making call to your php code with each click. Here's what I would suggest, if you're using just jQuery:
var images = [],
index = 0,
count = 0,
max = 0;
$.getJSON("http://testing/api/getimg", function(data) {
images = data;
count = images.length;
max = count - 1;
});
$('#getimg1').on('click', function() {
if (count === 0) {
return;
}
if (index === max) {
index = 0;
} else {
index++;
}
$('#HTMLBox').attr('src', 'data:image/png;base64,' + images[index]);
});
I must admit I didn't test it, but I believe it should work - if you could try and see how you get on.
So, if you wanted to do something really dirty, you could track how many images you've loaded via a hidden input. You can increment that upon your ajax success. Then, what you can do is pass to your PHP via your AJAX that value, and run something like:
SELECT * FROM images LIMIT 1 OFFSET $images_already_fetched
By passing an OFFSET declaration, you're telling it to skip that many rows.
My algorithm:
I get the DIV text from php/SQL ($.get( "read.php"...)
APPEND contenteditable div with loaded text by jQuery
check the div value, if there is errors in text I make div red (assign class, $(this).addClass("fill_red");)
on every change of text - check and assign/remove class if needed.
Problem is: with preloaded text - everything is working.
But when I append div using JS - check function don't works.
I searched the web, maybe on() method helps me.
But what event?
It should be something like onload, onchange..?
(yes, I could make div generated by php and solve the problem, but I dont want full refresh)
Thank you!
part of code:
//texts load
$(function() {
$.get( "read.php", function( data ) {
var ionka = data.split(' ');
ionka.forEach(function(item, i, arr) {
var app_text = "<div id=\"segm" + i + "\" contenteditable role=\"textbox\">" + item + "</div>";
$("#textarea").append(app_text);
});
});
//checks
var intRegex = new RegExp('^[0-9/\]{5}$');
$('#textarea div').each(function(i,elem) {
if(!intRegex.test($(this).text())) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
});
// edit on change. Blur because of contenteditable
var segm_array = [];
$('#textarea div').each(function(i,elem) {
$(this).blur(function() {
if (segm_array[i]!=$(this).text()){
segm_array[i] = $(this).text();
if(!intRegex.test(segm_array[i])) {
$(this).addClass("fill_red");
}else{
$(this).removeClass();
}
}
});
});
You dont show much code here, but my guess is that you are trying to add class before new data is loaded into dom
$.get( "read.php" ).done(function( data ) {
// addClass etc
});
I'm looking to put a div on my website where the content changes based on what link is clicked without refreshing. The content to put there comes from a MySQL database and it's put in JSON.
My problem is that I can't get the JSON data to display when clicking the links.
Here's the script I'm using:
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
for(var i=0; i<data.length;i++) {
$("#changetext"+data[i].id).click(function() {
$("#rightside").html("<h1>" + data[i].title + "</h1><p />" + data[i].content);
});
}
}
});
This is the div element that has to change:
<div class='rightside' id='rightside'>Test</div>
The links are constructed this way:
echo "<a id='changetext" . $row['id'] . "'> ";
echo "<div class='tile'>";
echo "<h2>Tile</h2></div></a>";
I've tested the different elements and they work fine (changing the divs content with hardcoded data, displaying the JSON data), but I'm having a hard time figuring out why the combined thing isn't working.
Objects does'nt have a length, use $.each to iterate it instead, unless it's actually an array containing objects :
$(document).ready(function () {
$.getJSON("jsondata.php",rightSideData);
function rightSideData(data) {
$.each(data, function(i, d) {
$("#changetext" + d.id).on('click', function() {
var h1 = $('<h1 />', {text : d.title}),
p = $('<p />', {text : d.content});
$("#rightside").html(h1.add(p));
});
});
}
});
The problem is that i var will be data.length at the end of the loop and that's what the click handler will see.
I am really confused how i managed these things.Please look at the attached image.See the right panel area.
Starting from first, package name is coming from last page; let's say page1.php. Now assume this attached image is page2.php.I am able to grab the selected checkbox values from left hand side and it is posting on right hand side.See i have checked the video checkbox.I have used jquery for that.
Problem 1 if i refresh the page values disappear except package value.I want the all checkbox value from right panel whatever user checked and post it to page3.php for further usage.I dont think jquery will do.I used the ajax post but cant able to grab values from below code.kindly help him regarding this.
Image link http://s7.postimage.org/3zbf1ucwb/image.jpg
function refreshPrices() {
var beg=<?php echo isset($beg) ? $beg : 0 ?>;
var inte=<?php echo isset($int) ? $int : 0 ?>;
var advn=<?php echo isset($adv) ? $adv : 0 ?>;
var currentTotalValue = 0;
currentTotalValue = currentTotalValue + beg + inte + advn;
$("#results div").each(function() {
if (!isNaN(parseInt($(this).find("span").text().substring(1)))) {
currentTotalValue += parseInt($(this).find("span").text().substring(1));
}
});
$("#totalValue").text("$" + currentTotalValue)
}
$(document).ready(function() {
$('#1').click(function() {
//var row = $(this);
if (($(this).attr('checked')) == 'checked') {
$('#result').append("-PDF Document <html><span style=float:right>$100</span></html>");
}
else {
$('#result').text("");
}
refreshPrices()
});
$('#2').click(function() {
if (($(this).attr('checked')) == 'checked') {
$('#result2').append("-Video <html><span style=float:right>$200</span></html> ");
}
else {
$('#result2').text("");
}
refreshPrices()
});
});
$(this).attr('checked') returns true or false, not 'checked', so you need to do :
if ( $(this).prop(':checked') ) { --- }
or just
if ( this.checked ) {
$('#result').append("-PDF Document <html><span style=float:right>$100</span></html>");
}
Also, you should'nt be using just a number as an ID, change it to #a1 etc. and you do realize that <html> tags are the start and end of the document, and appending them to an element inside the DOM does really seem like a great idea.
I am new to json n php..
using code below to fetch data for radio button check box and text box with json . It is working fine but I donno how to populate data in select box in the same way .
function get_input_value(name, rval) {
//console.log(name + ' && ' + rval);
var i = 0;
var chk = $('input[name="' + name + '"]');
while (i < chk.length) {
//console.log($(chk[i]));
if ($(chk[i]).val() == rval) {
//console.log('loopvalue => ' + i);
$(chk[i]).prop('checked', true);
}
i++;
}
}
function loadJson (table, id) {
$.get("json-object.php", {'table': table, 'id':id}, function (data) {
console.log(data);
$.each(data, function (k, v) {
if ($('input[name="'+k+'"]').is('input[type="text"]')) {
$('input[name="'+k+'"]').val(v);
}
if ($('select[name="'+k+'"]').is('input[type="radio')) {
get_input_value(k,v);
}
if ($('input[name="'+k+'"]').is('input[type="checkbox"]')) {
get_input_value(k,v);
}
console.log(k+' ==> '+v);
});
}, 'json');
}
Your code is just setting value of text boxes and auto select certain checkboxes based on the PHP output.
To have it auto set the proper item in drop down lists as well you need to change this wrong code:
if ($('select[name="'+k+'"]').is('input[type="radio')) {
get_input_value(k,v);
}
To this:
$('select[name="'+k+'"]').val(v);
(No point to check type of <select> since it got none)