0

I got a wierd issue with a javascript script.

This is my code:

function checkDiscountCode()
{

  var discountCode = $('#korcode').val();
  var errorMessage = $('#errorMessage').text();

  if(discountCode.length > 2)
  {

     $.getJSON( 'calc.php?code=' + discountCode, function( json ) 
     {    
       var color = json.color; 
       var soort = json.soort;
       var waarde = json.waarde; 
       var message = json.message;

       if(errorMessage != message)
       {
          $('#error').html('<font color="' + color + '" id="errorMessage">' + message + '</font>');
       }

       if(message == 'OK!')
       {
          var outputData = soort + '-' + waarde;
          console.log('outputData = ' + outputData);
          return outputData;
       }

     });   
  }   
}

The console log give the right data, for example 0-12.00 but when I request this function in another function, for example just a alert(checkDiscountCode()); it says undefined..

Can anyone please help me? I don't see the issue..

Thanks in advance!

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
user926734
  • 1
  • 1
  • 4
  • When you're alerting, is `discountCode.length > 2` true? That's likely the problem. – Purag Mar 11 '12 at 02:53
  • @Purmou and I are thinking the same thing. The difference in your observations may be when the function is being called, in relation to when the page is loaded. – vol7ron Mar 11 '12 at 02:55
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – icktoofay Jun 26 '13 at 02:41

5 Answers5

8

Your checkDiscountCode() function doesn't have a return statement, so it returns undefined by default.

The return statement that you've included is inside the anonymous function passed as a callback for $.getJSON(), so it returns from that function back to the jQuery code that called it, not back to your code (and even then it returns undefined if message is not 'OK!'). (Also your $.getJSON() doesn't run unless discountCode.length > 2, though your checkDiscountCode() function doesn't try to return a value either way.)

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
2

You're returning from a callback passed to a function that does work asynchronously. You'll have to adapt the code to take a callback and change the caller to deal with the fact that it's asynchronous.

That means that rather than this:

// won't work
function checkSomething() {
    someAsynchronousFunction(function(result) {
        return result == "success";
    });
}
if(checkSomething()) {
    alert("It worked.");
}else{
    alert("It didn't work.");
}

You'll have to change your code to look like this:

function checkSomething(callback) {
    someAsynchronousFunction(function(result) {
        callback(result == "success");
    });
}
checkSomething(function(result) {
    if(result) {
        alert("It worked.");
    }else{
        alert("It didn't work.");
    }
});
icktoofay
  • 126,289
  • 21
  • 250
  • 231
  • I tried this with no result, I have a funtion: [code] checkDiscountCode(function(outputData) { alert(outputData); }); [/code] to get this data and I set the data with [code] function checkDiscountCode(callback) { callback(outputData); [/code] (ofc only pieces of the code) What am I doing wrong? – user926734 Mar 11 '12 at 03:08
  • It works perfectly, that schema is very useful. Is there any link to read the doc about synchronous and asynchronous functions in JS ? – Joe Lewis Jun 25 '13 at 15:04
  • @Joe: JavaScript, unlike many other languages, doesn't really have official documentation. There is, however, another question here on Stack Overflow practically identical to this one with [a very good explanation](http://stackoverflow.com/q/14220321) you may want to read explaining the reasons *why* the problem occurs (something I didn't really elaborate on here) and how to fix it. – icktoofay Jun 26 '13 at 02:40
  • @icktoofay Thanks a lot, it's perfect both your answer for a quick understanding and the link for a wide knowledge of sync/async calls in JS. ;) – Joe Lewis Jun 26 '13 at 13:45
1

If discountCode.length > 2 is not true, you aren't returning a value, thus it will return undefined.


I'll also add that if you did put it in another function alert(checkDiscountCode()) and you closed firebug up, or opened in another browser that doesn't have console open, your browser will encounter a javascript error, if you left the console.log(...) line still in your code.

A console window has to be open in order to log to it.

vol7ron
  • 40,809
  • 21
  • 119
  • 172
0

JQuery's getJSON() method runs asynchronously. You should add a callback function to checkDiscountCode(); the callback function will run the rest of your app's logic. For example:

function sampleCallback(outputData) {
  console.log('outputData = ' + outputData);
}

function checkDiscountCode(callback) {
  $.getJSON( 'calc.php?code=' + discountCode, function( json ) {
    // get output data, and then call callback.
    callback(outputData);
  });
}

checkDiscountCode(sampleCallback);
monsur
  • 45,581
  • 16
  • 101
  • 95
0

And if discountCode.length > 2 you are invoking the $.getJSON function, but that takes a callback, and returns nothing immediately. Hence, in either case, you get undefined.

Ryan Roemer
  • 987
  • 7
  • 13