JS events source detection - javascript

I'm working on a part of my web site where people can vote on publications, I have many in the same page, and next every publication there are two images one to agree and the other to disagree. I want to change the images, so when someone votes, whether agree or not, the image changes to say he already voted.
Here's my code:
JPS:
<logic:iterate id="comment" name="Liste_Comments" scope="request">
<html:img src="pages/images/ok.png" alt="Vote pour!" paramId="code" paramName="comment" paramProperty="code" onclick="voterComment('pour');"/>
<html:img src="pages/images/ko.png" alt="Vote contre!" paramId="code" paramName="comment" paramProperty="code" onclick="voterComment('contre');"/>
<bean:write name="comment" property="libelle" />
<bean:write name="comment" property="subject" />
<br>
</logic:iterate>
Script:
<script type="text/javascript">
function voterComment(vote) {
var url = "<%=request.getContextPath()%>/VoteComment.do";
new Ajax.Request(url, {
parameters: {vote: vote},
onSuccess: function(transport, json) {
if (json.error) {
alert(json.error);
}
else{
window.event.srcElement.src = "pages/images/photo.jpg";
}
}
});
}
</script>
I have a problem to access to the image that was clicked!!
Thanks guys, in advance, for your great helping :)

You can change you html to send the value of this to the click handler. This will contain a reference to the source element - in this case the image that was clicked.
<html:img ... paramProperty="code" onclick="voterComment(this, 'pour');"/>
Javascript:
function voterComment(sourceImage , vote) {
var url = "<%=request.getContextPath()%>/VoteComment.do";
new Ajax.Request(url, {
parameters: {vote: vote},
onSuccess: function(transport, json) {
if (json.error) {
alert(json.error);
}
else{
sourceImage.src = "pages/images/photo.jpg";
}
}
});
}

Related

Add a javascript result to an image url

