arnas
arnas

Reputation: 83

how can i store data from jQuery.post to a local variable so that i can work with it?

this.formsValidation = function(form_id)
{
    var fieldNames;
    jQuery.post('index.php','option=com_itcs_forms&controller=itcs_fields&task=getFieldsNameForValidation&tmpl=component&form_id='+form_id,
    function(data)
    {
        fieldNames = data;
    });
    alert(fieldNames);
    return false;
}

here "fieldNames" is showing "undefined" although it must show a string which is in "data". i am unable to store "data" to a variable, so that i can work with it after "post" function. how to do that?

Upvotes: 0

Views: 100

Answers (2)

user1864610
user1864610

Reputation:

Your assignment should work, but your code is executing asynchronously - that is, you are issuing your AJAX call, then immediately executing alert() before the AJAX call has completed. If you wish to work with the data you should do so in the AJAX callback, thereby guaranteeing you have data when your code executes:

var fieldNames;
jQuery.post('index.php','option=com_itcs_forms&controller=itcs_fields&task=getFieldsNameForValidation&tmpl=component&form_id='+form_id,
function(data)
  {
     fieldNames = data;
     alert(fieldNames);
     // do more stuff here

  });

Upvotes: 0

Ashwini Agarwal
Ashwini Agarwal

Reputation: 4858

Do the following -

this.formsValidation = function(form_id)
{
    var fieldNames;
    jQuery.post('index.php','option=com_itcs_forms&controller=itcs_fields&task=getFieldsNameForValidation&tmpl=component&form_id='+form_id, 
     function(data)
     {
         fieldNames = data;
         alert(fieldNames);
     });

     return false;
}

Upvotes: 1

Related Questions