Calling a click event of a dynamically created element - javascript

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(){
});
});

Related

jQuery Load And Ajax Forms Not Working Together

I've created a news system, where i should be able to edit articles dynamically without redirect, from a modal. Also, i should be able to delete and create articles.
When something is changed, jQuery Load is called, but the problem is when i have to edit the loaded content.
$("#toolbox-items").load('inc-toolbox');
The above code loads the articles (the file is called inc-toolbox on purpose and works fine).
$(function () {
$('form').on('submit', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});
But, when ever something has to be edited or deleted, the whole page reloads and nothing changes, although i'm still able to add things.
The add-button is not loaded dynamically from the script, but is in there from the start.
What in the world might the problem be?
Try code like this
$(function () {
$(document).on('submit','form', function(e) {
e.preventDefault();
var clicked = document.activeElement.getAttribute('name');
$.ajax({
type: 'post',
url: 'process-toolbox',
data: $(this).serialize() + "&" + clicked + "=success",
success: function (response) {
$("#toolbox-items").load('inc-toolbox');
$('.modal-backdrop').remove();
}
});
});
});

AJAX jQuery on click dynamically created only works first time

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

Jquery ajax button click event firing twice?

I have a Employee page which shows list of employees with an edit option. On clicking the edit button jquery-ajax is used to fetch the data from the server.
The problem is when I click the edit button the event is firing twice.
I am using a seperate js file and is referring the file to the main page.The script was working fine until i moved it to the seperate js file.
The Jquery script is
//ajaxGet on edit button click
$(document).on('click', '.editRole', ajaxGet);
var ajaxGet = function (e) {
var spinner = $(this).parent('div').find('.spinner');
var href = $("#editMenuSettings").data("url");
var menuRoleId = $(this).data('id');
spinner.toggle(true);
var options = {
type: "GET",
url: href,
data: { menuRoleId: menuRoleId }
};
$.ajax(options).success(function (data) {
spinner.toggle(false);
$(".modal-body").html(data);
$(".modal").modal({
backdrop: 'static'
});
});
$.ajax(options).error(function (data) {
spinner.toggle(false);
toastr.error("Oops..Some thing gone wrong");
});
return false;
};
You call $.ajax twice.
At lines
$.ajax(options).success(function(data)...
$.ajax(options).error(function(data)...
you actually make two different AJAX calls - one with success callback only, another one with error callback.
In your case, your call should look like this:
var options = {
type: "GET",
url: href,
data: { menuRoleId: menuRoleId }
};
$.ajax(options)
.success(function (data) {
spinner.toggle(false);
$(".modal-body").html(data);
$(".modal").modal({
backdrop: 'static'
});
})
.error(function (data) {
spinner.toggle(false);
toastr.error("Oops..Some thing gone wrong");
});
return false;
It will set both callbacks to the single AJAX call and execute this one.

Refresh a particular div when I click on that div.Without reloading the whole page.I specifically want it using onclick function

$(document).ready(function () {
var j = jQuery.noConflict();
j(document).ready(function () {
j(".refresh").everyTime(2000, function (i) {
j.ajax({
url: "refresh.php",
cache: true,
success: function (html) {
j(".refresh").html(html);
}
})
})
});
j('.refresh').css({
color: ""
});
});
<?php
echo time();
?>
It works for refreshing page after particular time interval .I want this to be working after I click on particular div.
You can place your code in a click handler. Like this:
$(document).ready(function () {
var j = jQuery.noConflict();
j(".refresh").everyTime(2000, refreshDiv)
j('#myDiv').click(refreshDiv);
j('.refresh').css({
color: ""
});
function refreshDiv() {
j.ajax({
url: "refresh.php",
cache: true,
success: function (html) {
j(".refresh").html(html);
}
});
}
});
Note that I extracted the logic in to its own function so it can be called from different parts of your code. I also removed the pointless duplicate DOMReady handler.
This is just a simple one
But you need to modify it
$(document).ready(function(){
$('.refresh').on('click', function(){
$.ajax({
url: "refresh.php",
cache: true,
success: function (html) {
j(".refresh").html(html);
}
});
});
});

How can I prevent a click event from firing when I call "<element>.click()"? Or what's a better way to solve this issue?

$(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&regionId=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;

Categories