Solved

Java Script function appears not to be returning a value?

Posted on 2016-08-04
10
48 Views
Last Modified: 2016-08-07
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
Comment
Question by:brgdotnet
10 Comments
 
LVL 35

Expert Comment

by:Terry Woods
ID: 41743621
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
 
LVL 2

Author Comment

by:brgdotnet
ID: 41743644
Hello Terry,

I have tried that, and still no value is being returned?
0
 
LVL 53

Expert Comment

by:Julian Hansen
ID: 41743658
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
 
LVL 22

Accepted Solution

by:
Kim Walker earned 250 total points
ID: 41743665
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
 
LVL 53

Assisted Solution

by:Julian Hansen
Julian Hansen earned 250 total points
ID: 41743680
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 2

Author Comment

by:brgdotnet
ID: 41746418
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
 
LVL 2

Author Comment

by:brgdotnet
ID: 41746420
Thank you. I captured the returned value using a global variable for the Java Script file.
0
 
LVL 2

Author Comment

by:brgdotnet
ID: 41746421
I used a global variable to capture the return values. Works great now. Thanks.
0
 
LVL 2

Author Comment

by:brgdotnet
ID: 41746423
Thank you. A global variable returned the value in question.
0
 
LVL 2

Author Closing Comment

by:brgdotnet
ID: 41746425
A global variable captured the return vaue from the Ajax call. A global variable in the Java Script file that is.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

863 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now