FrostyPinky FrostyPinky - 16 days ago 5
C# Question

Display return data from external javascript

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 to 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

Answer

I think you are using $.get() function in wrong way! Please see following link for more info.

You should pass function as call back in $.get() (which you are doing) and in that function do logic which you want (which you are NOT doing right now.)

I will rather do like this (probably not good in your case because you are using external file):

$.get(url, function (e) {
    var Date = e.toString();
    console.log(e);
    console.log(Date);

    document.getElementById("TransactionYear").innerHTML = Date
});

Or try this in your case:

 function CurrentDate() {
    var url = CurrentDateUrl();
    var result;

    $.ajax({
    url: url,
    type: 'get',
    async: false,
    success: function(data) {
        result = data;
    } 
 });
 return result;
}

Please note: I am not returning any value and I am using $.ajax() with ** async: false**. Now you can return result in that way but it is not async.