0

I am trying to use jquery GET functionality to load the value from the external page to a variable

var cbname = $.get('/getname.php','name='+item.f);
alert(cbname);

but in alert it is bringing me an object object

Can anyone guide what is the best approach to do this:

voyeger
  • 139
  • 2
  • 9

2 Answers2

0
var cbname;

$.get('/getname.php','name='+item.f, function(data) {
    cbname = data;
    alert(cbname);
});

Gotta use the success callback.

If you don't want to use the callback, but instead want a synchronous call:

jQuery.ajax({
     url:    '/getname.php?name='+item.f,
     success: function(data) {
         cbname = data;
     },
      async:   false
});

alert(cbname);

Also note that if item.f is not url safe, you'll want to use

'/getname.php?name='+encodeURIComponent(item.f)

instead

Dave
  • 10,748
  • 3
  • 43
  • 54
Lotus
  • 2,596
  • 1
  • 22
  • 20
  • 2
    Pretty sure you are going to get `undefined` from this. `alert` also needs to be in the callback. – Dave Oct 02 '14 at 17:09
  • guys, if i use above and place the alert outside the callback, it gives me `object object`, How do i use it outside.. – voyeger Oct 02 '14 at 18:56
  • updated for synchronous feature (SJAX instead of AJAX) – Lotus Oct 02 '14 at 19:35
0

If you are making web requests, don't take the easy way out by forcing your program to run synchronously, instead start to think like an AJAX programmer: instead of thinking "I need a function that returns a value," an AJAX programmer thinks, "I need a function that does something with a value once I have it."

You want something like the following:

$.get('/getname.php','name=' + item.f, myCallback);

function myCallback(cbname) {
    alert(cbname);
}
Dave
  • 10,748
  • 3
  • 43
  • 54