Ajax execute only once inside an event - javascript

I have created a widget that displays a html template fetched with an ajax request to the server. I want to refresh the template clicking on a <p> element of the template. However when I click on it, it refreshes the template only once, then, if I try to click again, the event does not respond, it does not execute the request again. This is my code, if someone has any idea what I am doing wrong.
/******** Our main function ********/
function main() {
jQuery(document).ready(function ($) {
var widget_url = "/home/widget?callback=MyCallbackFunction"
$.ajax({
url: "/home/widget",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
success: function (data) {
$('#example-widget-container').html(data.html);
$("#panel-sidebar-icon").on("click", function () {
$.ajax({
url: "/home/widget",
type: "GET",
dataType: "jsonp",
jsonp: "callback",
cache: false,
success: function (data) {
$('#example-widget-container').html(data.html);
}
});
});
}
});
});
}
The template example:
<aside>
<p id="panel-sidebar-icon">Click </p>
<ul>
<li>.... </li>
</ul>
</aside>

events attached to DOM elements are lost when you replace the container html, so.
change this
$("#panel-sidebar-icon").on("click", function () {
to this
$("body").on("click", "#panel-sidebar-icon", function () {

maybe because you create a new DOM object so the event goes with the erasure. You should update simple datas on the element or recreate the same component+event associated to it

Related

Html Ajax button not doing anything

im sure this is something obvious but I cant figure it out
onclick of button retrieveScoreButton my button is simply not doing anything
any help is appreciated, im attempting to append the data to a table but cant even get it to register the clicking of the button so I cant test the function showsccore
<button id="addScoreButton">Add score</button>
<button id="retrieveScoreButton">Retrieve all scores</button>
<br>
<div id="Scores">
<ul id="scoresList">
</ul>
</div>
<script>
$(document).ready(function () {
$("#addScoreButton").click(function () {
$.ajax({
type: 'POST',
data: $('form').serialize(),
url: '/addScore',
success: added,
error: showError
}
);
}
);
});
$(document).ready(function () {
$("#retrieveScoreButton").click(function () {
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: alert("success"),
error: showError
}
);
}
);
});
function showScores(responseData) {
$.each(responseData.matches, function (scores) {
$("#scoresList").append("<li type='square'>" +
"Home Team " + matches.Home_Team +
"Away Team: " + matches.Away_Team +
"Home: " + scores.Home_Score +
"Away: " + scores.Away_Score
);
}
);
}
function showError() {
alert("failure");
}
</script>
</body>
</html>
There are a couple things wrong here:
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: alert("success"),
error: showError
});
First, you never defined id. (After some comments on the question it turns out your browser console is telling you that.) What are you trying to log? You may as well just remove that line entirely.
Second, what are you expecting here?: success: alert("success") What's going to happen here is the alert() is going to execute immediately (before the AJAX call is even sent) and then the result of the alert (which is undefined) is going to be your success handler. You need a handler function to be invoked after the AJAX response, and that function can contain the alert.
Something like this:
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: function() { alert("success"); },
error: showError
});
(To illustrate the difference, compare your current success handler with your current error handler. One of them invokes the function with parentheses, the other does not. You don't want to invoke a handler function right away, you want to set it as the handler to be invoked later if/when that event occurs.)

Javascript functions keeps executing even after updating the DIV

I have certain content that gets updated using ajax on that Id, for example, let's suppose I have a complete main page and inside the body I have this code:
<div id="content">
<button onclick="update1()"></button>
<button onclick="update2()"></button>
</div>
<script>
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
</script>
<script src="js/script.js"></script>
And the index.html of Page1 contains some code like this:
<button onclick="update1()"></button>
<button onclick="update2()"></button>
<div id="page1"> .....</div>
And the index.html of Page2 contains some code like this:
<button onclick="update1()"></button>
<button onclick="update2()"></button>
<div id="page2"> .....</div>
And the script.js contains some code like this:
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
});
What I want to do is when the button is pressed to call Ajax that gets the index.html from Page1 and puts it inside the id content, run a script.js this script only executes when the id page1 exists, I have found this trick from this answer, by using an if with jQuery for example if($('#page1').length ){my sj code} the javascript code runs only when that id exists, but unfortunately when I click the button to get the Page2 that has another id page2 that code keeps running, is there a way to stop this js code when that div is updated???
The function is not stopping because the interval will not stop firing unless you clear it, using clearInterval() function.
just put all your JS code in one file like this:
$(document).ready(function() {
var the_interval = setInterval(function() {
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}, 2000);
function stopTheInterval(){
clearInterval(the_interval);
}
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
stopTheInterval(); // we stop the first interval
}
});
}});
what I did here is saved the interval number in a variable, and created a new function to clear it.
next, all I did was put my new function in your update2() function, so once I get the data back I clear the interval and stop the repeating function.
script.js
dont use setInterval.
function some_function(){
$.ajax({
url: "someapi",
type: "POST",
dataType: "json",
success: function (result) {
console.log(result)
}
});
}
And call above function in update1.because you want it only when page1 updated
<script>
function update1(){
$.ajax({
url:"Page1/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
some_function() // call function here
}
});
}
function update2(){
$.ajax({
url:"Page2/index.html",
type:'GET',
success: function(data){
$('#content').html((data));
}
});
}
</script>
Try using update1().stop()
in starting of update2 function

How to make an AJAX call to an html element?

