0

My code :

function send() {

    var nop = 6;

    var send_this = {
        nop: nop
    };

    $.ajax({

            type: "GET",
            data: send_this,
            url: "example.com",
            success: function(r) {

                var obj = JSON.parse(r);

                nop = obj.nopval;

                /* some other stuffs*/

            }

        )
    };

}

Now, since I already set the nop to 6 , it will pass 6. But on returning, the json response obj.nopval will return 12 which I want to set to nop. So that next time it sends 12 and return 18 and so on....

What happening here is , it is sending 6 and returning 12 but sending 6 again and returning 12 again. The variable is not getting updated.

JLRishe
  • 99,490
  • 19
  • 131
  • 169
nick
  • 67
  • 2
  • 10

2 Answers2

6

You are declaring and initializing the nop variable inside your function, so it will start off at 6 every time the function is called. nop needs to exist somewhere outside your function in order for the changes to persist:

var nop = 6; // outside the function

function send() {
    var send_this = {
        nop: nop
    };

    $.ajax({
        type: "GET",
        data: send_this,
        url: "example.com",
        success: function(r) {
            var obj = JSON.parse(r);
            nop = obj.nopval;
            /* some other stuff*/
        }
    });
}
JLRishe
  • 99,490
  • 19
  • 131
  • 169
1

You need to define your variable outside the function , you are using it in the ajax callback function so everytime you run the function it will reset the value to 6.

Hasan Al-Natour
  • 1,936
  • 2
  • 14
  • 22