Always get the last Id of for each in Json - javascript

I got a problem with my Json in Javascript.
So I run json and I get a list of all youtube id's, now I show all those youtube videos and I place a button next to it. Now if I click that button it must give me a console log of the youtube id of that video but it always gives me the last youtube video id. Can anyobdy help me witht his code cause Im stuck.
Here is my code:
function generateLast5()
{
$("#musicList").html("");
console.log("what uuup");
$.ajax({
url: ".............",
dataType: "jsonp",
success: function(json){
console.log(json.played_tracks);
for(i in json.played_tracks)
{
console.log(i);
oSingle = json.played_tracks[i];
console.log(oSingle.youtube_ids.default);
phli = $("<li/>")
.appendTo("#musicList");
$("<iframe/>")
.attr("src", "http://www.youtube.com/embed/" + oSingle.youtube_ids.default)
.appendTo(phli);
$("<button/>")
.attr("id","btnAddToPlaylist")
.text("Add To Playlist")
.click(function() {
console.log(oSingle.youtube_ids.default);
})
.appendTo(phli);
}
}
});
}

There's a number of issues with your code.
First, you are creating multiple buttons that have the same id. ids should be unique (and in your case they are not needed).
Second, it is not recommended to use a for...in loop to iterate through arrays. Instead, use a for loop and the array length.
Third, you are assigning values to global variables. I would recommend local variables (e.g. var oSingle) to avoid conflicts.
Now to your issue: you always get the last id because that's what you are calling with oSingle.youtube_ids.default (cf. above comment on local variables). Instead, you could attach the id to each button:
$("<button/>")
.data("youtubeId",oSingle.youtube_ids.default)
.text("Add To Playlist")
.click(function() {
console.log($(this).data(youtubeId));
})

You should split your code up for better readability
AJAX Function
function generateLast5() {
$("#musicList").html("");
console.log("what uuup");
$.ajax({
url: ".............",
dataType: "jsonp",
success: function (json) {
load(json); // call load function here
}
});
}
Loop with proper Array for loop and set id as data attribute
function load(json) {
console.log(json.played_tracks);
for ( var i = 0; i < json.played_tracks.length; i++) { // use array loop
console.log(i);
oSingle = json.played_tracks[i];
console.log(oSingle.youtube_ids.default);
phli = $("<li/>")
.appendTo("#musicList");
$("<iframe/>")
.attr("src", "http://www.youtube.com/embed/" + oSingle.youtube_ids.default)
.appendTo(phli);
$("<button/>")
.data("id", oSingle.youtube_ids.default) // set id as data attribute
.addClass('btn') // set class here for delegation reasons instead of id, Id should be unique
.text("Add To Playlist")
.appendTo(phli);
}
}
Separate click event
$('button').on('click', '.btn', function(){
console.log($(this).data('id'));
});

Related

JQuery .each() Function assigning the same ID for children elements (not iterating?)

I am trying to iterate through a list of children elements and pass their encrypted IDs via AJAX to my controller to update display order on drop using jQuery Sortable. jQuery is selecting the correct amount of child elements but it is assigning the same ID from the dragged and dropped item to both items in my array. I'm not sure what's going on.. I would really appreciate the help! Thanks
JS Code:
$(document).ready(function () {
$(".reqconsentList").sortable({
axis: 'y',
update: function (event, ui) {
var consentForms = [];
$(this).children().each(function (index) {
consentForms.push({ 'id': $('#ConsentID').val(), 'position': index + 1 });
});
var data = { 'sortedConsentForms': consentForms };
//debugger;
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '#Url.Action("UpdateConsentDisplayOrder", "Check", new { Area = "Administration" })'
});
}
});
});
First problem is that $('#ConsentID').val() would return the value from the first element with that id. ID needs to be Unique.
Changing the jquery to class would be correct, but the code would still not know what "element" it should get the data from.
So we need to tell it search for the .reqconsentList, to look for child with the class .ConsentID
This is done this way: $(this).find('.ConsentID').val()

Is there any error in my code, this is not working, Jquery Ajax

