My code involves fetching some data using jQuery's Ajax. I then append the result I get from the server to html (in form of buttons). All buttons have a class name mybutton. A separate JavaScript file handles the button click events. Everything works okay for the first Ajax call but I then get an error on second Ajax call. The Ajax calls are made at an interval
HTML code
<button class="mybutton">Button 1</button>
Javascript Code in a SCRIPT1.js file
document.addEventListener("DOMContentLoaded", ready);
function ready() {
let buttons = document.querySelectorAll(".mybutton");
buttons.forEach((button) => {
button.addEventListener("click", () => {
//do some stuff
console.log("I was Clicked");
});
});
}
jQuery CODE in a SCRIPT2.js file
$(document).ready(() => {
//append the html to add more buttons after some time
setInterval(() => {
$.ajax({
method: "GET",
url: "/getButtons",
async: true,
success: function (data, status, xhr) {
data.forEach((item) => {
$("body").append(
'<button class="mybutton">' + item + "</button>"
);
});
const scriptsrc = document.createElement("script");
scriptsrc.setAttribute("type", "text/javascript");
scriptsrc.setAttribute("src", "//script location here");
$("head").append(scriptsrc);
},
});
}, 10000);
});
The JavaScript attached to the buttons only fires up only once after the first Ajax request.The second time I get an error:
Uncaught SyntaxError: Identifier 'buttons' has already been declared
Can you try with the following script? To clarify if the 'let buttons' is issue or the ready() function is overriding the existing one.
document.addEventListener("DOMContentLoaded", init_fun);
function init_fun() {
document.querySelectorAll(".mybutton").forEach((button) => {
button.addEventListener("click", () => {
//do some stuff
console.log("I was Clicked");
});
});
}
Updated due to the comment.
In this case, if you are injecting the script1 after your ajax call, you will have multiple script tags which include multiple variables with the same name.
Instead of adding the whole script, call the function after the success callback of the ajax call. That should avoid multiple variable issues.
Related
I need to access a js variable declared in one block of a html page into another block of the same html page just so I can stop a ajax call that is being made, but I don't know how can I access a variable that was declared into another block. I can't merge the two blocks, everything else is on the table.
<script>
$(function() {
var term = new Terminal('#input-line .cmdline', '#container output');
term.init();
});
</script>
<script>
term.ajaxHandler.abort();//but how can I access the variable term from the block above,this will be inside a button later
</script>
Thanks in advance
The way your code example is described, it's not possible to reuse that variable. Because it is not bound to the window object, it's bound to the function that is self-executed. It's an example of a "safe" way of libraries not intervening with your own code.
You can however, since I guess by the syntax it's jQuery, hook into the jQuery ajax handling. Based on your requirements, to stop an ajax call, you need to listen to all ajax requests.
You could take a look at the jQuery ajax hooks, https://api.jquery.com/category/ajax/.
You could end up with something like:
$(document).ajaxSend(function(event, xhr, settings){
if (settings.url === "/your/url/to/abort") {
xhr.abort();
}
});
just declare var term above the function declaration
var term
function test1(){
term = 'hello there'
test2()
}
function test2(){
console.log(term)
}
test1()
ok, I managed to solve, basically I created a function only to abort the ajax request like this:
this.abortAjax = () => {
requestHandler.abort();
}
and then accessing it within terminal.js itself using the term object that was instantiated beforehand. After working around the code I was able to keep everything inside the terminal script and not splitted in the two parts, getting something like this:
function ShowLoadingScreen () {
var customElement = $("<div>", {
"class" : "btn btn-danger btn-lg",
"text" : "Abort",
"onclick": "term.abortAjax()"
});
$.LoadingOverlay("show", {
//image : "/static/loading.gif",
background : "rgba(204, 187, 0, 0.8)",
imageAnimation : "rotate_right",
//imageAutoResize : true,
text : "Loading...",
custom : customElement
});
}
function request (command) {
...
requestHandler = $.ajax({
url: _url,
beforeSend: function () { ShowLoadingScreen(); }, // <Show OverLay
type: 'GET',
dataType: 'json',
success: function (response) {
...
},
complete: function () { HideLoadingScreen(); } //<Hide Overlay
}).fail(function (jqXHR, textStatus, error) {
...
});
ShowLoadingScreen();
}
Thanks, everyone.
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 have a issue in my js file.
This is my Js Code.
<script type="text/javascript">
$(document).ready(function()
{
$(".abc").click(function()
{
$(this).addClass('testingClass');
});
$(".testingClass").click(function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
});
</script>
My HTML :
<button class="abc">Demo</button>
When i load this page in Browser, The addClass function is successfully executing and adding new class named "testingClass".
But When Try to click again t that button (meens : class="testingClass") the alert function does not working. What is the error.
Is JS is not supporting frequent execution of an element ?
Anybody Please help me.
Steps..
One Button has class named abc
When click on it an ajax function will storing current time in database.(ajax function not in stack-code).
after successful ajax response the button class changed to testingClass.
now the class name of the button is testingClass
After some time Click on the Button again (class named:testingClass), i want to call a ajax function with current time of click and store the values in database.
Then the Button class name will changed to old ( abc).
You need to event delegation for dynamic added element
$(document).on("click",".testingClass",function()
{
alert("hiiiiiiiiiiiiiiiiii")
});
Event delegation
Update
For the changed question, you are looking for something like this.
Here is a demo.
$('body').on('click', '.abc', function () {
// event attached to .abc
// updateTime is a method that takes context (this), current timestamp and a function
// we need to send the context so that we have access to the current
element inside the below function which is executed outside the scope
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('testingClass').removeClass('abc');
$('#log').append('Time: ' + data + 'from abc <br/>');
});
}).on('click', '.testingClass', function () {
// event attached to .abc
updateTime.call(this, new Date().getTime(), function (data) {
$(this).addClass('abc').removeClass('testingClass');
$('#log').append('Time: ' + data + ' from testingclass <br/>');
});
});
function updateTime(currentTime, successCallback) {
$.ajax({
context: this, // the context sent from the above methods is used here
url: '/echo/html/',
data: {
html: currentTime
},
method: 'post',
success: successCallback
});
}
Using .one() will help you attach event only once upon multiple clicks.
This handler is executed at most once per element per event type.
I think this is what you are looking for. Adding a handler after the class is added.
$(".abc").click(function(){
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
$(document).ready(function() {
$(".abc").click(function() {
$(this).addClass('testingClass');
$(".testingClass").one('click', function() {
alert("hiiiiiiiiiiiiiiiiii");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="abc">Demo</button>
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.
My problems seems basic, yet I have tried a lot of different ways of putting these functions on one html file to no avail. The problem is that, when the 1st function is called, the second also runs, leaving me with the results of the second function all the time. I have no idea what I am doing wrong, please help. Here is the code in question.
<script>
$(document).ready(function () { // Make sure the elements are loaded on the page
// Listen for a click event on the button
$('#buttonON').click(funct);
$('#buttonOFF').click(funct2);
});
// Now define the function
function favfunct(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "1", "caroff" : "0"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
function funct2(e) {
// Stop the page from "following" the button (ie. submitting the form)
e.preventDefault();
e.stopPropagation();
// Insert AJAX call here...
$.ajax("carstatusupd.php", {
// Pass our data to the server
data: { "username" : "sibusiso", "caron" : "0", "caroff" : "1"},
// Pass using the appropriate method
method: "POST",
// When the request is completed and successful, run this code.
success: function (response) {
// Successfully added to favorites. JS code goes here for this condition.
}
});
}
</script>
You have omitted the closing brace from the function favfunct().
Please use this,
<script>
$(document).ready(function () {
function funOne(){
};
function funTwo(){
};
$('#buttonON').live('click',function(){
funOne();
});
$('#buttonOFF').live('click',function(){
funTwo();
});
});
NOte: initialize function before use and initialize them into document ready.