Hi I'm trying to do something with ajax.
function DoSomething(url){
$.ajax({
type: "GET",
url: url,
success: function(data) {
if(data.SessionExpired === true)
alert('SessionExpired');
else{
//DO Something
}
}
});
DoSomething else;
}
before clicking on alert box 'OK' "DoSomething else" is getting executing.
I want that this will execute only after clicking on alert ok or after "Do Something" block.
Could you please guide me ??
$.ajax calls are async be default, your code 'DoSomething' is executing because the ajax call doesnt hault execution until it returns.
Put your DoSomething() inside the ajax callback
function DoSomething(url){
$.ajax({
type: "GET",
url: url,
success: function(data) {
if(data.SessionExpired === true)
alert('SessionExpired');
DoSomething();
else{
DoAnotherThing();
}
}
});
}
Related
While using ajax call, I'm calling a function of showMessage() in the beforeSend method of $.ajax and inside the done method of $.ajax I'm calling hideMessage().
The issue is hideMessage() isn't hiding the Message popup. After that, if I execute this function from the console, it worked. Can anyone suggest why is this?
Jquery Version: 1.11.2
$.ajax({
type: 'GET',
url: '...',
dataType: 'json',
beforeSend: function(x) {
showMessage('Please Wait');
}
}).done(function(data) {
hideMessage();
});
function showMessage(text) {
var mv = null;
if ($('#messagePopup').size() == 0) {
mv = $('<div class="wait_popup" id="messagePopup"><div class="wait_div"><div class="wait_content"><div class="text_content"></div></div></div></div>');
$('body').append(mv);
} else {
mv = $('#messagePopup');
}
mv.find('.text_content').html(text);
mv.fadeIn();
mv.find('.wait_div').delay(400).show('clip');
}
function hideMessage() {
$('#messagePopup').hide('clip');
}
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.)
I have a page that popup a modal and using hidden.bs.modal event, I want to reload the same page contents i.e body tag html via ajax. I have the following code:
$("#actions-modal").on('hidden.bs.modal', function(){
alert(document.location)
$.ajax({
url: document.location,
type: "get",
sucess: function(data){
alert('hhhh')
return $("#body1").html($(data).find('#body1'));
},
error: function(xhr){
console.log(xhr);
}
})
})
In the above code, alert(document.location) works fine. However, both alert('hhhh') in success handler of the ajax and console.log(xhr) in the error handler of the ajax don't work at all. i.e there is no success nor error! Additionally, there is no any errors in the browser's console.
document.location will return you the object, So try using document.location.href which will return you the string of URL. Then the AJAX call will start working.
Remove the return from your success function. You don't need to return when changing the html of an element. The return is only required when doing something like this:
function getHTML()
{
$.ajax({
url: document.location,
type: "get",
sucess: function(data){
return data;
},
error: function(xhr){
return "Failed";
}
});
}
var myHTML = getHTML();
$('#body1').html(myHTML);
However, when you are immediately setting the html you don't need it.
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.
I'm trying to make a function that uses jquery's ajaxfunction to get some info from my ajax.php file.
code:
function ajaxIt(dataLine){
$.ajax({
type: "POST",
url: "ajax.php",
data: "ajax=true&"+dataLine,
success: function(msg){
console.log("[AjaxIt]: "+dataLine+" returned "+msg);
return msg;
}
});
}
if(ajaxIt("action=loggedIn")=="1"){
console.log("Logged In");
loggedIn=true;
initiate2();
}
The problem is that I can't get the success function to return all the way to the ajaxIt function. Could anyone shed some light onto how I could do something like that?
Thanks.
You need to invoke a callback function to process data that way:
function ajaxIt(dataLine, cb){
$.ajax({
type: "POST",
url: "ajax.php",
data: "ajax=true&"+dataLine,
success: function(msg){
if($.isFunction(cb))
cb.apply(null, [msg]);
}
});
}
ajaxIt("action=loggedIn", function(data){
if(data === "1"){
console.log("Logged In");
loggedIn=true;
initiate2();
}
});
$.ajax is asynchronous. This means that it will return right away, instead of waiting for the AJAX query to execute and retrieve a result from the server. By the time the message from the server arrives, your ajaxIt function has already finished working.
What you should use here is a continuation-passing style. Provide ajaxIt with a continuation: a function that explains what should be done once ajaxIt has finished working.
function ajaxIt(data, continuation) {
data.ajax = true;
$.post("ajax;php", data, function(msg) {
console.log("[AjaxIt]: returned "+msg);
continuation(msg);
});
}
ajaxIt({action:"logged-in"}, function(result) {
if (result == "1") {
console.log("Logged In");
loggedIn=true;
initiate2();
}
});