0
var userIdD = $.get('http://someurl.com/options.php', function(abc) {
  var abc = $(abc);
  var link = $(abc).find('a:contains(View My Profile)');
  //console.log (link);
  var userID = $(link).attr('href');
  var userId = $(userID);
  console.log(userId);
  console.log(userID);
});

console.log(userIdD);
console.log(userId);

I can`t start using variables "userIdD" & "userId" outside function "abc". Inside it, it works greatly. Can someone help me to use them outside it? where I'm wrong?

  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Patrick Evans May 26 '16 at 08:56

2 Answers2

0

Declare your variables outside the function:

var userID, userId;
var userIdD = $.get('http://someurl.com/options.php', function(abc) {
    var abc = $(abc)
    var link = $(abc).find('a:contains(View My Profile)')
    //console.log (link)
    userID = $(link).attr('href');
    userId = $(userID)
    console.log(userId)
    console.log(userID)
})
console.log(userIdD)
console.log(userId)
Argee
  • 1,216
  • 1
  • 12
  • 22
  • it still returns value of variable "undefined", and also appears "c.extend.ajax jquery-1.4.2.min.js:130 c.extend.get jquery-1.4.2.min.js:122 (anonymous function)" errors – BuZZinga May 26 '16 at 09:10
0

The problem is that userIdD is set asynchronously. The stuff that happens inside the function call happens after the stuff outside the function call.

Here's a simplified example which you can run:

$.get('http://jsonplaceholder.typicode.com', function(){
   alert('Stuff inside function happening');
});

alert('Stuff outside function happening');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Now, if we look at your code, we'll see that you're trying to console.log variables that are set inside the function call.

To go around the asynchronicity, you can make use of promises. Let's have a look at how that works...

var valuesPromise = $.get('http://jsonplaceholder.typicode.com').then(function(serverResponse){
  return { objectId: 123 }; // return stuff you want to use later
});

// later in your code, you can make use of the returned value...

valuesPromise.then(function(returnedValue){
  alert(returnedValue.objectId); // alerts '123'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
meltuhamy
  • 3,293
  • 4
  • 23
  • 22
  • It doesn`t helps me... It takes another error "TypeError: Object # has no method 'then'" U can look code I`ve made upper – BuZZinga May 26 '16 at 09:47