'Is it possible to re-use an array taken from PHP via JSON in a $.ajax function?
Here is the deal: This area is a preparation for a dynamic chart where I'm opening a new select input when my first select input is selected. With its value(from the first), I'm doing a SQL query and getting the country data filtered by the first select. It is all working fine, but I do want to re-use this array which came from PHP to create up to 4 new more selects. As it is staying inside the $.ajax success, I'm not sure if I can use it outside.
Here is my code:
$(document).ready(function() {
$('#indicators').change(function() {
$('#country1').fadeIn('slow');
var indic_val = $(this).val();
$.ajax({
url: 'scripts/chart_handler.php',
dataType: "json",
type: 'post',
data: {'indicator' : indic_val},
async:false,
success: (function ( data ){
$.each(data, function(i, key) {
$('#country1').append('<option value="'+ key +'">'+ key +'</option>');
});
}),
});
});
});
Solution 1:[1]
pretty simple actually. Just declare a variable that is accessible outside the current AJAX call and is therefore persistent for that scope (inside the anonymus function inside the ready-function).
$(document).ready(function() {
var jsonData; // this is the variable where we will store the data
$('#indicators').change(function() {
$('#country1').fadeIn('slow');
var indic_val = $(this).val();
$.ajax({
url: 'scripts/chart_handler.php',
dataType: "json",
type: 'post',
data: {'indicator' : indic_val},
async:false,
success: (function ( data ){
jsonData = data; //that's all what you need
$.each(data, function(i, key) {
$('#country1').append('<option value="'+ key +'">'+ key +'</option>');
});
}),
});
});
});
Solution 2:[2]
Yes you can. Create a function and pass the data as argument:
success: (function ( data ){
myFunction(data);
$.each(data, function(i, key) {
$('#country1').append('<option value="'+ key +'">'+ key +'</option>');
});
}),
function myFunction(data){
// do your stuff
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | halfer |