1

I'm retrieving the number of rows contained by a table in my database with the following function using JSON.

function rowCount()
{
    $.ajax({
        headers: { 
                'Accept': 'application/json',
                'Content-Type': 'application/json' 
            },
        datatype:"json",
        type: "GET",                    
        url: "/wagafashion/ajax/CmsRowCount.htm",
        success: function(response)
        {
            $("#rows").val(response);
        },
        error: function(e)
        {
            alert('Error: ' + e);
        }
    });
}            

In the success handler, the response is arriving as expected. There is no problem on the server side.

The response is just mapped with the long type of Java which represents the number of rows in a database table.

I'm putting this response in a hidden field whose id is rows using $("#rows").val(response); in the success handler.

The above function is invoked when the form is submitted using the following jQuery function.

$(function() {
    $('#dataForm').submit(function() {

        rowCount();  //Invokes the above function that makes a JSON request.
        var rows=$("#rows").val();
        alert("rows = "+rows);

        return false;
    });
});

The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time. It alerts the actual value only when I press the submit button once again (without a page refresh).


Also tried to replace the preceding function with the following.

$(function() {
    $('#dataForm').submit(function() {

        rowCount();  //Invokes the first function that makes a JSON request.     

        var form = $(this),
        url = form.attr('action'),
        rows = form.find('input[name="rows"]').val();

        alert("rows = "+rows);

        return false;
    });
});

But it didn't work either. Why does this happen? What is the way of retrieving the correct value of that hidden field into the preceding jQuery function?

Tiny
  • 27,221
  • 105
  • 339
  • 599
  • Ajax is **asynchronous**. You are trying to access the data **before** the response was received . Please have a look at http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call-from-a-function. – Felix Kling Feb 02 '13 at 20:59

1 Answers1

2

The alert box attempts to alert the value contained by the hidden field (which is the JSON response as described above) but it is empty for the first time.

Ajax calls are asynchonrous. When you call rowCount, you start the call, but then rowCount returns and your code continues. The call doesn't complete until later (which is why ajax accepts a callback).

If you trigger the next step in what you're doing from the callback, you'll have the value. You typically do this by having rowCount accept a callback of its own, like this:

function rowCount(callback)          // <==== Accept the callback
{
    $.ajax({
        headers: { 
                'Accept': 'application/json',
                'Content-Type': 'application/json' 
            },
        datatype:"json",
        type: "GET",                    
        url: "/wagafashion/ajax/CmsRowCount.htm",
        success: function(response)
        {
            $("#rows").val(response);
            callback();              // <==== Call the callback
        },
        error: function(e)
        {
            alert('Error: ' + e);
            callback();              // <==== Probably want to give it a value telling it things failed
        }
    });
}

Then using it:

$(function() {
    $('#dataForm').submit(function() {
        var form = $(this); // <== Grab this outside the callback

        rowCount(function() {

            var url = form.attr('action'),
                rows = form.find('input[name="rows"]').val();

            alert("rows = "+rows);
        });

        return false;
    });
});

If you want to decide whether to allow the form to be submitted on the basis of the callback, you'll have to always cancel the submission, and then trigger submitting it programmatically from the callback if you want to allow it.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875