I've got an AJAX function that works correctly but I can't seem to access variables that I'm declaring within the function later in the page. If you look at the below code, you'll see I alert the variable number_rows within the function which works but when I try to log it outside of the function, it comes back as 'undefined.'
var newData = "user_id=" + id;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
var number_rows = response;
alert(number_rows);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
console.log(number_rows);
I understand my scope may be off. I tried to move all of my code within the success function but that causing a bunch of other issues so the easiest thing would be to get the response variable to be a global variable that I could use throughout the rest of the page's code. I also tried something like this:
success:function(response){
$('body').append('<span class="ajax_response" id="' + response + '"></span>');
}
var number_rows = $('.ajax_response').attr('id');
console.log(number_rows);
But for some reason it isn't able to pick up the ID value immediately that way. I can confirm that the span does get made with the correct ID value but for some reason it doesn't handle it correctly. Any help with this would be greatly appreciated.
Thanks!