Consider the following script which is used for counting twitter followers. For some reason I get the list twice. I just want the follower count stats for the elements in the array. Any help is greatly appreciated.
echo "<div id='twitter'>
<script type='text/javascript'>
$(document).ready(function(){
var i;
twitterusername = ['Sinbg','followfog','miniclip','vgames'];
for(i=0; i<4; i++){
(function(i){
$.getJSON('http://twitter.com/users/' + twitterusername[i] + '.json?callback=?',
function(data){
$('#twitter').html( document.getElementById('twitter').innerHTML + twitterusername[i] + ' ' +
data.followers_count + ' Followers' + '<br/>');
}
) // end getJSON
})(i);
}// end for??
});</script></div>";
Move the script-tag out of the twitter-div.
Here the example with the script inside.
Here with the script after the div.
I can't reproduce the error with the code you've posted:
http://jsfiddle.net/mLCHX/
You might want to check your php code to see if you are outputting the javascript twice.
Another option would be to clear the contents of #twitter before getting the info.
Related
I'll try to keep this simple and clear. I'm pretty new to using API's but I'm using the Flickr API to search for and display photos on my website based on a certain tag. For a simple, static web page this is quite simple and I've already got it working as intended. This is the jquery script I found to use:
$(function() {
var apiKey = 'MY_API_KEY_IS_IN_HERE';
var tag = '%23FFLIVE2014-09-03';
var perPage = '25';
var showOnPage = '6';
$.getJSON('http://api.flickr.com/services/rest/?format=json&method='+
'flickr.photos.search&api_key=' + apiKey +
'&tags=' + tag + '&per_page=' + perPage + '&jsoncallback=?',
function(data){
var classShown = 'class="lightbox"';
var classHidden = 'class="lightbox hidden"';
$.each(data.photos.photo, function(i, rPhoto){
var basePhotoURL = 'http://farm' + rPhoto.farm + '.static.flickr.com/'
+ rPhoto.server + '/' + rPhoto.id + '_' + rPhoto.secret;
var thumbPhotoURL = basePhotoURL + '_s.jpg';
var mediumPhotoURL = basePhotoURL + '.jpg';
var photoStringStart = '<a ';
var photoStringEnd = 'title="' + rPhoto.title + '" href="'+
mediumPhotoURL +'"><img src="' + thumbPhotoURL + '" alt="' +
rPhoto.title + '"/></a>;'
var photoString = (i < showOnPage) ?
photoStringStart + classShown + photoStringEnd :
photoStringStart + classHidden + photoStringEnd;
$(photoString).appendTo("#flickr");
});
$("a.lightbox").lightBox();
});
});
Create a #flickr div on a page and load that script, photos tagged #FFLIVE2014-09-03 would be displayed, if there are any. My problem is that the site/page I want to show the photos on is dynamic with data generated from a database. So website.com/page.php is the single page, in the database is data for a certain date and a performance that happened on it (For a band).
So what I'm struggling with is how to dynamically edit the tags searched for in the script. With the above script placed in my page.php obviously page.php?id=1 and page.php?id=261 will show the same photos, because the tags searched will be the same when in fact they should be different, based on the date for the data.
So, is there some way to do this? Generate the correct date tag to search for based on the database data? I can generate the correct tag inside the PHP file itself quite easily, just echo the first part of the tag then the date. But how would I do that in relation to the javascript? I gather it is possible to use PHP within Javascript but that would be outside the database, so it wouldn't know what it was generating.
I hope that makes sense!
i have jquery syntax to consume json list from database.
here's the code
$(document).ready(function () {
//function to get the result from user-input
$("#btnsearch").click(function() {
$("#posting").html("");
//show the div section
$("#divContent").show("slow", function(){
//getting value from searchbox
valobj = $('#search_box').val();
//execute data from database.
$.getJSON("search.php", { q : valobj }, function(data,result){
//show result from database
$.each(data.content, function(index, value) {
var li = $("<li><h3></h3><p></p></li>");
$("#posting").append(li);
$("h3",li).text("<a href='post.php?id='>" + value.title + "</a>");
$("p",li).text(value.intro_text);
});
//end show result
}, JSON);
}); //end show div section
}); //end click function
As you can see above, i need to place anchor to post title, so when user click it, it will redirect to another page
$("h3",li).text("<a href='post.php?id='>" + value.title + "</a>");
But it is not working and shows a result to browser example: Test Post 100
how to properly insert anchor on the jquery function?
thanks in advance.
use .html()
$("h3",li).html("<a href='post.php?id='>" + value.title + "</a>");
From the API :
We need to be aware that this method (.text()) escapes the string provided as
necessary so that it will render correctly in HTML. To do so, it calls
the DOM method .createTextNode(), does not interpret the string as
HTML
http://api.jquery.com/text/
http://api.jquery.com/html/
I have the code to dynamically generate the textboxes. I want to multiply the values of quantity and rate textboxes and display the result in total textbox and post it to next page.
The fiddle http://jsfiddle.net/hEByw/ that shows how textboxes are dynamically generated.
I have tried the following part of code to multiply the two textbox values but its not working for me. please see the fiddle for complete code.
//To multiply two textbox values
$('#qty + counter + ').keyup(calculate);
$('#rates + counter + ').keyup(calculate);
function calculate(e)
{
$('#total + counter + ').val($('#qty + counter +').val() * $('#rates + counter+').val());
}
Can any one suggest where am I going wrong or the correct way of doing it. I am new to jquery. Any help is appreciated.Thanks in advance.
I think the problem is here
$('#rates + counter + ')
It should be made to
$('#rates' + counter)
EDIT :
I analysed it with jsfiddle but the problem is with your logic. How can you get the counter when you are pressing a key. Counter will be used and it will be undefined once the controls are added.
Edit 2 :
At last I came up with the answer.
I had to tweak around a bit but that i hope it will satisfy you
Check This JsFiddle Link
Sorry for editing your own link
I just added a title attribute and i used it instead of the counter variable.
e.target.title For the counter
title = '+ counter + ' in your HTml
Refer the link. Hope this helps you
As long as you are using jquery 1.4+:
$('#qty' + counter).live('keyup', function(){ calculate(counter); });
$('#rates' + counter).live('keyup', function(){ calculate(counter); });
function calculate(counter)
{
total = Number($('#qty' + counter).val())*Number($('#rates' + counter).val())'
$('#total' + counter).val(total);
}
You never know the value of counter when the event triggers.
$('#qty' + counter).on("blur", function() {
calculate($(this));
});
$('#rates' + counter).on("blur", function() {
calculate($(this));
});
function calculate(el) {
var counter = el.attr("id").indexOf("qty") != -1 ? el.attr("id").substring(3) : el.attr("id").substring(5);
var qty = isNaN(parseInt($('#qty' + counter).val())) ? 0 : parseInt($('#qty' + counter).val());
var rate = isNaN(parseInt($('#rates' + counter).val())) ? 0 : parseInt($('#rates' + counter).val());
$("#total" + counter).val(qty * rate);
}
See this form - http://schnell.dreamhosters.com/form.php
This form has a portion of it where you enter data and can choose to add more of the same data by clicking a button called 'Add A Site' and it will make another of that section to enter another site. This is the jQuery that performs the duplication...
$(function () {
var sites = 1;
var siteform = $("#site1").html();
$(".addsites").live("click", function(e) {
e.preventDefault();
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<br /><hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />"
+ "<button class='addsites'>Add Another Site</button>"
+ "</center></div>");
});
$(".removesites").live("click", function(e) {
e.preventDefault();
var id = $(this).attr("title");
$("#" + id).remove();
});
});
The duplication works perfectly, but one thing that's bugging me is that when I have to enter data for someone claiming a LOT of sites, it gets very annoying having to repeat same or similar parts of this section of the form (like every site is in the same city, on the same day, by the same person, etc.) So I had the idea that with each duplication, the values of the form elements would also carry over and I just edit what's not the same. The current implementation only duplicates the elements, not the data. I'm not sure how to easily copy the data into new sections, and I can't find any jQuery tools to do that.
PS - This part isn't as important, but I've also considered using this same form to load the data back in for viewing/editing, etc. The only problem with this is that the reprinting of the form means that there will be a form section with the id "Site7" or something, but jQuery starts its numbering at 1, always. I've thought about using selectors to find the highest number site and start off the variable 'sites' at that number, but I'm not sure how. Any advice how to do this, or a better system overall, would be much appreciated.
You want to itterate over the input fields in siteform and store them in an object using their name attribute as a key.
Then after the duplication of the object you made and look for the equivelant fields in the new duplicated form ans set their values.
Somthing like this (not tested, just the idea)
var obj = new Object();
$("#site1 input").each(function(){
obj[this.id] = this.value;
);
// Dupicate form
$.each(obj, function(key, value){
$('#newform input[name="'+key+'"]').value = value;
});
Mind you these two each() functions differ from each other.
http://api.jquery.com/jQuery.each/
http://api.jquery.com/each/
You could consider using cloneNode to truely clone the previous site-div and (by passing true to cloneNode) all of its descendants and their attributes. Just know that the clone will have the same id as the original, so you'll have to manually set its id afterwards
Try this in your click-function
var clone = $("#site" + sites).clone(true, true); // clone the last div
sites++; // increment the number of divs
clone.attr('id', "site" + sites); // give the clone a unique id
$("#events").append(clone); // append it to the container
As Scuzzy points out in a comment jQuery does have its own clone() method (I don't use jQuery much, so I didn't know, and I didn't bother to check before answering). Probably better to use jQuery's method than the built-in cloneNode DOM method, since you're already using jQuery for event listeners. I've updated the code
The query to transfer values is quite simple (please, check the selector for all the right types on the form):
$("#site1").find("input[checked], input:text, input:hidden, input:password, input:submit, option:selected, textarea")
//.filter(":disabled")
.each(function()
{
$('#site2 [name="'+this.name+'"]').val(this.value);
}
Ok I finally figured this out. It's, more or less, an expansion on Alex Pakka's answer.
sites++;
$("#events").append("<div id='site" + sites + "'>"
+ "<hr><br />"
+ siteform
+ "<center><button class='removesites' title='site"
+ sites + "'>Remove This Site</button><br />");
$("#site1").find("input:checked, input:text, textarea, select").each(function() {
var name = $(this).attr("name");
var val = $(this).val();
var checked = $(this).attr("checked");
var selected = $(this).attr("selectedIndex");
$('#site' + sites + ' [name="'+name+'"]').val(val);
$('#site' + sites + ' [name="'+name+'"]').attr("checked", checked);
$('#site' + sites + ' [name="'+name+'"]').attr("selectedIndex", selected);
});
I used extra vars for readability sake, but it should do just as fine if you didn't and used the methods directly.
Dont forget to create a function for registering the event! Its very important because when the DOM is loaded, all new attributes need to be registrated to the DOM.
Small example:
<script>
$(document).ready(function(){
$('#click-me').click(function(){
registerClickEvent();
})
function registerClickEvent(){
$('<input type="text" name="input_field_example[]">').appendTo('#the-div-you-want')
}
registerClickEvent();
})
</script>
I have a checkbox on a webpage that when you click it, updates the value in the database as well as the editedBy and editedDate columns in a table in the database. I am doing the update via an ajax call to a php page. I am trying to get the updated editedDate and editedBy data in the callback on success so i can update the sorresponding span tags that hold this information. I'm trying to use jQuery to accomplish this. This is what i have so far:
var updateUserDate = function(data){
var table = data.table;
var rowId = data.rowId;
var editedDate = data.editedDate;
var editedBy = data.editedBy;
//alert(table+' - '+rowId+' - '+editedDate+' - '+editedBy);
$('"#'+table+' .row'+rowId+' .newEditedDate"').html('"'+editedDate+'"');
}
var submitDataCheckbox = function(target){
var project = target.attr('project');
var tableName = target.attr('table');
var rowId = target.attr('rowId');
var checkboxValue = (target.attr('checked'))?true:false;
$.ajax({
type: 'GET',
url: '/checklistpost.php?projectId='+project+'&table='+tableName+'&rowId='+rowId+'&value='+checkboxValue,
success: function(data){
updateUserDate(data);
},
error: function(){
alert('There was an error submitting data to the database.');
},
dataType: 'json'
});
}
The checklistpost.php page takes the variables that are in the query string and posts them to the database. It also then puts the variables in an array which is then encoded in json so that i have a json object to work with. Basically, i am trying to take that json object that gets called back and use it to update the span as mentioned above. When i have used an alert() inside of the updateUserDate function before to verify that i can see the variables and they all have the right data (you can see the code i used to do this is commented out). However, whenever i try and use the variables with jQuery as you see on the 6th line of the code. It doesn't do anything. BTW, The jQuery code that should be output based on what is written above should look like this $("#tableName .row1 .newEditedDate").html("April 14, 2011 # 5:15pm") What am i missing? Thanks in advance for any help!
Your selector is broken, you've got extra quotes in there:
'"#' + table+' .row' + rowId + ' .newEditedDate"'
should be:
'#' + table + ' .row' + rowId + ' .newEditedDate'
So:
// you're surrounding editedDate with extra quotes too, or is that intentional?
$('#' + table + ' .row' + rowId + ' .newEditedDate').html(editedDate);
Why are you using single and double quotes? The command you are passing to jQuery will evaluate to this:
$('"#tableName .row1 .newEditedDate"').html('"April 14, 2011 # 5:15pm"')
instead of this:
$("#tableName .row1 .newEditedDate").html("April 14, 2011 # 5:15pm")