title: Declaring Variable within AJAX function and Calling It Later (jQuery)
body: <p>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.'</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>success:function(response){
  
          $('body').append('&lt;span class="ajax_response" id="' + response + '"&gt;&lt;/span&gt;');
  
      }
  
  var number_rows = $('.ajax_response').attr('id');
  console.log(number_rows);
  </code></pre>
  
  <p>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.</p>
  
  <p>Thanks!</p>