Solved

Java Script function appears not to be returning a value?

Posted on 2016-08-04
10
37 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 51

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 21

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 51

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
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
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

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
Article by: DanRollins
This article describes a JavaScript program that creates a maze made of hexagonal cells.  In Part 2 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7850-Hex-Maze-Part-2.html), we'll extend the program by adding a depth-…
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…

757 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

21 Experts available now in Live!

Get 1:1 Help Now