So what im trying to do is query a Minecraft server with javascript, and with the response i get back with the api, i want to grab the .playerlist and put the response in this url (https://cravatar.eu/avatar/ {name} /100.png) for each person connected
If someone knows a better way to achieve this, i would very much appreciate your input!
Im also pretty new to javascript, so not fully know what im doing :/
Heres the HTML that i have (i know it may be messy, its also not fully my code)
<div class="card"> <div class="icon"><img src="https://cdn.worldvectorlogo.com/logos/minecraft-1.svg"></div><div class="header">
<div class="image"> <img src="https://res.cloudinary.com/lmn/image/upload/e_sharpen:100/f_auto,fl_lossy,q_auto/v1/gameskinnyc/u/n/t/untitled-a5150.jpg" alt="" /> </div>
<h2>Server Status</h2>
</div>
<div id="rest">Loading...</div>
<img src="https://cravatar.eu/avatar/" $face "/>
</div>
And here is the javascript
//Query api at this address
var url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, function(r) {
//data is the JSON string
if(r.error){
$('#rest').html('Server Offline.');
return false;
}
var p1 = '';
if(r.Players > 0 ){ p1 = '<br>'+r.Playerlist; }
// Text to display below
$('#rest').html('Total Online: '+r.Players+p1);
// Trying to add playerlist to html url
$('#face').html+p1;
});
Since you've pasted jQuery code, I'll submit my answer in jQuery. However, I do recommend you learn primitive JavaScript and not focus your attention just on jQuery... it's become something of a meme on StackOverflow.
Starting off, you really should be wrapping your code in $(document).ready this'll only run the code when the page has loaded.
$(document).ready(() => {
// The document is ready, let's run some code!
});
Then add your AJAX request as normal inside this bracket.
$(document).ready(() => {
let url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, response => {
});
});
Okay, whilst writing this, I checked the URL provided by OP and saw that it was timing out so I've grabbed a sample response from the Minetools' documentation.
{
"MaxPlayers": 200,
"Motd": "A Minecraft Server",
"Playerlist": [
"Connor",
"Kamil",
"David"
],
"Players": 3,
"Plugins": [],
"Software": "CraftBukkit on Bukkit 1.8.8-R0.2-SNAPSHOT",
"Version": "1.8.8",
"status": "OK"
}
So in your JSON response, you can see that Playerlist is a array which can contain multiple things in one variable. You can also iterate through an array, which is what we'll be doing to build the image URLs.
We iterate through an array using forEach.
$(document).ready(() => {
let url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, response => {
response.Playerlist.forEach(playerName => {
console.log(playerName);
});
});
});
//Console:
//Connor
//Kamil
//David
Now that we're iterating through the player list we can start assembling the URLs for these images and adding them to your document's body.
I've cleaned up your HTML, take note of the new div#user-images I've added. This'll be the place where jQuery will add your images from the forEach loop.
<div class="card">
<div class="icon">
<img src="https://cdn.worldvectorlogo.com/logos/minecraft-1.svg">
</div>
<div class="header">
<div class="image">
<img src="https://res.cloudinary.com/lmn/image/upload/e_sharpen:100/f_auto,fl_lossy,q_auto/v1/gameskinnyc/u/n/t/untitled-a5150.jpg" alt="" />
</div>
<h2>Server Status</h2>
</div>
<!-- This div tag will need to hide when there is no error, or say when there is. -->
<div id="rest">Loading...</div>
<!-- The user images will be added inside this div. -->
<div id="user-images"></div>
</div>
Now we have our HTML ready we can start using the jQuery function appendTo to add elements into our div#user-images.
$(document).ready(() => {
let url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, response => {
response.Playerlist.forEach(playerName => {
$(`<img src="https://cravatar.eu/avatar/${playerName}" />`).appendTo("#user-images");
});
});
});
Your div#user-images should start filling up with the images of players from the Playerlist array.
I noticed you added a simple way of showing whether or not there's an error with the API. We can interact with div#rest to show/hide or change text depending on the success of the response.
$(document).ready(() => {
let url = "https://api.minetools.eu/query/play.aydaacraft.online/25565";
$.getJSON(url, response => {
if(response.error){
$("#rest").html("The server is offline!");
}else{
//There is no error, hide the div#rest
$("#rest").hide();
response.Playerlist.forEach(playerName => {
$(`<img src="https://cravatar.eu/avatar/${playerName}" />`).appendTo("#user-images");
});
}
});
});
And that's it really. I hope this gives you some understanding of arrays, and iterating through them, as well as some DOM functions from jQuery.

Where do I put this function in my code? jQuery

