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: