I'm trying to store data from ajax (jquery) response to variable because I need to use it later in code.
The accepted Answer has 'var controlNumber = $data;
' declaration inside Ajax Success Callback, which wouldn't accessible from Outside of Ajax Function. That statement is very clear that You Can't get'controlNumber
' variable outside of
Ajax Callback Success Function, because it's a local variable
, declared inside a function
.. So the best would be declare a Global JavaScript Variable and reassign value again inside Ajax Success callback.
By they way if I follow the line "I'm trying to store data from ajax (jquery) response to variable
" then the accepted answer is fine.
But if I follow the statement "I need to use it later in code
" creates 2 assumptions here..
1 - if your code is still on inside ajax function - Then Fine
2 - if your code using ajax response on outside ajax function, then you won't be able to get 'controlNumber
' value. if you try you will get 'undefined
'
So what is the best way to deal Ajax Response, Create a function which responsible to return ajax object with success or error response. I am sure it didn't sound clear.. ;) No worry here is more or read more :)
First of all understand what is ajax and how it works...?
AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging
small amounts of data with the server behind the scenes. This means
that it is possible to update parts of a web page, without reloading
the whole page.
Content Reference: W3CSCHOOL
Kindly notice the word 'asynchronously
', it means if you call ajax and trying to use ajax response data at next line then you can't. Because, DOM will not wait for Ajax Response & script won't stop to wait to complete process of ajax it will continue & you will get 'undefined' until you don't make ajax request with 'async: false
' option. *But as of jQuery 1.8, the use of async: false is deprecated! Wohooo!! Sounds Great!!! @-@ *
Many people also suggest to use global var and set variable value later inside ajax success callback to use. But the problem is
asap you try to use variable after next ajax call then it will produce same error as describe above.
So the best method would be to Store or Use or Get Ajax Response by
using a function which returns ajax object and you can later use that
ajax object with 'YourAjaxObject.success(callback)
' anywhere
any time in your application without any worry. You can also use/put
your functions which requires ajax response inside ajax success
callback.
A very simple example I am sharing with you to understand this better..
// global var declare here
var collect = null;
$(document).ready(function() {
var btn = $('#mySubmitButton');
btn.on('click', function(e) {
e.preventDefault();
$.post('url.php', {
id: 1
}, function(ajx_res) {
// store ajax response in global var
collect = ajx_res;
// 'I will execute last with collect = ajx_res data
alert(collect);
});
// 'I will execute first with collect = null data
alert(collect);
// When btn click again, I will execute first with previous ajx_res data
alert(collect);
});
});
$(document).ready(function() {
var btn = $('#mySubmitButton');
btn.on('click', function(e) {
e.preventDefault();
$.post('url.php', {
id: 1
}, function(ajx_res) {
// now I am local var
var collect = null;
// store ajax response in local var
collect = ajx_res;
// 'I will execute last with collect = ajx_res data
alert(collect);
});
// I will execute first with collect = undefined
alert(collect);
// When btn click again I will execute first with same collect = undefined
alert(collect);
});
});
/**
* Ajax Request & Return Response
* @param url _url action url
* @param object options send payloads
*/
function AjaxCall(_url, _options) {
return $.ajax(_url, {
method: 'POST',
data: _options,
error: function(xhr, ajaxOptions, thrownError) {
alert("Request Error:" + thrownError + " with Status" + xhr.status);
}
});
}
// I am again as global var
var collect = null;
$(document).ready(function() {
var btn = $('#mySubmitButton');
// first button, click
btn.on('click', function(e) {
e.preventDefault();
// return ajax object, and can be use within entire application via callback
collect = AjaxCall(_url, _options);
// use success callback to retrieve data
collect.success(function(ajx_res) {
// I will execute first with ajx_res
alert(ajx_res);
});
});
var btns = $('#mySubmitButtons');
// on another button, another click
btns.on('click', function(e) {
e.preventDefault();
// using previous ajax obj to get data
collect.success(function(ajx_res) {
// I will execute first with previous ajx_res
alert(ajx_res);
});
});
});
// I am again as global var
var collect = null;
$(document).ready(function() {
var btn = $('#mySubmitButton');
// first button, click
btn.on('click', function(e) {
e.preventDefault();
// return ajax object, and can be use within entire application via callback
collect = AjaxCall(_url, _options);
});
var btns = $('#mySubmitButtons');
// on another button, another click
btns.on('click', function(e) {
e.preventDefault();
// using previous ajax obj to get data
collect.success(function(ajx_res) {
// I will execute first with previous ajx_res
alert(ajx_res);
});
});
});
So in short:
1 - You can't use local variable (which declared inside function or
loop) out side of their declaration area.
2 - Ajax don't return the response, you can get the response by using
callbacks.
3 - Store Ajax response in global variable to use outside of ajax
callback function.
4 - If any code, function depends on ajax response, put them inside
ajax success callback.
5 - If any specific functions needs ajax response value, then call
those functions inside success callback & pass ajax response as
parameters or you can use 'Injection Techniques' (function to function
with same parameter) e.g.
function Hello (ajx_res) {
alert (ajx_res);
// send in another function
Foo (ajx_res);
}
function Foo (ajx_res) {
alert (ajx_res);
// send in another function
Bar (ajx_res);
}
function Bar (ajx_res) {
alert (ajx_res);
}
So my answer would be for this Question use Ajax Object & Get response by Callbacks.
/**
* Ajax Request & Return Response
* @param url _url action url
* @param object options send payloads
*/
function AjaxCall(_url, _options) {
return $.ajax(_url, {
method: 'POST',
data: _options,
error: function(xhr, ajaxOptions, thrownError) {
alert("Request Error:" + thrownError + " with Status" + xhr.status);
}
});
}
$(document).ready(function() {
$("#submitReg").click(function() {
var email = $("#email").val();
var password = $("#password").val();
var confpassword = $("#confpassword").val();
if (!email || !password || !confpassword) {
swal({
type: "error",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Prosím vyplňte všetky polia!"
});
} else {
var ajaxObj = AjaxCall("./php/register.php", {
email: email,
password: password,
confpassword: confpassword,
});
// your ajax callback function for success
ajaxObj.success(function(response) {
var controlNumber = response;
if (controlNumber == '1') {
swal({
type: "success",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Registrácia prebehla úspešne."
});
} else if (controlNumber == '0') {
swal({
type: "error",
timer: 10000,
showConfirmButton: true,
confirmButtonText: "OK",
confirmButtonColor: "#f4511e",
title: "Mail už bol zaregistrovaný."
});
} else {
alert(controlNumber);
}
});
}
});
});
Hope this will clear doubts for beginners user who are not comfortable with ajax at first sight, first love :D ^_^ Tadaaa.. :)