-1

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!

MillerMedia
  • 3,651
  • 17
  • 71
  • 150
  • 4
    It's *a*jax, and even if the variable would be global it would not have a value until the ajax finishes. Moving your code into the success callback function is indeed the way to go. – Bergi Sep 12 '13 at 18:42
  • 1
    At [jquery learn scope](http://learn.jquery.com/javascript-101/scope/), you will find an answer. And make your xhr synchron. – Mamuz Sep 12 '13 at 18:43
  • Just make sure that "later" is after the success callback happens and you'll be golden. – Kevin B Sep 12 '13 at 19:22

3 Answers3

-2

Changed the scope of your variable.
Change async: false or wait till you get the response from server, then use the value.

var newData = "user_id=" + id;
var number_rows = "";  //Declare Here

    $.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
        async: false,
        success:function(response){

            number_rows = response;  //assign here
           alert(number_rows);

        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
        }
    });

console.log(number_rows);  //Use here
sudhansu63
  • 6,025
  • 4
  • 39
  • 52
-2

Yes, your scope is off. If you defining a variable inside a function, as you do, you cannot access it outside. Also your ajax call is async and any code you.

Put your console.log inside the success function otherwise it will probably log undefined even if you declare the variable globally outside of the function.

var newData = "user_id=" + id;
var number_rows;
$.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){
        number_rows = response;
        alert(number_rows);
        console.log(number_rows); // here, so we are sure it's set. 
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
        }
    });
loddn
  • 658
  • 1
  • 6
  • 16
-2

Just add to your configuration:

async:false

Your code maybe look like this:

var newData = "user_id=" + id;
var number_rows = ""; //This is a global variable

    $.ajax({
        type: 'POST', 
        url: 'ajax.php',
        dataType:'text', 
        data:newData,
        async:false, //<------This is the option you must add
        success:function(response){

            number_rows = response;  //<----- receive data from the server
           alert(number_rows);

        },
        error:function (/*stuff here*/){
            //stuff here
        }
    });

  //Check data
   console.log(number_rows); 

Good luck ^^!

Leo
  • 1,051
  • 2
  • 13
  • 33
  • why? I know it's not the best option; however, it resolves his problem. – Leo Sep 12 '13 at 19:30
  • 2
    because better options exist. I can suggest a hammer to someone with a box of screws and it would work. But a screw driver would be much better suited. – rlemon Sep 12 '13 at 19:32
  • Ok I will like to know how it can be done! I see that many people suggest that there are better options; however, i dont see examples. Could you give one? – Leo Sep 12 '13 at 19:34
  • The duped question is full of answers, and Bergi mentions in the OPs question comments how it should be done. – rlemon Sep 12 '13 at 19:34
  • Then point it out in your answer that there are better solutions. You would neither get downvotes nor such comments… – Bergi Sep 12 '13 at 19:34
  • 1
    @MichaelVidal [does my answer here help?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call/16825593#16825593) – Benjamin Gruenbaum Sep 12 '13 at 19:35
  • 3
    This is more like suggesting to use the Twilight novels as a hammer. – SomeKittens Sep 12 '13 at 19:35
  • 1
    I apologize to everyone who was offended by my answer. However, I have given this answer based on my limited experience I have so far. But also I think the wrong answers may be opening to new knowledge, not criticism and sarcasm. – Leo Sep 12 '13 at 19:42
  • 1
    @MichaelVidal No need to apologize, no one is offended by your answer. This is not what downvotes mean at all here :) Don't worry we know you were just trying to help (and we appreciate the attempt and good will to contribute). All downvotes mean is that we disagree with the usefulness of your answer to OP's issue. – Benjamin Gruenbaum Sep 12 '13 at 19:44
  • I know @BenjaminGruenbaum. Thanks for support. But I do not see reason why most programmers feel like "God" when they realize that someone has made ​​a mistake. Well leave it up to here. – Leo Sep 12 '13 at 19:50