Changed variable value not available outside ajax request - jQuery [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have multiple fields in a form with same name, and I pass these values into ajax as;
$('#mybutton').click(function(){
var flag = 0;
$('input[name="myfield"]').each(function(){
var current = $(this);
var item = $.trim(current.val());
if(item != ""){
$.ajax({
type: 'POST',
url: 'ajaxhandler.php',
data: 'myitem='+item,
cache: false,
success: function(result) {
if(result == "true"){
flag++;
}
alert("stage1 = "+flag);//returns flag (1,2,3 etc)
}
});
}
});
alert("stage2 = "+flag);//returns 0. But I need same value as on the flag above
});
The flag is set to count the number of valid items, and is collected for further use. But outside ajax block, its not available. How can I solve this?

Your flag variable is local variable which declared inside of click event handler. And it will not be visible to outside of event handler. So you should simply declare it outside of event handler. If you want to use it inside of click event itself you can make your ajax query async:false or create function and call it after ajax call done.

EDIT:
As the Ajax request is asynchronous then the alert("stage2 = "+flag);
Is called right after your ajax call without waiting for the response. That is why flag=0

Related

How to declare variable outside of callback, modify it in the callback, then use modified value outside? [duplicate]

This question already has answers here:
Javascript - Stop form submit depending on ajax response [duplicate]
(2 answers)
jQuery preventDefault() not working inside AJAX call
(6 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 1 year ago.
I'm looking for a way to modify a variable declared outside of a callback, then use the modified variable after defining the callback. My intent is reflected in the code:
$('#my_form').submit(function() {
let my_condition
let data = $(this).serialize()
$.ajax({
method: 'POST',
url: '/my_url',
data: data
})
.done(function(json_response) {
if (json_response.my_variable) {
my_condition = true
}
else {
my_condition = false
}
})
// I'm looking for a way to guarantee `my_condition` is set by the AJAX before the below code is run.
if (my_condition) { // I know `my_condition` will be null because this line won't wait for the AJAX to finish and set `my_condition`.
return true
}
else { // The event handler will always hit this condition.
return false
}
})
I'm aware that I could add blocking sleep time before checking my_condition to wait for the AJAX. This is not a solution I'm looking for. I'm also aware that I could set my_condition based on inspecting data on the frontend. However, for reasons specific to my use case, data needs to be processed on the backend. Lastly, I want to avoid the AJAX setting async: false.
I know why the code above does not work. My question is, is there some way to achieve the desired result? I have a feeling there might be a solution that uses Promise, but I don't see exactly how that would be done.
Edit 1: The specific use case is with regards to form submission. I want the submit handler to return true or false, i.e., submit via the form's action attribute (when my_condition is true) or a different (AJAX) route (when my_condition is false) based on backend processing results of data.
Edit 2: This is indeed a duplicate of Javascript - Stop form submit depending on ajax response [duplicate]
I suspect (although specific problem is not clear) you want the form to submit only if you get a valid response in the ajax.
You can prevent the initial submit and then submit the form inside the done callback if condition is met.
$('#my_form').submit(function(e) {
// prevent submit
e.preventDefault()
let form = this;
let data = $(form).serialize()
$.ajax({
method: 'POST',
url: '/my_url',
data: data
})
.done(function(json_response) {
if (json_response.my_variable) {
// trigger native submit, will bypass this jQuery submit listener
form.submit()
}
else {
// do something else
}
})
})

jQuery callback after request made by another function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have never been very good at understanding JS callbacks, promises and all of these. Now I stumbled on one of these scenarios.
I have a text element. When clicked, it is made editable. When pressing enter, an AJAX request is made with the input value and then (here is my issue) the original text should be updated with the input.
$('#text-element').click(function() {
edit($(this), url, paramName);
});
function edit($element, url, paramName) {
// show the input, set up some UI events...
$input.keypress(function(key) {
// check if it is the correct key to submit the data
if (submit) {
var data = {};
data[paramName] = $input.val();
$.ajax({
url: url,
method: 'post',
data: data,
success: function(response) {
// ???
}
});
}
});
}
You could say: simple, just take the data from the response and replace the original text with the updated one. I can't/don't want to do that because I want the edit function to stay generic so it can be used in other scenarios, as you might have guessed by the use of the different arguments.
Also, in the context of the edit function we don't really know the shape of the response object, so we cannot handle it at that stage.
The right place where the response should be handled is the part where we click the text element, here we do know the context and we know the expected composition of the response.
So essentially, I would want to return (or whatever you do when dealing with promises, callbacks, async operations...) the response from the ajax success function, fetch that response in the click handler funtion and deal with it accordingly:
$('#text-element').click(function() {
edit($(this), url, paramName); // <--- this should "return" the response
var response = ...; // how do I fetch this response from the edit function
$(this).html(response.content); // the response we expect in this case would be a JSON response with a key "content"
});
I hope I could make myself understand. If I don't, please let me know so I can clarify the question.
Simply make a callback function:
$('#text-element').click(function() {
edit($(this), url, paramName,function(response){
this.html(response.content);
}.bind($(this)));//bind to keep the #text-element as this
});
function edit($element, url, paramName,callback) {
// show the input, set up some UI events...
$input.keypress(function(key) {
// check if it is the correct key to submit the data
if (submit) {
var data = {};
data[paramName] = $input.val();
$.ajax({
url: url,
method: 'post',
data: data,
success: function(response) {
callback(response);//whats your problem with callbacks? they are so easy...
}
});
}
});
}
By the way, if the user clicks twice, there are two keypress handlers registered, making the whole code a mess. So you may prevent that in a way...

How to make a function return data retrieved via AJAX [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
In my javascript file, I use the function above to get asynchronously a value calculated by the server:
function function2(userid)
{
$.ajax({
type: "POST",
url: "http://localhost/bghitn/web/app_dev.php/get_number_of_articles",
data:{id:userid},
cache: false,
success: function(data){
return data;
}
});
}
In fact, I call the function2 inside a set of functions:
function1();
var userid=.....
var x= function2(userid);
function3(x);
The problem:
as you see, function3 uses the data returned by function2. But it seems that function3 starts executing before the AJAX call is successfully finished. I tried to use the when function but in vain.
$.when(function2(userid)).done(function(){
function3();
});
How to make the next javascript code executes after the preceding AJAX request is successfully performed? Your advices are highly appreciates.
Option 1: You can always set your AJAX call to be synchronius, but be ready that the whole page stucks while waiting for response. just add parameter async: false to your set of parameters.
Option 2: Provide callbacks or put your future code inside success handler
Option 3: You can use defer/promise described here http://blog.mediumequalsmessage.com/promise-deferred-objects-in-javascript-pt1-theory-and-semantics

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.

Jquery On Click Function that Stops an Ajax Requests currently running [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Stop all active ajax requests in jQuery
I want to have a button that will abort any ajax requests currently being run. Below is a selector that grabs the right button. What should go in the place of the alert('test')?
$('#abort').click(function(){
alert('test')
});
You need to call abort() method - on each of the ajax calls !
var request = $.ajax({
type: 'POST',
url: 'someurl',
success: function(result){..........}
});
After that you can abort the request:
request.abort();
Create an array for each xhr object:
var xhrArray = new Array();
For every xhr object you need to add it to an array (where xhr is the object):
xhrArray.push(xhr);
Then on abort:
for( i = 0; i < xhrArray.length; i++){
xhrArray[i].abort();
stop = true;
}
The stop variable is for a loop that is elsewhere in my code to prevent more xhr objects from being created/sent.

Categories

Resources