0

I am trying to assign value I receive from the php file to the jquery variable. The php file runs a loop and echos out a value. I am trying then to store the value in the jquery variable but I am getting NaN result back. How can I assign the value echoed from the php file into the variable in the jquery function?

    var increment;

    event.preventDefault();
    $.ajax({
            type: 'POST',
            url: 'increment.php',
            data: $(this).serialize(),
            dataType: 'text',
            success: function (data) {
                    //console.log(data);
                    data = increment;
            }
    });
Code_Ed_Student
  • 1,180
  • 6
  • 27
  • 67
  • possible duplicate of [How to return AJAX response Text?](http://stackoverflow.com/questions/1225667/how-to-return-ajax-response-text) – Quentin Dec 04 '13 at 06:40

2 Answers2

1

You should be using

increment = data;

instead of

data = increment;

Also one more thing to note here is the request nature. Since the ajax request is asynchronous accessing the variable outside might show unexpected result. You have to access the variable once the ajax request is successful (inside success callback).

rahul
  • 184,426
  • 49
  • 232
  • 263
  • Oh I see now. I may have to assign the result to an input field and then assign the value of that input field to `var increment` – Code_Ed_Student Dec 04 '13 at 06:49
  • You don't have to create an additional input field for this. Just make sure that you are assigning the response only when the request is complete. – rahul Dec 04 '13 at 06:51
0

do like so,you should assign data recieved to increment var:

    var increment;

event.preventDefault();
$.ajax({
        type: 'POST',
        url: 'increment.php',
        data: $(this).serialize(),
        dataType: 'text',
        success: function (data) {
                //console.log(data);
                increment = data ;
        }
});
Hamed mayahian
  • 2,465
  • 6
  • 27
  • 49