Im trying to figure out which is the best method for sending data from a get request to a div. The issue that confuses me is to send it only to a div that is relative to the one calling the action. So when I click on the message_tab I want to send the data from the get request to the thread_load. however the thread_load is not a direct descendant of the message_tab yet a sibling to the message_flyout. How can i get this to send the data only to the sibling's thread_load? Here is what i have:
The message_tab and message_flyout are both a part of the appended message_block.
HTML
var el = $(
'<div class = "message_block">'+
'<div class = "message_tab" value = '+ user_id +' >'+ '</div>' +
'<div class = "message_flyout">' +
'<div class = "message_content">' +
'<div class = "message_header">'+ '</div>' +
'<div class = "conversation_scroll">' +
'<div class = "scroll_content">' +
'<ul class = "thread_load">'+ '</ul>'+
'</div>' +
'</div>' +
'<div class = "message_form">' +
"<form class = 'myForm' action='"+'http://localhost:8000/newMsg/'+user_id+"' method= 'POST' accept-charset= 'UTF-8'>" + "<input name='_token' type='hidden' value='lbaqsTEePfIMYguGnsMvEDt8ExHly3dLKHtAu18c'>" +
'<div class = "message_form">' +
"<input class='input-mini' placeholder='Type a message...' name='body' type='text'>" +
'</div>'+
"</form>" +
'</div>'+
'</div>'+
'</div>'+
'</div>');
Javascript:
$(document).on('click', '.message_tab', function(){
var user_id = $(this).attr('value');
var elem_data = $(this).siblings('.message_flyout');
var data_transfer = $(elem_data).children('.thread_load');
console.log(data_transfer);
base_url = 'http://localhost:8000/thread';
$.get(base_url + '/' + user_id , function (data) {
$(data_transfer).closest('.thread_load').html(data);
});
$(this).siblings('.message_flyout').toggle();
$(this).parent('.message_block').css('width', '258px');
});
You should do:
$(document).on('click', '.message_tab', function () {
var user_id = $(this).attr('value');
var elem_data = $(this).siblings('.message_flyout').find('.thread_load');
console.log(data_transfer);
base_url = 'http://localhost:8000/thread';
$.get(base_url + '/' + user_id, function (data) {
elem_data.html(data);
});
$(this).siblings('.message_flyout').toggle();
$(this).parent('.message_block').css('width', '258px');
});
.closest traverse upwards and return the first matching element. Whereas, .find traverse inside the node giving all the matching element.
Note:
And you should not use value as an attribute for a div, it is not valid thingy. Always use data-whatever and fetch it using either .data('whatever') or .attr('data-whatever').
Something like this perhaps?
$(document).on('click', '.message_tab', function(){
var user_id = $(this).attr('value');
var data_transfer = $(elem_data).children('.thread_load');
var base_url = 'http://localhost:8000/thread';
// Target thread load here
var $thread_load = $(this).next('.message_flyout').find('ul.thread_load');
$.get(base_url + '/' + user_id , function (data) {
$thread_load.html(data);
});
$(this).siblings('.message_flyout').toggle();
$(this).parent('.message_block').css('width', '258px');
});
.message flyout comes directly after .message_tab, so if we move to that element then use .find which is the fastest way to retrieve thread load you should be good. I haven't tested this however.
Related
I'm trying to set the source and type for Video.js dynamically via a JSON object that is retrieved from a remote method call.
radioPlayer = videojs("RadioPlayer");
function RadioListPage() {
$.getJSON(serviceURL + 'rbApp.cfc?method=Radio', function(data) {
$.each(data.DATA, function(index, itemData) {
$('#radioList').append('<div class="play" data-type="' + itemData[4] + '" data-src="' + itemData[3] + '" data-station="' + itemData[1] + '" data-id="' + itemData[0] + '"><img src="' + itemData[2] + '"></div>');
lastIDNumberVideo = itemData[0];
});
$('#radioList .play').click(function() {
var stationObject = new Object();
stationObject.src = $(this).data("src");
stationObject.type = $(this).data("type");
var jsonStr = JSON.stringify(stationObject);
radioPlayer.src(jsonStr);
radioPlayer.play();
});
loading('hide', 100);
});
}
VideoJS will throw an error that the stream isn't valid. However, if I take that jsonStr variable and hard code that value like this radioPlayer.src({"src":"http://wlca-stream.lc.edu:8004/wlca","type":"audio/mpeg"}) it plays with no issue. What am I missing here? Is this not possible to do?
The example code you show provides a JS object to the src() method, yet you're providing JSON. Try providing the object directly to the method.
Also note that I'd suggest you use a delegated event handler instead of binding events in the AJAX callback, which can lead to issues with duplicated events. Try this:
radioPlayer = videojs("RadioPlayer");
$('#radioList').on('click', '.play', function() {
radioPlayer.src({
src: $(this).data("src"),
type: $(this).data("type")
});
radioPlayer.play();
});
function RadioListPage() {
$.getJSON(serviceURL + 'rbApp.cfc?method=Radio', function(data) {
let html = data.DATA.map(item => `<div class="play" data-type="${item[4]}" data-src="${item[3]}" data-station="${item[1]}" data-id="${item[0]}"><img src="${item[2]}"></div>`);
$('#radioList').append(html);
lastIDNumberVideo = data.DATA.slice(-1)[0];
loading('hide', 100);
});
}
Branching from a firebase quickstart template for a simple blogger (source: https://github.com/firebase/quickstart-js/tree/master/database)
I am writing data to the firebase DB successfully, and am able to pull and display all values in an HTML element, bar one value which has started returning undefined, despite having data in DB / .json.
Code sample for writing the data to the DB:
// [START write_fan_out]
function writeNewPost(uid, username, picture, title, body) {
var postedDate = moment().format('DD/MM/YYYY');
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
authorPic: picture,
posted: postedDate,
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().child('posts').push().key;
// Write the new post's data simultaneously in the posts list and the user's post list.
var updates = {};
updates['/posts/' + newPostKey] = postData;
//updates['/category/' + title + '/' + newPostKey] = postData;
//updates['/user-posts/' + uid + '/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
}
// [END write_fan_out]
This works without issue. Example of the data written in .json format:
"-KTmYfts6vYEjyjo1rvk" : {
"author" : "Nathan",
"authorPic" : "https://lh4.googleusercontent.com/photo.jpg",
"body" : "Time: 6:00pm\nDuration: 35 seconds\nRecovery: 60 seconds\n",
"posted" : "11/10/2016",
"title" : "Seizure",
"uid" : "rB4n3ELLnFUCWHztHLGA4mVeSHm1"
}
This is correct data as the date is shown under the "posted" tag.
The code for rendering on the page is:
function createPostElement(postId, title, text, author, authorId, authorPic, posted) {
var uid = firebase.auth().currentUser.uid;
var html =
'<div class="post mdl-cell mdl-cell--12-col ' +
'mdl-cell--12-col-tablet mdl-cell--4-col-desktop mdl-grid mdl-grid--no-spacing">' +
'<div class="mdl-card mdl-shadow--2dp">' +
'<div class="mdl-card__title dark-purple mdl-color-text--white">' +
'<h4 class="mdl-card__title-text"></h4>' +
'</div>' +
'<div class="header">' +
'<div>' +
'<div class="avatar"></div>' +
'<div class="username mdl-color-text--black"></div>' +
'</div>' +
'</div>' +
'<div class="date"></div>' +
'<div class="text"></div>' +
'</div>' +
'</div>';
// Create the DOM element from the HTML.
var div = document.createElement('div');
div.innerHTML = html;
var postElement = div.firstChild;
componentHandler.upgradeElements(postElement.getElementsByClassName('mdl-textfield')[0]);
// Set values.
postElement.getElementsByClassName('text')[0].innerText = text;
postElement.getElementsByClassName('mdl-card__title-text')[0].innerText = title;
postElement.getElementsByClassName('date')[0].innerText = posted;
postElement.getElementsByClassName('username')[0].innerText = author || 'Anonymous';
postElement.getElementsByClassName('avatar')[0].style.backgroundImage = `url("${authorPic || './silhouette.jpg'}")`;
This is working for every field but "posted" which returns 'undefined' despite having data in the DB.
Apologies for the blocks of code, each of the write, DB data and present all tie in to why this isn't working, I assume...
I have tested the "posted" data in another field and it displays correctly. I have also used another fields data in the 'date' div which also works correctly.
so somewhere in the pulling from the DB to writing on the page I have broken it.
I want to add my photostream to my website I have tried multiple bits of code
https://gist.github.com/willdurand/5705453 (cant find the set id)
and
jQuery.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729#N22&lang=en-us&format=json&jsoncallback=?", function(data){
jQuery.each(data.items, function(i,item){
jQuery("<img/>").attr("src", item.media.m).appendTo("#images")
.wrap("<a href='" + item.link + "'></a>");
});
});
suppose I need to find id to add the public feed to my photostream?
edit this seems to work but throws a 403.
<script>
jQuery(function(){
var apikey = 'xxxxxxx';
var userid = 'xxxxxx';
jQuery.getJSON('http://api.flickr.com/services/rest/?&method=flickr.people.getPublicPhotos&api_key='+apikey+'&user_id='+userid+'&format=json&jsoncallback=?',
function(data){
jQuery.each(data.photos.photo, function(i,item){
var purl = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_m.jpg';
var pid = item.id;
var container = '<div class="image-container" style="background: url(' + purl+ ');"></div>';
jQuery(container).appendTo('#images');
});
});
});
</script>
this works just have to set the images to public.
I have taken the exact code you have posted below and applied it to a JSFiddle.
jQuery.getJSON("http://api.flickr.com/services/feeds/groups_pool.gne?id=675729#N22&lang=en-us&format=json&jsoncallback=?", function(data){
jQuery.each(data.items, function(i,item){
jQuery("<img/>").attr("src", item.media.m).appendTo("#images")
.wrap("<a href='" + item.link + "'></a>");
});
});
http://jsfiddle.net/mYnQy/
The images are returned correctly and the links are working too, I would imagine that you should check that you have a div with an ID of "images" located on your page and that you have no other javascript that is causing an error on your page.
Check this by using developer tools in your browser of choice and taking a look at the Console.
My below code working well but i need to import XML data from xml URL not from HTML file like this
if i need to retrieve image from XML how i can do that.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(document).ready(function(){
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).find('show').each(function(){
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
//alert($('#show_table').html());
})
all what i need is change this var xml = "9/8 ... " to let the JQuery code read from the ONLINE URL
If you need to load XML data from the URL, you need to execute AJAX request, it may be something like this:
$(function() {
$.ajax({
type: "get",
url: "http://yoursite.com/yourfile.xml",
dataType: "xml",
success: function(data) {
/* handle data here */
$("#show_table").html(data);
},
error: function(xhr, status) {
/* handle error here */
$("#show_table").html(status);
}
});
});
Keep in mind, if you use AJAX you can place .xml file on the same domain name. In other case you need to set up cross-origin resource sharing (CORS).
EDITED:
I modified your code, now it appends td element to your table. But xml is still inside html.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>"
$(function() {
$(xml).find('show').each(function() {
console.log(this);
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append($(html));
});
});
But you need to modify your html file, check my solution here: http://jsfiddle.net/a4m73/
EDITED: full solution with loading xml from URL
I combined two parts described above, check here: http://jsfiddle.net/a4m73/1/
Use jquery-xpath, then you can easily do what you want like:
$(xml).xpath("//shows/show");
if you want know more about xpath just take a look on XML Path Language (XPath) document.
var xml = "<shows><show><date>9/8</date><place>Toads Place</place><location>New Haven, CT</location><time>9PM</time></show></shows>";
$(document).ready(function () {
//$('#table').append('<h2>SHOWS</h2>');
$('#table').append('<table id="show_table">');
$(xml).xpath("//shows/show").each(function () {
var $show = $(this);
var date = $show.find('date').text();
var place = $show.find('place').text();
var location = $show.find('location').text();
var time = $show.find('time').text();
var html = '<tr><td class="bold">' + date + '</td><td class="hide">' + place + '</td><td>' + location + '</td><td class="bold">' + time + '</td></tr>';
$('#show_table').append(html);
});
})
I have the following code below which returns some results when the user searches a term.
Once i get some results,I want to add feature which will allow me to get more data when scrolling down ward?
NOTE: I dont want to use any plugin(s).
$(document).ready(function() {
$("#submit").click(function (event) { // wire up this as an onclick event to the submit button.
var searchTerm = $("#search").val(); // get the user-entered search term
var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
//var URL = "http://api.flickr.com/services/feeds/photos_public.gne";
var ID = "25053835#N03";
//var MYID-"84215563#N08";
//var tagmode="&tagmode=any";
//var format ="&format=json";
var tags="&tags="+ searchTerm;
var tagmode="&tagmode=any";
var jsonFormat = "&format=json&jsoncallback=?";
var ajaxURL= URL+"?jsoncallback=?id="+ID+tags+tagmode+jsonFormat;
//var ajaxURL= URL+"?"+tags+tagmode+jsonFormat;
$.getJSON(ajaxURL,function(data){
//$("h1").text(data.title);
//alert(data.length);
var photoHTML;
$("#photos").empty();
if (data.items.length) {
alert(data.items.length);
$.each(data.items, function(i,photo) {
//var photoHTML = "<h4>" +photo.tags + "</h4>";
photoHTML = "<p>";
photoHTML += '<a href="' + photo.link + '">';
photoHTML += '<img src="' + photo.media.m + '" alt="' + photo.media.m + '" title="' + photo.media.m + '"></a>';
photoHTML = "</p>";
$('#photos').append(photoHTML).fadeIn(200);
});
} else {
alert(data.items.length);
photoHTML = "<h2> No Results</h2>";
$('#photos').append(photoHTML).fadeIn(200);
}
//$('#photos').append(photoHTML).fadeIn(200);
});
});
});
You could use the jquery .scroll() method. You have two options, save all data when page loads then display as user scrolls OR make ajax request every time there is a scroll down request.
$("#yourSelector").on('scroll', function(){
// do stuff
});
or simply using the shortcut:
$("#yourSelector").scroll(function(){
// do stuff
});
I hope this helps!
Here is a link to jquery scroll api to know about the options (such as specifying scroll DOWN): http://api.jquery.com/scroll/
You can also bind scroll event using jquery:
Put your whole code into a function:
function myfun(){
//-- you code
}
and call myfun() from both event:
on click event-
$("#submit").click(function (event) {
myfun();
});
on scroll event -
$("#yourSelector").scroll(function(){
myfun();
});