What I want to do is pretty simple. I want to make an AJAX call to a specific html class, so that whenever the html page is loaded, jquery will make an AJAX call to that specific html div class.
For example:
<div class="targeted"></div>
In jquery:
$('.targeted')
I know that the syntax to make an AJAX call is:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
console.log(data);
}
});
But how do I implement this AJAX call to the $('.targeted') whenever the page is loaded?
Thanks
If you mean you want to display the result of the ajax call in the element, you update the element from within the success callback:
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
That example assumes
You want to replace the content of the element (rather than adding to it); more options in the jQuery API.
data will be HTML. If it's plain text, use .text(data), not .html(data). If it's structured data, then of course you'll need to do more work to put the information in the desired form.
window.onload = function() {
yourFunction();
};
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
OR Drectly you can pass that method in document ready it will execute automatically
$(document).ready(function(){
//This will execute onload oof your web page what you required
yourFunction();
})
function yourFunction(){
$.ajax({
type: "GET",
url: "/api/something",
success: function(data) {
$('.targeted').html(data);
}
});
}
For when the page is loaded, you use:
$( document ).ready(function() {
console.log( "ready!" );
});
Inside the document ready, you put your AJAX call. If the result you get is in JSON format, you need to include the dataType as well like this:
$.ajax({
method: "GET",
url: "/api/something",
dataType: "json"
})
.done(function( data ) {
$('.targeted').append(JSON.stringify(data));
});
If the result is not JSON, then you can just append the data.
Also note:
The jqXHR.success(), jqXHR.error() and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail() and jqXHR.always() instead.
Please look at the jQuery documentation.
you can use jquery load like this:
$(".targeted").load('/api/something');
if you want to wait untill after the page is loaded, wrap it with window load like so:
$(window).load(function () {
$(".targeted").load('/api/something');
});
P.S. $(window).load(..) and $(".class").load(url) are two different functions
You can do:
$(function() {
$.ajax({
type: "GET",
url: "/api/something",
})
.done(function(data) {
$('.targeted').text(data);
});
});

jQuery is not getting applied

I am working on notification system and loading html notification body from database to views which populate as follows:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and applying jQuery function which I already defined on same page is like this:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
});
So when user click on button it's not work even not showing alert.
But things gets more interesting when I inject above jquery function from chrome console while view is loaded and button start working fine and shows alert too!
I am not getting the point which not letting things work!
It's because your acceptingRequest function is visible only inside anonymous jQuery(document).ready callback.
So when you click the button acceptingRequest is not visible.
Solutions keeping jQuery(document).ready(function() {})
To solve this bind the handler inside the callback using $('button.acceptinvite').on('click',acceptingRequest)
or use an anonymous callback (something like this):
$('button.acceptinvite').on('click',function(){
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
});
In both cases remove onclick="acceptingRequest();" since it's no longer needed.
Another option is to make acceptingRequest visible outside using a global variable (it's not a good practice anyway):
acceptingRequest = function () {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
Now acceptingRequest is visible outside jQuery().ready and you can do onclick="acceptingRequest();"
Solutions without jQuery(document).ready(function() {})
If you don't need the DOM to be completely loaded (like in this case) you can remove
jQuery(document).ready(function() {}) and just write your function from in head, so they are visible to the button.
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
//Etc.
}
</script>
Let me know if this was useful.
I think you are defining the function acceptingRequest() on document ready, but you are not really calling it. Try adding:
acceptingRequest();
just after the definition of the acceptingRequest() function. The result would be:
// Accept invitation button click
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
acceptingRequest();
});
It is because this string
<button class="acceptinvite btn btn-primary" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
will be proceded by the browser earlier than the definition of your acceptingRequest function. 'acceptingRequest' in your code will be defined asynchronously when document ready fired. So browser can't assign it with the click listener. Try to put your script exactly before </body>(and after jQuery script) and without jQuery(document).ready
<script>
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
</script>
</body>
Function defined in ready state can be used in it's own scope.So you can use acceptingRequest() method in ready state.
in my view below code is bestpractice in event binding:
<form id="acceptInviteForm" method="POST">
<input type="hidden" name="accountId" value="6">
<input type="hidden" name="operation" value="acceptinvite">
<button class="acceptinvite btn btn-primary" id="acceptInviteButton" href="/acceptinvite" onclick="acceptingRequest();">Accept Invitation</button>
</form>
and in ready state:
jQuery(document).ready(function() {
function acceptingRequest() {
var formData = jQuery("#acceptInviteForm").serialize();
alert(formData);
jQuery.ajax({
type: "POST",
url: "/acceptinvite",
data: formData,
dataType: "json",
beforeSubmit: function() {
jQuery(this).attr({"disabled":"disabled"});
},
success: function(data) {
alert("Success");
},
error: function() {
alert("Got error while accepting invitation, reload or contact administrator!");
}
});
}
$("#acceptInviteButton").on("click",acceptingRequest);
});

Form submitting to wrong function when changing class dynamically

I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
$(this).removeClass('InvoiceForm');
$(this).addClass('UpdateInvoice');
$(this).find('.btn').val('Update');
$(this).find('.id').val(data.invoice_id);
$(this).find('.btn').removeClass('btn-default');
$(this).find('.btn').addClass('btn-danger');
$(this).find('.AddRow').removeClass('hide');
$(this).find('.invoiceDetails').html(data.returnedData);
$(this).parent().next().find('.grade').focus();
}
});
return false;
};
Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){
var r = confirm("Are you sure you want to make this update?");
if (r == true) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
alert('This row has been updated');
$(this).find('.total').html(data);
}
});
} else {
}
return false;
});
The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>
<div class="result" />
Script:
$(function () {
$('.new').click(function (e) {
$('.result').text("Im new !");
$(this).removeClass("new");
$(this).addClass("update");
// Bind UpdateInvoice's click event on the fly
$('.update').live(bindUpdate());
});
function bindUpdate() {
$('.update').click(function (e) {
$('.result').text("Update me !");
});
}
});
jsfiddle's demo

Categories