Html Ajax button not doing anything - javascript

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.)

Related

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

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

JQuery wrong ajax done callback fired

I have a strange situation going on with ajax callbacks.
Call A works fine (I can see the server calls in the right place), and the done callback is fired correctly.
Call B call works fine (I can see the server calls in the right place), but then A's done callback is fired!
Here's the code:
A:
$(document).ready(function () {
$('#beta_signup_form').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
url: $(this).attr('action'), //submits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON", // you want a difference between normal and ajax-calls, and json is standard
type: 'POST'
}).done(function(json){
console.log("in the beta signup form success function!!!!");
})
.fail(function () {
console.log("--------> beta signup modal callback error");
});
return false; // prevents normal behaviour
});
});
and code B:
$(document).ready(function () {
$('#twitter_sign_up').submit(function() {
var valuesToSubmit = $(this).serialize();
$.ajax({
url: $(this).attr('action'), //submits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON", // you want a difference between normal and ajax-calls, and json is standard
type: 'POST'
}).done(function(json) {
console.log("in success for modal B...");
}).fail(function () {
console.log("--------> modal B callback error");
});
return false; // prevents normal behaviour
});
});
What's going on here???
OH man... I just figured it out.
So I had:
<div id="twitter_sign_up">
<form id="beta_signup_form" ...>
...
</form>
</div>
My fault for copying html!

Only show changes after JS function ends?

I have some JavaScript that runs after a successful AJAX call:
$.ajax({
type: "POST",
url: "CalendarServices.aspx/UpdateFilter",
data: 'id=' + this.value + '&checked=' + $(this).is(':checked'),
success: function (data) {
$('#calendar').fullCalendar('refetchResources');
$('#calendar').fullCalendar('refetchEvents');
}
,
error: function () {
}
});
I do not want the user to visually see the changes of $('#calendar').fullCalendar('refetchResources');until $('#calendar').fullCalendar('refetchEvents'); has been called... is that possible?
This is because I inject some html in a callback for $('#calendar').fullCalendar('refetchEvents'); that gets destroyed when resources are fetched, so there is a small flicker.
Is there some way to do this?

Calling a function from if block in success

Hello fellow programmers. I am newbie to jquery ajax.
How do i call function checkreturn() from if block or is it possible to access msg outside the success if yes then please let me know how. I need it because only if condition proves true i have to enable the subsequent textbox. Here is my code.Thanks in advance for your time and reply.Rajesh.
<script type="text/javascript" >
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e){
var uname= $("#<%=Username.ClientID%>").val();
var sq=$("#<%=SecQuest.ClientID%>");
var sqtn = $("#<%=SecQuest.ClientID%> option:selected").text();
var sans=$("#txtAns");
var msgbox = $("#Dstatus");
$.ajax({
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
}
else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
});
}
</script>
You have a typo in your checkreturn function. You want to use removeAttribute, instead of removeAtrribute (double t,not double r).
Also, you can use jQuery functions:
function checkreturn(){
$('#txtAns').prop('disabled',false);
}
, instead of native DOM functions (document.getElementById, setAttribute):
not sure what why the normal way is not working but you could try forcing what the browser is supposed to do,
function checkreturn(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Becomes
window.checkreturn = function(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Then try calling via window.checkreturn(); or checkreturn(); you can also so try this the other way arround so you can leave your function and try calling window.checkreturn();
If none of these are working it would say your function is not entering the window(Global) scope for your page use Firebug or Inspector and try to all checkreturn(); see what exception you get back,
if you get a not found your not showing us some thing in your code maybe a closure or some thing
I'll look into it further but try setting async for the ajax call to false:
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e) {
var uname= $("#<%=Username.ClientID%>").val(),
sq=$("#<%=SecQuest.ClientID%>"),
sqtn = $("#<%=SecQuest.ClientID%> option:selected").text(),
sans=$("#txtAns"),
msgbox = $("#Dstatus");
$.ajax( {
async: false,
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
} else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
} );
}
Now, when the ajax call is made, the rest of the script will wait til it completes instead of how everything continues when async is true.

Categories