I have an ajax call in jquery which returns 4 different arrays.
3 of these arrays i want to use outside of the ajax success function and the data in the arrays should be accessible for certain click events.
I just don’t know the best way to handle the array variables.
some people say going global is a bad idea and other say its ok.. so
ajax success function:
does stuff with one of the arrays
array1, array2 needs to be used by other functions and click events
function display_results_1(){
$('#myDiv').html(array1.id);
}
$('#binfo').click(function(){
$('#client_info_div').dialog({
$('#myDiv').html(array2.id);
});
})
This is my ajax call:
$('#c_search').submit(function(){
data = ($(this).serialize());
$.ajax({
url: 'actions/get_company.php',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function(selected){
`doing stuff here`
})
})
Should I use separate Ajax calls to get the data when needed for each different function?
You definitely don’t want your variables in the global scope, but you could wrap everything in a function to prevent them from being in the global scope:
By doing this you’ll ensure that the code is also running on page load, notice the $() wrapping the function.
See http://api.jquery.com/ready/ for more info.
Contrary to the previous answers, going global is NOT a good idea. You may end up having multiple pieces of JavaScript using the same variables.