Okay, so for class I have to make a CRUD application basically. I have to have a nav bar that links to different "pages" that are loaded in using a server.js file. In that server is where I load a JSON file that holds two arrays, one for pages, or sections, and another for users. The goal is to input information about a user in one section, hit a button and then that user's info will be listed in a different section. You also need to be able to delete each individual user at will, and it's all local.
My problem is that I have this addUser function, and within this function there's a click listener for the add button. Right now, the only thing it does when it's supposed to be clicked it throws a console.log, but I can't get that to work. The addUser function also has a console.log that's running fine, and I believe that my problem is that I don't know where I'm supposed to be adding the addUser function into my code. Just to be safe, I'll go ahead and list all my code. First is the server.js:
var SERVER = (function(){
//variable to store data.users into
var _userData = [];
var _sectionData = [];
//getting the data and putting it into the variables above
var _loadData = function(){
$.getJSON("./data/data.json", function(data){
_userData = data.Users;
_sectionData = data.Sections;
//console.log(_sectionData);
})
}
var _showData = function(){
return _userData;
}
var _getSection = function(sectionYouWant){
let sec = {};
$.each(_sectionData, function(idx, section){
if(section.sectionName == sectionYouWant){
sec = section.sectionContent;
}
});
return sec;
}
_loadData();
return {
loadData: _loadData,
showData: _showData,
getSection: _getSection
}
})()
next is the app.js
function addUser(){
console.log("firing addUser");
$('#addButton').click(function(e){
console.log("are you working????")
e.preventDefault();
})
}
function initNavListeners(){
$("#home").click(function(e){
//console.log('click home');
var sectionData = SERVER.getSection('home');
$('.wrapper').html(sectionData);
});
$("#view").click(function(){
//console.log('click view users');
var userData = SERVER.showData();
var sectionData = SERVER.getSection('view');
$(".wrapper").html(sectionData);
function showUsers(){
$.each(userData, function(idx, user){
$(".wrapper").append(`
<br/><p><b>Name:</b> ${user.fName} ${user.lName}</p>
<p><b>Email Address:</b>
${user.email}</p>
<p><b>Twitter Handle:</b>
${user.twitter}</p>
<button class="delete" id=${idx}>DELETE</button><br/>`)
})
}
showUsers();
});
$("#register").click(function(e){
//console.log('click register');
addUser();
var sectionData = SERVER.getSection('register');
$('.wrapper').html(sectionData);
});
}
$(document).ready(function(){
SERVER.loadData();
initNavListeners();
var sectionData = SERVER.getSection('home');
$('.wrapper').html(sectionData);
})
Finally, the JSON:
{
"Users": [
{
"fName": "Andrea",
"lName": "Trigg",
"email": "at#users.com",
"twitter": "#at"
}
],
"Sections": [
{
"sectionName": "home",
"sectionContent": "<h1>HOME</h1><p>Welcome to the home page for my Homework 5 assignment! In this little application, you can register users and it will be submitted to a local JSON file. Then when you go to the view users page, it will show all the current users registered. You can also delete each individual user by pressing the \"delete user\" button below their information.</p><p>I hope this will work on your machine because it definitely works on mine!</p><p>I'm honestly not sure what else I should put here, so have a gif of a cute kitten trying to eat their own tail.</p><img src=\"https://i.pinimg.com/originals/84/c8/ba/84c8bab01787f2ee1ebef1378e9e8444.gif\"><p>I hope you have a great week! Thank you for taking a look at my Homework 5!</p>"
},
{
"sectionName": "view",
"sectionContent": "<h1>VIEW USERS</h1><p>Scroll below to see all users stored in the database. Click the delete button to delete a user from the database (careful, you won't get the information back if you delete!)</p>"
},
{
"sectionName": "register",
"sectionContent": "<h1>REGISTER</h1><p>Register a new user by using the form below!</p><form><input id=\"first\" type=\"text\" value=\"\" placeholder=\"First Name:\"><br/><input id=\"last\" type=\"text\" value=\"\" placeholder=\"Last Name:\"><br/><input id=\"emailAddress\" type=\"text\" value=\"\" placeholder=\"Email:\"><br/><input id=\"twitterHandle\" type=\"text\" value=\"\" placeholder=\"Twitter Handle\"><br/><input id=\"addButton\" type=\"button\" value=\"SUBMIT\"></form>"
}
]
}
If you see anything that could be causing my click listener to not be working while the function itself is, that would be a tremendous help. I'm really struggling with this so any help would be great! Thank you!
Wow okay so after working on this for three hours, I finally figured it out.
So basically, you take the addUser function and instead of having it be global, you put it into the #register click listener that's in the initNavListener. It should look something like this:
$("#register").click(function(e){
//initListeners();
//console.log('click register');
var userData = SERVER.showData();
var sectionData = SERVER.getSection('register');
$('.wrapper').html(sectionData);
function addUser(){
console.log("firing addUser");
$('#addButton').click(function(e){
console.log("are you working????")
e.preventDefault(); )}
I feel like the biggest idiot right now :'D
ETA: If anyone wants to help me figure out how to delete these users that would be cool, but it's not listed in the rubric as something that I need to do, so I'm not putting major emphasis on it atm.

RESTLET - Angular.JS File Upload on Client Side

We are using Restlet for our API on the client side, everything server side is written in Laravel 5. We are having trouble in one portion. We have a couple endpoints that require you to upload a file. In Angular, I have only gotten that to work using the following method thus far:
var fd = new FormData();
fd.append('image', $scope.file);
$http.post(apiURL + "/upload", fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}).then(function(response) {
//yay it worked
}, function(response) {
//try again
});
I don't know why that is the only way I have been successful, but I would like to change it over to the Restlet endpoint I have created. For most of my calls, it is as simple as this:
$rootScope.restlet.getCompanyAll().then(function(response) {
$scope.companies = response.data;
});
and
var config = {
params: {
start: "2016-01-01",
end: "2016-01-31"
}
};
var id = 1;
$rootScope.restlet.getCompanyStatsCompany_id(id, config).then(function(response) {
$scope.companies = response.data;
});
Pretty simple, but when I try to implement the post of an image, it doesn't recognize it, and leaves the image out completely. Here is the code I am attempting to use, it works with the non-Restlet way, but doesn't work with Restlet.
var config = {
params: {
name: $scope.newCompany.name,
rep_id: $scope.newCompany.rep_id,
image: $scope.image_input
}
};
var id = 1;
$rootScope.restlet.postCompanyCreate(config).then(function(response) {
$scope.companies = response.data;
});
Has anyone gotten something like this to work? And if so, how does it work? Thanks! :)
EDIT 1:
Here is the HTML of the page I have set up. It does have a file input, but for some reason it Restlet doesn't like the file. I have tried a plain file input, along with an input with a directive on it. The current version I am using is an image, that when clicked is linked to an file input that is hidden. I am also using a custom directive on it currently.
HTML:
<div class="modal-body">
<form ng-submit="createCompany()">
<!-- OTHER FORM STUFF GOES HERE -->
<div class="col-sm-12">
<img src="" id="imagePreview" onClick="$('#imageUpload').trigger('click');" style="max-width: 100%;" />
<input type="file" style="display: none;" id="imageUpload" file="file" />
</div>
<!-- FORM SUBMIT AND RESET BUTTONS HERE -->
</form>
</div>
Custom Directive:
app.directive('file', function() {
return {
scope: {
file: '='
},
link: function(scope, el, attrs) {
el.bind('change', function(event) {
var file = event.target.files[0];
scope.file = file ? file : undefined;
scope.$apply();
});
}
};
});
You didn't post your HTML but I assume that you are using an input with a type of file to specify the file to upload and binding to it with ng-model or some native Angular binding mechanism. I have no idea why, but Angular doesn't support this. There are 2 common ways to implement this.
The 1st is to use a directive that works around this issue. There's one here: https://github.com/danialfarid/ng-file-upload.
The 2nd, and at least where I would start, is you can simply use document.getElementById to retrieve the file name from the input in your controller. IOW, $scope.file = document.getElementById("myFileThingy").value.

Loading specific div based on the results of multiple dropdowns

EDIT: Would the approach be much easier if the Javascript listed was removed completely, and the dropdown menus restyled as <div>'s within <li>'s, and the final div was generated by a Javascript onclick event? e.g.
<a id="click_link">click me</a>
$("#click_link").click(function(){
$('#div').load('http://www.link.com/');
});
Either way, the problem at hand...
My decision to use an elegant-looking javascript solution is highlighting my massive inexperience when it comes to javascript! The problem is, on the face of it, simple...
Once an option has been chosen on each of the dropdown menus, I need a final div to load so that a specific button can be shown (a link to buy the item with the specified options, e.g. choosing Necklace D, with Stone Option B, and Delivery Option A = loading div with 'Buy' Button #17)
The dropdowns are divs that are filled and styled through the Javascript (as opposed to using the simpler <form> and <input> method), giving the flexibility to add two lines of differently styled text for each option etc. - This is where I step into the realm of the unknown and my inexperience shines through.
The isolated section is viewable in its entirity here
Ok, to the code.
Here's the Javascript:
function createByJson() {
var pearlData = [
{description:'Choose your pearl...', value:'Pearls', text:'Pearls'},
{description:'Beautiful black stone', value:'Black Pearl', text:'Black Pearl'},
{description:'Classic white stone', value:'White Pearl', text:'White Pearl'}
];
$("#DropItPearls").msDropDown({byJson:{data:pearlData, name:'pearls', width: 200}}).data("dd");
var blodeuweddData = [
{description:'Choose your item...', value:'Blodeuwedd', text:'the Blodeuwedd Collection'},
{description:'A striking statement', value:'BlodeuweddCelticStatement', text:'Celtic Statement Piece'},
{description:'Gold laced flower and pearl', value:'BlodeuweddBracelet', text:'Bracelet'},
];
$("#DropItBlodeuwedd").msDropDown({byJson:{data:blodeuweddData, name:'blodeuwedd', width: 250}})
.msDropDown({on:{change:function(data, ui) {
var val = data.value;
if(val!="")
window.location = val;
}}}).data("dd");
var deliveryData = [
{description:'Choose your method...', value:'Delivery', text:'Delivery Options'},
{description:'4-6 weeks delivery', value:'Four Weeks', text:'Made To Order'},
{description:'(unavailable on this item)', value:'Rush', text:'Express Delivery', disabled:true}
];
$("#DropItDelivery").msDropDown({byJson:{data:deliveryData, name:'delivery', width: 200, selectedIndex: 1}}).data("dd");
paymentData = [
{ description:'How would you like to pay?', value:'Payment', text:'Payment Method'},
{image:'images/msdropdown/icons/Visa-56.png', description:'Secure online payment', value:'Visa', text:'Visa'},
{image:'images/msdropdown/icons/Paypal-56.png', description:'Secure online payment', value:'Paypal', text:'Paypal'},
{image:'images/msdropdown/icons/EmailPay-56.png', description:'Order by email', value:'Email Payment', text:'Send Your Details'},
{image:'images/msdropdown/icons/Mastercard-56.png', description:'(coming soon)', value:'Mastercard', text:'Mastercard', disabled:true},
{image:'images/msdropdown/icons/Collect-56.png', description:'(coming soon)', value:'Collection', text:'Order and Collect', disabled:true},
{image:'images/msdropdown/icons/Email-56.png', description:'email Menna', value:'Other Method', text:'Alternatives'}
];
$("#DropItPayments").msDropDown({byJson:{data:paymentData, name:'payments', width: 250}}).data("dd");
}
$(document).ready(function(e) {
//no use
try {
var pages = $("#pages").msDropdown({on:{change:function(data, ui) {
var val = data.value;
if(val!="")
window.location = val;
}}}).data("dd");
var pagename = document.location.pathname.toString();
pagename = pagename.split("/");
pages.setIndexByValue(pagename[pagename.length-1]);
$("#ver").html(msBeautify.version.msDropdown);
} catch(e) {
//console.log(e);
}
$("#ver").html(msBeautify.version.msDropdown);
//convert
$("select").msDropdown();
createByJson();
$("#tech").data("dd");
});
function showValue(h) {
console.log(h.name, h.value);
}
$("#tech").change(function() {
console.log("by jquery: ", this.value);
})
//
And the html:
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Item</p></div>
<div id="DropItBlodeuwedd"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Precious Stones</p></div>
<div id="DropItPearls"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Payment</p></div>
<div id="DropItPayments"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Delivery</p></div>
<div id="DropItDelivery"></div>
</div>
<div id="dropOptions">
<div id="dropOptionsTitle"><p>Buy Now!</p></div>
<div id="DropItBuy"></div>
</div>
Again, working version viewable here
Many thanks in advance!
What I think you want is for your Buy button to dynamically read what the dropdowns currently say and build a link for redirection based on that, rather than trying to update the Buy button every time a dropdown changes.
From your code I can't see what the form of the final URL is supposed to be. For example, to get the current value of the delivery option, you can check $('#DropItDelivery :selected').text() which will be something like "Made To Order".
Your Buy Now! could be a button with a click event that reads these values and constructs the URL with basic string concatenation, e.g.:
window.location = "buynow.html?delivery=" + $('#DropItDelivery :selected').text() +
"&payment=" + $('#DropItPayments :selected').text()
// etc.
Of course you'd have to handle these options on the server.
In case you want to redirect to the payment page of the processor, you can just branch based on the payment method and give them the URL you want based on that.
var pm = $('#DropItPayments :selected').text();
if (pm == "Visa")
{
// Visa payment URL construction
}
else if (pm == "Send Your Details")
{
// Send your details URL construction
}
// etc.

Using Shoutcast, Display Now Playing Album Art

I have a small 70x70 box in an HTML player I built where I wish to place in the album artwork to coincide with my now playing information from my shoutcast server. Is there a way, using the artist-song information the shoutcast server provides, that I can search a web service (amazon/last.fm) and have it place the (most likely) album cover there?
Here is the JS code I'm using now:
jQuery(document).ready(function() {
pollstation();
//refresh the data every 30 seconds
setInterval(pollstation, 30000);
});
// Accepts a url and a callback function to run.
function requestCrossDomain( callback ) {
// Take the provided url, and add it to a YQL query. Make sure you encode it!
var yql = 'http://s7.viastreaming.net/scr/yql.php?port='+port+'&username='+user+'&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
jQuery.getJSON( yql, cbFunc );
function cbFunc(data) {
// If we have something to work with...
if ( data ) {
// Strip out all script tags, for security reasons. there shouldn't be any, however
data = data[0].results.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
data = data.replace(/<html[^>]*>/gi, '');
data = data.replace(/<\/html>/gi, '');
data = data.replace(/<body[^>]*>/gi, '');
data = data.replace(/<\/body>/gi, '');
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
}
function pollstation() {
requestCrossDomain(function(stationdata) {
var lines = stationdata.split('|+|');
jQuery('#sname').html(lines[0]);
jQuery('#sgenre').html(lines[1]);
jQuery('#clisteners').html(lines[2]);
jQuery('#bitrate').html(lines[3]);
jQuery('#artist_block').html('' + jQuery.trim(lines[4]) + '');
var prev = lines[5].split('+|+');
jQuery('#np_table').html('');
for (var i = 0; i < 8; i++)
{
if(typeof(prev[i]) != 'undefined')
{
jQuery('#np_table').append('<tr>'+'<td>'+ prev[i] + '</td>'+'</tr>');
jQuery("tr:odd").css("background-color", "#154270");
}
}
jQuery('#mplayers').html(lines[6]);
jQuery('#mobile').html(lines[7]);
jQuery();
} );
}
and here's the HTML:
<div id="col_left">
<div id="now_playing">
<div id="np_ribbon"><span>Now Playing</span></div>
<div id="np_img"><img name="nowplayingimage" src="" width="70" height="70" alt="album cover" style="background-color: #000000" /></div>
<div id="artist_block">
<span class="artist_name"><strong>Artist:</strong> Artist name</span><br />
<span class="song_name"><strong>Song:</strong> "song title"</span><br />
<span class="album_name"><strong>Album:</strong> Album Name</span> <br />
</div>
<div id="player">
<div id="container"><script type="text/javascript" src="http://shoutcast.mixstream.net/js/external/flash/s7.viastreaming.net:8790:0:::999999:::1"></script></div>
</div>
</div><!-- end now playing -->
<div id="recent">
<div class="table_title">Recently Played</div>
<table id="np_table">
</table>
</div><!-- end recent -->
</div><!-- end col_left -->
So naturally, I want the image to appear where the div "np_img" is. Any ideas what code to use and how to implement it. You can probably tell by my code that I'm an amateur so please be clear and gentle. :)
You can use the iTunes search API. It supports JSONP so you can use it directly within your webpage, without worrying about cross-domain.
As #Brad mentioned, iTunes has terms of use. In particular:
(...) provided such Promo Content: (i) is placed only on pages that promote
the content on which the Promo Content is based; (ii) is proximate to
a "Download on iTunes" or "Available on the App Store" badge (as
approved by Apple) that acts as a link directly to pages within iTunes
or the App Store where consumers can purchase the promoted content. (...)
Here's how the code looks like:
​function refreshArtwork(artist, track) {
$.ajax({
url: 'http://itunes.apple.com/search',
data: {
term: artist + ' ' + track,
media: 'music'
},
dataType: 'jsonp',
success: function(json) {
if(json.results.length === 0) {
$('img[name="nowplayingimage"]').attr('src', '');
return;
}
// trust the first result blindly...
var artworkURL = json.results[0].artworkUrl100;
$('img[name="nowplayingimage"]').attr('src', artworkURL);
}
});
}

Categories

Resources