Code_Ed_Student
Code_Ed_Student

Reputation: 1190

Assign ajax request result to variable in the jquery function

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;
            }
    });

Upvotes: 0

Views: 518

Answers (2)

rahul
rahul

Reputation: 187030

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).

Upvotes: 1

Hamed mayahian
Hamed mayahian

Reputation: 2323

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 ;
        }
});

Upvotes: 0

Related Questions