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!

3
  • When you're alerting, is discountCode.length > 2 true? That's likely the problem. Commented Mar 11, 2012 at 2: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. Commented Mar 11, 2012 at 2:55
  • possible duplicate of How to return the response from an AJAX call? Commented Jun 26, 2013 at 2:41

5 Answers 5

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.)

Sign up to request clarification or add additional context in comments.

Comments

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.");
    }
});

4 Comments

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?
It works perfectly, that schema is very useful. Is there any link to read the doc about synchronous and asynchronous functions in JS ?
@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 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 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. ;)
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.

1 Comment

It will also return that when it > 2 :)
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.

Comments

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);

2 Comments

Should I also return something?? I tried this methode but it didn't work.
I modified the code snippet to show what a callback would look like.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.