overwrite javascript variable from ajax call [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I want to overwrite the status variable from the ajax call.. i tried in this way but its not overwriting the status variable... Please help me.
function myfunction()
{
var status = "";
$.ajax({
type: 'POST',
url: "<?php echo base_url() ?>login/ajaxsessioncheck/",
success: function(data)
{
status="new value";
}
});
alert(status)
return status;
}

A possible solution could be something like,
function ajaxsessioncheck(myCallback)
{
var status = "";
$.ajax({
type: 'POST',
url: "<?php echo base_url() ?>login/ajaxsessioncheck/",
success: function(data)
{
//status="new value";
myCallback(data);
}
});
// alert(status)
// return status;
}
So what you probably want to do is,
if(ajaxsessioncheck()){
//then session still exists
}
but you should actually do something like,
ajaxsessioncheck(function(data){
status = "new value";
alert(status);
//go to next page
//or do next action that is only allowed if session still exists
});
Also the thread mentioned in the comment by Arun P Johny ,How do I return the response from an asynchronous call? ,provides a thorough explanation of how to tackle this specific problem and the issues related to the synch and asynch behaviour of ajax requests.

You're lacking basic understanding of how AJAX calls work. AJAX calls are asynchronous. Your code keeps executing while the call is being processed. The code inside your success callback will only execute after the current executing code finishes (when javascript relinquishes control back to the browser) and when the AJAX request is finished. If you put the alert after status = "new value" you'll see it gets the right value.

FIDDLE
An ajax call is Async by default so when you return status the new value for status is probably not set. Either make your ajax call synchronous or define your status variable in the outer scope and then just set it inside the success callback.
var status = "";
alert(status);
function ajaxsessioncheck(){
$.ajax({
type: 'POST',
url: "<?php echo base_url() ?>login/ajaxsessioncheck/",
success: function(data){
status="new value";
alert(status);
// write code for additional functionality that needs to be executed after the new value has been set for status here.. of just make a call to another function that handles further operations..
doSomethingWithNewStatus();
}
});
}
ajaxsessioncheck();
function doSomethingWithNewStatus() {
alert("Here is your new status " + status);
}

Related

Success data returns null from AJAX GET type [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I am using the following codes to get success data into a variable:
var compdet = null;
$.ajax({
url: uri2 + "/" + $("#textbox_id").val(),
type: "GET",
cache: false,
success: function (data) {
compdet = data;
}
});
And to check if my var compdet has value in it, I added:
console.log(compdet);
Sadly, it returns JUST null. So I tried putting the console.log into
success: function (data) { console.log(data); }
And it returns the output that I want to see. Anyone who can explain this to me?
I realized something here. You can actually make Javascript function async and await AJAX calls.
For example:
async function func_name() {
await $.ajax({
// some codes here
});
}
JavaScript execution is synchronous but AJAX is asynchronous. If you have any code after AJAX it might execute before completing the AJAX. That's why you are getting the value null.
In this scenario you can execute your next code stuff inside success() callback or call another method to execute the next code chunk.
An example with method call:
function next(compdet) {
// code stuff
}
$.ajax({
url: uri2 + "/" + $("#textbox_id").val(),
type: "GET",
cache: false,
success: function (data) {
next(data)
}
});
See the difference between synchronous vs asynchronous.

JQuery / Ajax isset (MyFunction) always returns false

I've written a php function to generate a random math question for anti-spam purposes. It sets a question and the answer to two session variables.
In the HTML file I call the function in the document ready event and send the results to the div for the question, this works fine.
$(document).ready(function(){
$.ajax({
url: "sec.php",
type: "POST",
data: {"GetQA":""},
success: function(data) {
$("#no_spam_Q").replaceWith(data);
}
});
});
What I'm having trouble with is refreshing the text of the question after the user clicks a submit button.
jQuery:
$(document).on("click", "#submit", function () {
var comment = document.getElementById('comment').value
var no_spam = document.getElementById('no_spam').value
$.ajax({
type:"POST",
url: "comments-set.php",
dataType: "html",
data:{no_spam, comment:comment},
success: function(data){
$("#display").html(data);
$.ajax({
url: "sec.php",
type: "POST",
data: {"GetQA":""},
success: function(data) {
$("#no_spam_Q").replaceWith(data);
}
});
}
});
});
Here the nested ajax call is supposed to refresh the question & answer but it always appears to fail.
PHP:
session_start();
Function GetQA($str){
// some code to generate the question & answer
return $secFinal;
}
if (isset($_POST['GetQA'])) {
echo GetQA($_POST['GetQA']);
}else{
echo "not set";
}
The php always returns "not set" and so the anti-spam question text doesn't change. In another PHP file that checks the answer I echo the right answer if a wrong answer is given (just for debugging). The confusing thing is even though "not set" is being returned a new answer is generated, because entering the same answer twice fails my check and the echo message about the correct answer is shown.
I'm guessing this has something to do with the query being async but despite reading the API and other SO questions for many hours I'm none the wiser on how to solve it.
Here's what I've tried:
deferred.done()
Moving the nested call to GetQA from the success function to a
.mouseup() event for the submit button
Moving the function from success and running it after the call to comment-set.php
On another note I'm passing an empty string to GetQA because the the compiler complains if i just use data: {"GetQA"} - how can I call a function without paramenters?

Javascript / jQuery from async: false to async: true and still get data from outside [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have a few functions that grab data using ajax and I can then get the result data from outside the function when needed.
Here is one example:
function myfunction() {
jQuery.ajax({
url: someurl
method: 'GET',
async: false,
success: function(result) {
myresult = result;
}
});
return myresult;
};
And this from outside I get the data like this:
myvar = myfunction();
Doing it this way I am able to get the data outside the function.
I have searched google and stackoverflow and I still can't understand it so I thought adding a function that I'm already using might help me understand better how to do this.
How can I convert this code so that when I set async to true I'm able to get the data from outside the function?
How can I convert this code so that when I set async to true I'm able to get the data from outside the function?
Simple answer, don't. You're approaching the problem in the wrong way.
Instead of trying to get data available outside the function, you could provide a callback function which the data should be passed to:
function myfunction(callback) {
$.ajax({
url: someurl
method: 'GET',
success: callback
});
};
myfunction(function(data) {
// work with the data retrieved from the async request here...
console.log(data);
});
Note: this pattern is a little redundant in this example as you could just give the anonymous function directly to the success property. In a real scenario you'd probably want to execute some actual generic logic in the success handler before calling the provided callback function.
Alternatively you could return the deferred object from the jQuery AJAX request and then use a done() handler to be executed when the object is resolved:
function myfunction() {
return $.ajax({
url: someurl
method: 'GET'
});
};
myfunction().done(function(data) {
// work with the data retrieved from the async request here...
console.log(data);
});
In either case the logic to follow is that the data from the request should be provided to the required function instead of being made globally available.

Javascript variable state after ajax request [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm new in the web programming and I don't fully understand some simple things.
Suppose we have following ajax request:
var records = [];
$.ajax(
{
url : "index",
dataType: 'json',
success: function (response)
{
records = response;
}
});
alert(records.length);//This displays 0
alert(records.length);//This alert correctly displays number of records
The problem is that the array records appears empty, if I try to use them immediately after calling ajax (first alert displays zero length, while second alert displays correct length). What's the problem and how to solve it?
You just need to put your alert inside the success callback.
var records = [];
$.ajax(
{
url : "index",
dataType: 'json',
success: function (response)
{
records = response;
alert(records.length); // will always be correct
}
});
In your example, the behavior will be unpredictable and will depend on how fast the call returns.
The A in Ajax stands for Asynchronous
The success function doesn't trigger until the HTTP response comes back.
When the first alert fires, it hasn't come back. In the time it takes for you to click OK to that alert, the response has arrived so the success function has run by the time the second alert fires. (alert is a blocking function).
Do your work on the data in the success function, not immediately after sending the HTTP request.

Can not change variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have some JavaScript code (below).
In every case, at the end of the loop the $sid should be zero, but "alert($sid)" always give me 200. I can't find an error in my code. Could you please help me?
Thanks in advance.
$sid = 200;
$canAppend = 0;
$iPage = 1;
while ($sid && $canAppend==0 && $iPage==1) {
alert($sid);
$.ajax({
url: "tmp/result1.html",
success: function(html)
{
if(html)
{
$("#inzeraty").append(html);
$('div#loadmoreajaxloader').hide();
$sid = 0;
}
},
error: function()
{
$sid = 0;
}
});
}
The issue is that the ajax call is asynchronous. JavaScript puts this makes the request to the server and then continues on to the next line of code. Your success and error callback functions are not being called until after JavaScript has completed execution of your while loop.
Furthermore, the structure of the code doesn't make any sense at all (sorry, not trying to be rude). The $canAppend and $iPage variables are not used or changed. What this code will do is enter into a loop and never exit. Why is this? It's because the call to $.ajax() is non blocking. It won't wait there until the request is completed, it will continue on. Since JavaScript is (essentially) single threaded the callbacks for error and success CAN'T be executed until the current execution process is completed. Because the success and error handlers can't be run the $sid can't be set. Because $sid can't be sent the code can't exit the while loop.
I don't see how you code is actually making use of the while loop. Instead, just call the $.ajax() function and handle the results in your success handler. Try this on for size to help you better understand what's going on:
$sid = 200;
alert("$sid is 200: " + $sid); // you'll see this first
$.ajax({
url: "tmp/result1.html",
success: function(html)
{
if(html)
{
$("#inzeraty").append(html);
$('div#loadmoreajaxloader').hide();
$sid = 0;
alert("$sid is now 0: " + $sid); // you'll see this third if html is not false
} else {
alert("$sid is STILL 200: " + $sid); // you'll see this third if html is false
}
},
error: function()
{
$sid = 0;
alert("you got an error, but $sid is now 0: " + $sid); // you'll see this third if there's an error
}
});
alert("$sid is still 200: " + $sid); // you'll see this second
By default ajax calls are asynchronous and the success or error functions are postponed until after $.ajax has retrieved tmp/result1.html. In your case, they'll be postponed forever because the while loop will keep the hand, $sid will remain equal to 200 and you'll keep piling up ajax calls.
A quick fix is to make your ajax call synchronous:
$.ajax({
url: "tmp/result1.html",
async: false,
success: function(html)
// etc.
Rewriting your code to avoid a mix of while loop and ajax might be a better idea (but I don't know your specific context).

Categories

Resources