I want to apply a for loop (or `do/while loop) but it is not working.
Without the for loop it works for one item but I want to implement the loop because I want multiple items in a single invoice.
$(document).on('keyup', function() {
for (var m = 1; m < 200; m++) {
$("#item_name" + m).on('keyup', function() {
var suppliercode = $(this).val();
$.ajax({
type: 'POST',
url: 'sqty_dynamics.php',
data: {
item_name: suppliercode
},
success: function(data) {
$("#order_item_squantity" + m).val(data);
}
});
});
}
});
You are using two events one outside the loop and other is inside the loop. The outside loop it works and in the loop, it doesn't because it needs the keyup event for each iterate.
So you need to bind up inside event while firing out the event.
See this click event
From what I can see in your code, you're putting your for loop inside of an event handler for the document's keyup handler. Is that what you meant to do?
Right now, that code says "when a keyup is detected on the whole document, add event listeners for more keyup events m < 200 times on m item". That means every time the document gets keyup'd, the listeners for those individual items in the loop get re-added.
Certainly that's not what you were hoping to accomplish. Try just removing the $(document).on(...) part altogether and see what it does.
Thanks Everybody for helping me. Mr Gufran Hasan share the link to find the answer. So, after some effort i found the answer.
This code works for me to getting the required results.
<script>
$(document).on('keyup',function(){
$(function() {
var dummy = [1, 2, 3, 4, 5];
$.each(dummy, function(i, v) {
$('#item_name' + i).keyup(function() {
//alert(i);
var suppliercode = $(this).val();
$.ajax({
type: 'POST',
url: 'sqty_dynamics.php',
data:{item_name:suppliercode},
success:function(data){
$("#order_item_squantity"+ i).val(data);
}
});
});
});
});
});
</script>

Get id of the <a> tag from one function to another

I am very new in javascript/jQuery so please bear with me if my question will be too easy for you and too difficult for me.
This is from a function, I just don't post the complete codes since it will be too long.
And I have another function which also have an ajax and I want to pass get the ID of the <a> tag:
function someName() {
jQuery.ajax({
type: 'POST',
url: 'thisisprivate.aspx',
data: {
action: 'MyAction',
word: 'Wednesday',
count: '4',
page: '1'
},
success: function(data) {
var json = jQuery.parseJSON(data);
var htmlInfo = '';
for (i = 0; i < json.length; i++) {
var htmlCode = '';
htmlInfo = htmlInfo + htmlCode;
}
jQuery('#WMVideoxx').html(htmlInfo);
}
});
}
and
function VideoDiv() {
jQuery.ajax({
type: 'POST',
url: 'thisisprivate.aspx',
data: {
action: 'actionNameHere',
idorname: id //I Want to pass the ID here
});
}
What you are doing is:
jQuery('a').click(function() {
VideoDiv(jQuery(this).attr('id'));
});
This will not work because of the nature of <a> tag being dynamically generated and the event doesn't get registered. Consider delegating the event (see Understanding Event Delegation for more information):
jQuery(document).on("click", 'a', function() {
VideoDiv(jQuery(this).attr('id'));
});
The above code works, but will delegate for all the <a> inside the document. Instead, add a class or something that uniquely identifies that. And call it this way:
jQuery(document).on("click", 'a.class', function() {
VideoDiv(jQuery(this).attr('id'));
});
Another thing about the above delegation of code is, it is better to use a closest static parent instead of document. Since I don't know the HTML structure, I have used document. :)
Also, as Ismael Miguel says, it is better to get the id using this.id:
jQuery(".static-parent").on("click", '.class', function () {
VideoDiv(this.id);
});
The above would be the best code.
Also, it has been pointed out again, for better performance, you may replace the code with:
setTimeout(
(function () {
VideoDiv(this.id);
}).bind(this), 10
);
This will let jQuery handle the next even handler, and will execute this code on the next 10ms (when available).
use onclick="function();" with your anchor and pass arguments that you want in your function
Your htmlcode should be like this
Your VideoDiv function
function VideoDiv(id)
{
//your ajax goes here
}
Try this : you can put onclick call to a tag while creating it and pass this object which is nothing but the a tag element, see below code
var htmlCode = '';
Now make following changes in your javascript function
function VideoDiv(anchor)
{
jQuery.ajax({
type: 'POST',
url: 'thisisprivate.aspx',
data: {
action: 'actionNameHere',
idorname: anchor.id //pass id here from anchor object
}
});
}
NOTE: your data attribute in above ajax call is incomplete, please correct it.

Modifying html of dom element that was created after page loaded

I have two separate AJAX calls. One that gets a list of items from a txt file and creates an HTML table out of them and one that talks to a database to find how much each item costs and then lists this in the corresponding table cell for each item (I know this may sound like a strange approach, but it's a good option in our case...).
The issue is that the price is not getting written to the table since the table is created (or to be precise, the rows of the table are created) after the page loads. I'm not sure how to fix this.
$(document).ready(function() {
makeItemTable();
listPrices();
...
});
function makeItemTable() {
$.ajax({
url: 'products.php',
type: 'GET'
})
.done(function(response) {
$('.price-table > tbody').html(response);
})
}
function listPrices() {
.ajax({
url: 'prices.php',
type: 'GET'
})
.done(function(response) {
priceData = $.parseJSON(response);
$('.price-table tr').each(function() {
var item = $(this).find('td:nth-child(1)').text();
if (priceData[item]) {
var price = priceData[item];
$(this).find('td:nth-child(2)').text(price);
}
})
}
You can try
Using setTimeout to check request to 'products.php' execute callback done (inside callback for request to 'prices.php')
Another way
var jqxhr1 = $.ajax("products.php");
var jqxhr2 = $.ajax("prices.php");
$.when(jqxhr1, jqxhr2).done(function(jqxhr1, jqxhr2) {
// Handle both XHR objects
alert("all complete");
});
Call function listPrices() inside callback request to 'products.php'
Hope to help

jQuery function not attached to dom elements

I am trying build a web page that will construct elements from JSON file and attach click function to those elements.
$(document).ready(function(){
$.ajax({
url: 'database.php',
type: "POST",
dataType: 'json',
success: function (datas) {
(datas);
for (var x = 0; x < datas.data.length; x++) {
var id = datas.data[x].ID;
var ip = datas.data[x].IP;
var ips='<div class="ip"><span id="ids">'+id+'</span><span id="number">'+ip+'</span></div>';
$('#left').append(ips);
}
}
});
$('.ip').click(function () {
alert($(this).children('#ids').text());
});
});
the code above builds the elements successfully but the click function is not working.
You can use the on function instead, it is used to apply event handlers to elements that are not yet created.
Where you have your current click setup, try something like this instead:
$(document).on('click', '.ip', function(){
alert($(this).children('#ids').text());
});
As #Pete has suggested, it is not a good idea to assign the same id attributes within a loop, they should be unique to the document. Consider finding them via class names instead, so you could alert something like:
alert($(this).children('.MyIdsSpan').text());

Categories

Resources