I'm trying to display the return data from the external Javascript.
Here's my code
global-functions.js
function CurrentDate() {
var url = CurrentDateUrl();
$.get(url, function (e) {
var Date = e.toString();
console.log(e);
console.log(Date);
return Date;
});
// RETURN the Current Date example. 11/29/2013 10:57:56 AM
}
Sample.cshtml (View)
<h2>Transaction Date: <b><span id="TransactionYear"></span></b></h2>
<script>
function CurrentDateUrl(){
return '@Url.Action("CurrentDate", "Global")';
}
$(document).ready(function () {
var Date = CurrentDate();
document.getElementById("TransactionYear").innerHTML = Date; // the return is UNDEFINED
});
</script>
As we can see in global-functions.js there is no problem as it return from what i wanted but when I try to call the function CurrentDate() it will return to UNDEFINED . Any other way to display it? or other good approach?
EDIT :
Question : Can you verify that function CurrentDate() is called?
- Yes. As I try to return the hard coded string in
CurrentDate()it will display.
I tried the suggested answer below
function CurrentDate() {
var url = CurrentDateUrl();
var result;
$.get(url, function (e) {
var date= e.toString();
console.log(e); // will return the Date in console
console.log(date); // will return the Date in console
result = date;
console.log(result); // will return the Date in console
});
console.log(result); // will return UNDEFINED in console
return "Sample";
}
OUTPUT
Transaction Date : Sample
return datais Undefined and not the functionDate()with your variable name. I'd choose something else: at leastdate =rather thanDate =global-functions.jsin my shared_Layout.cshtmlcause I also used it in my other views