function test() {
$.getJSON("/Home/GetAp", function (result) {
$.each(result, function () {
if (this.is_disabled == "False") {
var a = $("#MainDiv")
.append('<div id="imagewrap"><img id="infobutton" src="/Content/information%20icon.png" /></div>')
.val(this.id);
} else if (this.is_disabled == "True") {
var a = $("#MainDiv")
.append('<div id="imagewrap"><img id="infobutton2" src="/Content/information%20icon.png" /></div>')
.val(this.id);
} else {
return null;
}
})
})
}
How would I nest and ajax function be able to POST the a.val() so that when a user clicks on any $("#infobutton") they will be able to use the val of that button which would be an id specific to that button
$("#infobutton").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Home/setID",
data: JSON.stringify({ id: this.id }),
success: function (result) {
}
});
});
Do not make your logic depend on duplicate ids of DOM elements, use class instead.
Use event delegation to register event handlers for elements that exist at the time of event registration and for elements that will be created later.
.append('<div id="imagewrap"><img class="infobutton" src="/Content/information%20icon.png" /></div>')
$(document).on("click",".infobutton",function () {
$.ajax({
...
});
});
No need to nest ajax call. Just ensure click events bind to new elements appended and get the id in click event handler. Similar example (without ajax call)
$(document).ready(function(){
$(document).on('click', '.info', function(e) { alert("clicked div # " + $(e.target).text()); });
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 1.</div>"); }, 1000);
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 2.</div>"); }, 2000);
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 3.</div>"); }, 3000);
});
<div id="d1">
</div>
Let me know if you need more details or example with ajax call.
For id you can use
$(document).on('click', '.info', function(e) { alert("clicked div # " + e.target.id); });
Related
I have a table with some <td>s and I have a link to delete each row with the class of '.DeleteMe'.
I have an AJAX post call in jQuery, but when I click on a link, it does nothing (click event doesn't work).
$(document).ready(function() {
$(".DeleteMe").click(function() {
var button = $(this);
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Merchant/DeleteProduct/" + DeleteId,
type: "Post"
}).done(function() {
$(button).parents("tr").remove();
}).error(function() {
alert("Something Went Wrong.");
})
})
});
And here is the link on the each row:
<a class="btns delete-icon DeleteMe" data-deleteid="#item.id">Delete</a>
How can I get these links to work?
I guess, that your rows are created dynamically after your event has been attached. In this case I would recommend to use event-delegation instead:
$(document).ready(function() {
$(document).on('click', '.DeleteMe', function() {
var button = $(this);
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Merchant/DeleteProduct/" + DeleteId,
type: "Post"
}).done(function() {
$(button).parents("tr").remove();
}).error(function() {
alert("Something Went Wrong.");
})
})
});
I am trying to create a dropdown menu that I dynamically insert into using jQuery. The objects I'm inserting are notifications, so I want to be able to mark them as read when I click them.
I have an AJAX call that refreshes the notifications every second from the Django backend.
Once it's been refreshed, I insert the notifications into the menu.
I keep an array of the notifications so that I don't create duplicate elements. I insert the elements by using .append(), then I use the .on() method to add a click event to the <li> element.
Once the click event is initiated, I call a function to .remove() the element and make an AJAX call to Django to mark the notification as read.
Now my problem:
The first AJAX call to mark a notification as read always works. But any call after that does not until I refresh the page. I keep a slug value to identify the different notifications.
Every call I make before the refresh uses the first slug value. I can't figure out why the slug value is tied to the first element I mark as read.
Also, if anyone has a better idea on how to approach this, please share.
Here's my code:
var seen = [];
function removeNotification(elem, urlDelete) {
elem.remove();
console.log("element removed");
$.ajax({
url: urlDelete,
type: 'get',
success: function(data) {
console.log("marked as read");
},
failure: function(data) {
console.log('failure to mark as read');
}
});
}
function insertNotifications(data) {
for (var i = 0; i < data.unread_list.length; i++) {
var slug = data.unread_list[i].slug
var urlDelete = data.unread_list[i].url_delete;
if (seen.indexOf(slug) === -1) {
var elem = $('#live-notify-list').append("<li id='notification" +
i + "' > " + data.unread_list[i].description + " </li>");
var parent = $('#notification' + i).wrap("<a href='#'></a>").parent();
seen.push(slug);
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
}
}
}
function refreshNotifications() {
$.ajax({
url: "{% url 'notifications:live_unread_notification_list' %}",
type: 'get',
success: function(data) {
console.log("success");
insertNotifications(data);
},
failure: function(data) {
console.log('failure');
}
});
}
setInterval(refreshNotifications, 1000);
I really don't know what do you mean with parent[0] in
removeNotification(parent[0], urlDelete);
I think you can simply try $(this)
removeNotification($(this), urlDelete);
but to be honest I find to put
$( document ).ready(function() {
$( document ).on("click", "#notification" + i, function() {
console.log("onclick " + slug);
removeNotification(parent[0], urlDelete);
});
});
inside a loop .. its bad thing try to put it outside a function and use it like
$( document ).ready(function() {
setInterval(refreshNotifications, 1000);
$( document ).on("click", "[id^='notification']", function() {
console.log("onclick " + slug);
removeNotification($(this), urlDelete);
});
});
and try to find a way to pass a urlDelete which I think it will be just one url
In my Ajax success function i created button and on click i am calling a function.
The problem:
The page reloads based on the timer in set interval but when i click the button it will call the function based on the number of times the page reloaded.
For example:
If page reloads 5 times and then i call a function on clicking that button-it will call that function 5 times.
if it reloads 10 times then function call is for 10 times.
Please advice what i am doing wrong?
Here is the code:
$(document).ready(
function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: 'Refresh',
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
var buttonVar = ('<button id="bt21" class="btn121">' + "STOP" + '</button>');
trHTML += '<tr><td>'+buttonVar+'</td></tr>'
});
$('#test1').append(trHTML);
$(document).on('click','#bt21', function(event) {
var rownum1 = $(this).closest('tr').index();
stopTest(data[rownum1].process_id);
});
}
});
}, 5000);
});
You have set the AJAX call to be made every 5 seconds. Each time time this function is called, you are also attaching the click event on the button you append. So there will be multiple event handlers attached to the same element. You need to clear any existing event handlers on that element before you attach another if you want to stick to your current code. Here's how to do it:
$(document).off('click', '#bt21');
$(document).on('click','#bt21', function(event) {
var rownum1 = $(this).closest('tr').index();
stopTest(data[rownum1].process_id);
});
Each time the page is refreshed from your ajax call a new event listener is bound to the button in memory. You need to clear the event listeners then create a new one.
$(some element).unbind().on(...........);
I always unbind event listeners created in an ajax call if anything to keep the browser memory from being over loaded or to prevent the issue you are having.
$(document).ready(
function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: 'Refresh',
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
var buttonVar = ('<button id="bt21" class="btn121">' + "STOP" + '</button>');
trHTML += '<tr><td>'+buttonVar+'</td></tr>'
});
$('#test1').append(trHTML);
$(document).unbind().on('click','#bt21', function(event) {
var rownum1 = $(this).closest('tr').index();
stopTest(data[rownum1].process_id);
});
}
});
}, 5000);
});
First you are appending buttons on refresh that have the same id attribute so that's going to cause you issues at some point.
What you need to do is move your click event outside of the interval function and ajax callback. Add the process id to the button in a data attribute and delegate a click event to the button so it will work even though the elements haven't been created in the DOM when the page loads.
Here's an example although I'm not sure if it works (can't really simulate this easily):
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: 'GET',
url: 'Refresh',
success: function(data) {
var trHTML = '';
$.each(data, function(i, item) {
var buttonVar = '<button class="btn" data-process-id="' + item.process_id + '">' + "STOP" + '</button>');
trHTML += '<tr><td>'+buttonVar+'</td></tr>'
});
$('#test1').append(trHTML);
}
});
}, 5000);
$('#test1').on('click', '.btn', function() {
stopTest( $(this).data('process_id') );
});
});
$(function() {
$(".universeLink").click(function (e) {
e.preventDefault();
var link = this;
alert(link.id);
$.ajax({
type: 'GET',
url: "#Url.Action("IsUniverseCached", "Universes")" + "?universeId=" + (link.id),
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (returnedData) {
if (returnedData === false) {
alert(returnedData);
$("#" + link.id).empty();
$("#" + link.id).html("<div class=\"alert alert-warning\"><strong>Not cached</strong> — this data will take a while to arrive!</div>");
}
$("#" + link.id).click();
},
error: function () {
alert("Error");
}
});
});
});
I am building some JQuery to make a request before the original request is followed.
At the end of the success block, $("#" + link.id).click(); is called and the event is fired again. I tried something similar with (element).submit() on a form, and the .submit() event did not fire again, so I assumed I could do the same trick with .click().
Here's the HTML elements.
<a id="10" href="/Universes/ViewUniverse?universeId=10®ionId=8" class="universeLink">1</a>
(the ID is dynamically assigned)
Just redirect the browser to the new location. I.e. instead of using .click, assign to window.location.href:
window.location.href = link.href;
I'm pretty new to all things javascript related, and I seem to have got myself in a pickle. I'm creating a site which displays a seating plan of an office. When the page loads, I load data retrieved from the database, into a function that loops through it and creates an anchor for each person.
This is my method:
function getDesks(coordsArr) {
for (var i = 0; i < coordsArr.length; i++) {
var element = $("<a href='' class='deskBtn' data-name='" + coordsArr[i].UserName + "'>.</a>");
$(element).css({
"top": coordsArr[i].DeskYCoord,
"left": coordsArr[i].DeskXCoord
}).appendTo(".map");
}
}
The problem i'm having is where to place the following ajax click event.
$('.deskBtn').on('click', function () {
var user = $(this).attr("data-name");
console.log(user);
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: {user: user},
success: function (data) {
}
});
});
I tried placing it after the for loop, but when I click one of the anchor tags the data gets logged to the screen, however, it quickly vanishes. Any suggestions would be great.
Why can't you just add the handler inside the for loop?
$(element).on('click', function() { ... })
Delegate the event to a static element. Do it for body:
$('body').on('click', '.deskBtn', function () {
var user = $(this).attr("data-name");
console.log(user);
$.ajax({
url: "/Home/GetUserData",
type: "GET",
data: {user: user},
success: function (data) {
}
});
});
You should try with a live
$(document).ready(function(){
$('.deskBtn').live('click', function(){
});
});