I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.
Related
i face a problem of jquery click function when i scroll down in list.
in list, data is loaded by ajax request and when i scroll down then click function (trigger) is not working.
when i not scroll down, ajax data is not loaded then click function is working.
i'm confuse why this happened. i used following triggers below but not success.
on()
click()
bind()
load()
delegate()
i'm sending you code. this is code below. Please help me to sort out.
$(window).ready(function(){
$(".like").on("click", function(){
var id = $(this).attr('data');
// alert(id);
$.ajax({
url: "/stores/addLike",
type: 'GET',
data: {
id: id
},
error: function (data) {
console.log(data);
},
success: function (data) {
console.log(data);
if(data == "liked"){
alert('Sorry, you have already liked this beat.');
}else if(data == "notlogin"){
alert('Please login first to like a beat.');
window.location = "https://demo.amplifihub.com/login";
}else{
$(".likes"+id).text(data);
}
}
});
});
});
instead of $(".like").on("click", function(){ }); use $(document).on("click", ".like", function(){}); or use any static parent dom element to preserve the DOM event. I believe you are generating .like class element on scroll ajax call.
I am trying to execute a $.ajax() inside a function called by a .on() method, so that in the newlly attached data, it would be possible to execute a script on a .click() event - I know this is probably something similar to other requests, but i have tryed and tryed, and can't find what is wrong withthe code...
The ajax function is called by a change in a select, and 'this' is passed as a variable to the function.
The data is correctly inserted inside the targeted div, but it seems that there is no bubbling, because no javascript runs from it (but runs outside of targeted div).
I used .on() so it would bubble up, and update the DOM, and I dont see wath I am doing wrong with it...
The ajax is called with:
$("body").on("change", "[data-project-ajaxSelect='true']", {select: this},Select_AjaxCall);
function Select_AjaxCall(event) {
$select = event.data.select;
if (typeof $select.data === "undefined" || $select.data === null) {
var $select = $(this);
}
var options = {
url: $select.attr("data-project-action"),
type: $select.attr("data-project-method"),
target: $select.attr("data-target"),
data: { guid: $select.val() }
}
$.ajax({
type: options.type,
url: options.url,
data: options.data,
dataType: "html",
success: function (data) {
console.log(data)
$(options.target).html(data);
}
});
return false;
};
From that code, a button is added with the following View code:
<button id=#Model.Guid
class="button default cycle-button"
data-toggle="modal"
data-target="#modalDiv"
data-backdrop="static"
data-keyboard="true"
data-modal-modal="true"
data-modal-controller="Fin_Movement_Type"
data-modal-action="Create"
data-modal-var-guid=#Model.Guid
data-modal-var-modal=#ViewBag._modal>
<span class="icon mif-plus"></span>
</button>
And by cicking on this button, the following .click() event should be fired...
$("[data-modal-modal='true']").click(function () { ... }
But it isn't.
Please Help me find where is the bug with my code... thank you.
Edit
It seems you need live functionality that has been removed from jQuery, but you can use on instead of that, this way:
$(function () {
$(document).on("click","[data-modal-modal='true']", function () {
alert('clicked');
});
});
Original
You can add your code at the end of your success method:
success: function (data) {
console.log(data);
$(options.target).html(data);
$("[data-modal-modal='true']").on("click", function() {
alert('clicked!');
});
}
Also you can load the button with suitable script in onclick attribute, for example:
<button id="#Model.Guid"
...
onclick="alert('clicked!');">
<span class="icon mif-plus"></span>
</button>
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.
I am binding some jQuery event handlers to an element in the page which work fine initially, however if the user selects a radio button on the page, that element gets removed; they can bring it back by selecting another radio button; however when the data is loaded back in by AJAX the function no longer fires from the event handler.
I am binding it with this:
jQuery(document).ready(function(){
jQuery('#buyout_field').mouseleave(function() {
update();
});
jQuery('#buyout_field').focusout(function() {
update();
});
});
So to recap, runs fine initially, but once AJAX removes and then puts the data back it no longer runs.
Here is the the code that runs the AJAX:
function update() {
getAjaxData(loadUrl, dataObject, 'GET', 'json')
.done(function(response) {
// Add/Hide other data
jQuery('#buy_now').html(response.buy_now);
})
// End
}
function getAjaxData(loadUrl, dataObject, action, type) {
return jQuery.ajax({
type: action,
url: loadUrl,
data: dataObject,
dataType: type
});
}
The element buyout_field is contained within the buy_now element.
Isn't the element put back into the DOM or something?
Try this:
jQuery('#buy_now').on('mouseleave', '#buyout_field', function() {
update();
});
jQuery('#buy_now').on('focusout', '#buyout_field', function() {
update();
});
You need to delegate the events...
jQuery(document).on('focus', '#buyout_field', function() {
update();
});
jQuery('#buyout_field').on({
mouseleave : function() {
update();
}, $(document)
});
It is always a better idea to replace the events delegated to the document , to a static ancestor to which the events are bound.. In this case '#buy_now' will be the static parent as it is always present on the page when the event is bound.
I'm having problems with updating elements that are not ready after an ajax request.
If I run my myFunction() function on page load like so:
$(function() {
myFunction();
}
I have no problems at all. But if I then use something like
$.ajax({
url: this.href,
dataType: "script",
complete: function(xhr, status) {
myFunction();
}
});
which returns $(".myElement").replaceWith("htmlHere"). The elements are simply not ready when the complete event fires. If I set a delay in there it works fine again.
Is there any other event that gets fired other than 'complete' when the DOM is ready?
Update:
Here's the actual code:
$(function() {
$("a.remote").live("click", function(e) {
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
myFunction();
}
});
e.preventDefault();
return false;
});
myFunction();
});
function myFunction() {
// Modify the dom in here
}
The missing ); was just a typo on my part.
Ive tried using success now instead of complete and it doesn't appear to make any difference.
I have set up a jsfiddle based on your code, and it seems to be working.
This is the current code:
$(function() {
$("a.remote").live("click", function(e) {
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
myFunction();
}
});
e.preventDefault();
return false;
});
});
function myFunction() {
$("span").replaceWith("<p>test</p>");
}
And it replaces span tag with a paragraph. Please check it and compare with your code. If it is the same, then your problem somewhere other than this function (maybe in myFunction?).
You can use $(document).ready(function() { ... }); to wrap up anything you want fired when the DOM has loaded. Your ajax request could be placed inside the document.ready if you want this to wait until the dom has loaded.
If you want to wait until the ajax has loaded its resource then you should use ajax.success rather than complete.
Just change complete: to success: in your $.ajax() call:
$.ajax({
url: this.href,
dataType: "script",
success: function(xhr, status) {
//make your DOM changes here
myFunction();
}
});
The success function will run once the AJAX request receives a successful response. So make your DOM changes within that function, and then run myFunction().
Edit
You seem to be trying to make the DOM changes using your myFunction(). But if you don't first insert the HTML received in the AJAX response into the DOM, then there will be nothing for myFunction() to modify. If this is indeed what's happening, then you have two options:
Insert the response HTML into the DOM, then call myFunction() (and all of this should happen within the success callback function).
Pass the AJAX response to myFunction() as an argument, so that myFunction() can handle the DOM insertion and then do the necessary modification.
There is a event that triggers after every ajax call. It is called ajaxComplete.
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
});
So you can
function Init(){
// stuff here
}
$(document).ready(function()
Init();
});
$(document).ajaxComplete(function()
Init();
});
You are missing the closing parenthesis of the document ready wrapper function.
$(function() {
myFunction();
});
Note the }); at the end.
$(function() {
myFunction();
}
should be
$(document).ready(function() {
myFunction();
});
Or incase you want the ajax to run on load. Do
$(document).ready(function() {
$.ajax();
});