0

This is my code :

var noSubTasks = $.post('/taskuri/getTheNumberOfSubtasks/', { projectID: projectIdRow, taskName :  result }, function(data2){
    var x = data2;
});
alert(x);

and the fire bug show me this error :

ReferenceError: x is not defined
error source line:
alert(x);

can anyone tell me why ??? and How can I assign the data2 to a variable ?? Thx

Attila Naghi
  • 2,535
  • 6
  • 37
  • 59

2 Answers2

0

Problems

Ajax

... calls are asynchronous. That means if you want to access a variable directly after executing an ajax request, you cannot be sure that the ajax request is finished. You could use a callback function to solve this problem.

Scoping

The exception is thrown, because x is not defined in your scope. If you would change the var x = data2; to window.x = data2; or just x = data2;, you should be able to access (/alert) it in global scope.

I would recommend you to read the answer to this post, due to very good explenation of variable scoping.


Solution

[...]

$.ajax({
  type: 'POST',
  url: '/taskuri/getTheNumberOfSubtasks/', 
  data: { 
    projectID: projectIdRow, 
    taskname :  result 
  }, 
  done: function(data, textStatus, jqXHR) {
    EvaluateAjaxResponse(result);
  },
  fail: function(jqXHR, textStatus, errorThrown) {
    // Errorhandling
  }
});

[...]

function EvaluateAjaxResponse(ajaxResponse) {
  alert(ajaxResponse);
  // Do whatever you want.
}

jQuery docs:

Community
  • 1
  • 1
ˈvɔlə
  • 9,204
  • 10
  • 63
  • 89
0

An ideea to solve this problem would be : To create a hidden input type

<input type="hidden" id ="noSubTask">

To assign the data2 to the input type value

var noSubTasks = $.post('/taskuri/getTheNumberOfSubtasks/', { projectID: projectIdRow, taskName :  result }, function(data2){
$("#noSubtask").val(data2);
});

after that to get the value from the hidden input :

var getTheNumberOfSubtasks = $("#noSubtask").val();
alert(getTheNumberOfSubtasks );
Attila Naghi
  • 2,535
  • 6
  • 37
  • 59