Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 82
  • Last Modified:

Java Script function appears not to be returning a value?

I have some code in a Java Script.js file. I have a function named TestForValue() which calls a function named CheckValue();
CheckValue makes an Ajax call down to an MVC C# method, and returns a value. It all works great, however the string value (True or False) is not being returned from the method TestForValue. At line 3 and 4 below when line 4 below is executed nothing
is displayed in the alert box. I don't know why, because my CheckValue() method will return either true or false. So I don't know why
the value on line 3 and 4 below is coming back as an empty string. Does an Expert have any idea why CheckValue is not return my
string value?

I did not know wether to place this question in the Java Script Section or Ajax section, so I placed it in the Java Script section.

1   function TestForValue()
2  {
3     var x = CheckValue();
4    alert(x)
5 }


function CheckValue()
{
 
    return $.ajax({
          url: "../Home/GetResult",
          type: 'POST',
          ContentType: 'application/json; charset=utf-8',
          data: 'JSON.stringify({id:Parameter})',
          success: function (isOk)
         {
               if(isOk = "Success")
            {
                 alert(isOk); // Yes the message box displays the word "Success"
               return "true";
            }

           }

      });
      
      return "false";
}


}
0
brgdotnet
Asked:
brgdotnet
2 Solutions
 
Terry WoodsIT GuruCommented:
I'd suggest changing this part of the CheckValue function and see what you get. The existing part of the function that returns false will never get reached:

 
   if(isOk = "Success")
            {
                 alert(isOk); // Yes the message box displays the word "Success"
               return "true";
            } else {
               return "false";
            }

Open in new window

1
 
brgdotnetAuthor Commented:
Hello Terry,

I have tried that, and still no value is being returned?
0
 
Julian HansenCommented:
AJAX is async - you cannot return a value from an AJAX call because the function returns before the AJAX call has resolved.

Either you return a promise from the AJAX call and then perform your action on resolution of the promise or you do whatever logic needs to be done with the return in the success / then function

$.ajax({
    ...
}).then(function(ret) {
        if (ret) {
            // DO TEST FOR VALUE CODE HERE
            // IN OTHER WORDS - WHATEVER YOU WANT TO DO WITH THE RETURN
            // DO IT HERE
        }
});

Open in new window


You can make the $.ajax synchronous - but this is not recommended. If you are writing AJAX code with asynch set to false then you need to relook at your design.

If you post more of how you want to consume the return post your code and we an assist.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Kim WalkerWeb Programmer/TechnicianCommented:
There are several issues here.
if(isOk = "Success")
A single equals symbol here means if the variable isOk is successfully defined as the string "Success", then do whatever follows in the {} braces. I believe you intended to express a comparison rather than a definition. Try changing this to
 if(isOk === "Success")

Open in new window

However, the code as it is should result in a true condition and execute the alert. Therefore, I believe the ajax request is not successful. Can you post a link to the page with this code so we can see what is happening with the ajax request?

And, finally, Terry Woods did not mention that you should remove the return before the ajax call. The ajax call doesn't produce anything instantly, there is some delay for the remote connection to be negotiated and the remote code to be executed and the results transmitted back to the browser. So by the time the success property function is executed, the CheckValue function itself has completed. Therefore, the CheckValue function will always complete without returning anything.

And with all that being said, it is impossible to nest an ajax call in a function that is nested in another function and base any condition in that function on the results of the ajax call. Ajax sends a request to a remote server and monitors the connection with that server until a response is received -- all while the other javascript code is continuing to run. Hence the a in ajax which is for asynchronous. Any code that relies on the response from the ajax request must be placed in the success property (callback) of the ajax parameters.
0
 
Julian HansenCommented:
Breaking your code down further
function TestForValue()
{
   var x = CheckValue();
   // YOU GET HERE BEFORE YOUR SUCCESS FIRES
   // THE RETURN FROM CheckValue IS A PROMISE
   // NOT A RETURN FROM THE SUCCESS
}
function CheckValue()
{
  // HERE YOU ARE RETURNING A PROMISE
  return $.ajax({
    url: "../Home/GetResult",
    type: 'POST',
    ContentType: 'application/json; charset=utf-8',

    // YOUR DATA IS IN '' (QUOTES) - IT IS GOING TO BE SENT AS
    // json.stringify({id:Parameter})
    // RATHER THAN 
    // {"id": "Paramter"}
    data: 'JSON.stringify({id:Parameter})',
    success: function (isOk) {
        // FIRES WHEN AJAX COMPLETES - IN CPU TIME THIS IS
        // YEARS AFTER THE CheckValue FUNCTION RETURN
        if(isOk = "Success") {
          alert(isOk); // Yes the message box displays the word "Success"
          // ENDS UP IN /dev/null SUCCESS FUNCTIONS DON'T RETURN VALUES
          return "true";
        }
      }
    });
    // THIS NEVER FIRES BECAUSE YOU ARE ALREADY 
    // RETURNING THE PROMISE ABOVE
    return "false";
}

Open in new window


Consider this code to illustrate
<script>
var Parameter = 'Value'
$(function() {
  $('a').click(function(e) {
    e.preventDefault();
console.log('Call CheckValue');  
    var r = CheckValue();
console.log('CheckValue returned');
    r.then(function(resp) {
console.log('fired then');
      alert(resp);
    });
  });
});

function CheckValue()
{
console.log('Enter CheckValue');
  // HERE YOU ARE RETURNING A PROMISE
  return $.ajax({
    url: 't1465.php',
    type: 'POST',
    ContentType: 'application/json; charset=utf-8',
    data: JSON.stringify({id:Parameter}),
    success: function (isOk) {
        if(isOk = "Success") {
console.log('fired success');    
          alert(isOk); // Yes the message box displays the word "Success"
          return "true";
        }
      }
    });
console.log('Never Fires');  
    // THIS NEVER FIRES
    return "false";
}
</script>

Open in new window

The output in the console from the above is this
Note the order -
call CheckValue
Enter CheckValue
POST http://mrcp9/ee/t1465.php 200 OK 3ms	
CheckValue returned
fired success
fired then

Open in new window

There is a working sample here
0
 
brgdotnetAuthor Commented:
I ended up getting the value returned by creating a gobal variable in the Java Script file. Thank you everyone for the Expert help.
0
 
brgdotnetAuthor Commented:
Thank you. I captured the returned value using a global variable for the Java Script file.
0
 
brgdotnetAuthor Commented:
I used a global variable to capture the return values. Works great now. Thanks.
0
 
brgdotnetAuthor Commented:
Thank you. A global variable returned the value in question.
0
 
brgdotnetAuthor Commented:
A global variable captured the return vaue from the Ajax call. A global variable in the Java Script file that is.
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now