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
I think you are using $.get() function in wrong way! Please see following link for more info. It cannot return value, it should execute callback function when request is finished!
You should pass function as callback 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 (synchronous call):
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 using $.ajax() and I am not returning any value inside $.ajax. Also I added async: false. Now you can return result in that way but it is not async.
If you want to use asynchronous request you have to use callback function. Some implementation can be like in following example:
function CurrentDate(callbackFunction) {
var url = CurrentDateUrl();
var result;
$.get(url, function (e) {
var Date = e.toString();
callbackFunction(Date);
});
}
// Call your function in code like this
CurrentDate(function(result) {
// handle your result here
});
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have a button that when I click on it , it will get data from my database , and display it on my text area based on the id.
JQuery
$('#verifyBtn').on("click", function() {
var exeOutput = checkOutput();
$("outputArea").html(exeOutput);
});
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
function getOutput(dataStr, flag) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
return data;
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
Through my servlet for getting from my database.
Servlet
exercisesModel outputModel = null;
try {
DBConnection db = new DBConnection();
outputModel = db.getExerciseById(request.getParameter("exNo"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.getWriter().append(outputModel.getExpOutput());
EDIT: Upon clicking, i think there is data but my text area is not displaying it.
Since you're making an Asynchronous call you can't return an immediate response using return data;, but instead you could pass the selector then assign the result to your output element when the success callback is called:
<script>
$('#verifyBtn').on("click", function() {
checkOutput("outputArea");
});
function checkOutput(output_selector){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true, output_selector);
}
function getOutput(dataStr, flag, output_selector) {
$.ajax({
url: "/FYP/WebExerciseByOutput",
data: dataStr,
success: function (data) {
$(output_selector).html( data );
},
error : function (xhr,textStatus,errorThrown){
console.log("Something is wrong with ajax call."+ xhr);
}
});
}
</script>
NOTE : The passed flag parameter isn't used.
Hope this helps.
This block here:
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
getOutput(dataString, true);
}
try adding a return to the getOutput line
function checkOutput(){
var exNo = parseInt($('#selectExercise').val());
dataString = "exNo=" + exNo;
$("#result").empty();
return getOutput(dataString, true);
}
By value i guess you mean the result of the call. You can find that in the parameter of the success handler.
success: function (data) {
//This is your result from server.
console.log(data);
return data;
}
Take a look at your JS console to see the results.
I'm writing something to get all the layers names from my GeoServer. This is my code:
function getData() {
return $.ajax({
url: "http://localhost:8080/geoserver/ows?service=wms&version=1.1.0&request=GetCapabilities",
type: 'GET'
});
}
function onComplete(data) {
var parser = new ol.format.WMSCapabilities();
var result = parser.read(data.responseText);
var layersArray = result.Capability.Layer.Layer;
layersNameArray = [];
for(i=0;i<layersArray.length;i++){
layersNameArray.push(layersArray[i].Name)
}
return layersNameArray
}
getData().done(onComplete)
I'm far from an expert with asynchronous calls, but I think this one is supposed to work. If I stock the getData() result in a variable and run the onComplete() function line by line, the code works. But when I run the code with getData().done(onComplete), it always fails at the var result = parser.read(data.responseText);line with Assertion error: Failure.
Any idea why this isn't working ?
Edit:
This code works, but nothing is returned. I want the function to output the layersNameArrayvariable. How should I proceed ?
function getData() {
$.ajax({
url: "http://localhost:8080/geoserver/ows?service=wms&version=1.1.0&request=GetCapabilities",
type: 'GET',
success: function(response) {
var parser = new ol.format.WMSCapabilities();
var result = parser.read(response);
var layersArray = result.Capability.Layer.Layer;
layersNameArray = [];
for(i=0;i<layersArray.length;i++){
layersNameArray.push(layersArray[i].Name)
}
return layersNameArray
}
});
}
You can make use of the Jquery callback feature,
make a call to your function this way,
getData(function(responsefromAjax){
alert('the response from ajax is :' +responsefromAjax);
// what ever logic that needs to run using this ajax data
});
And the make change to your method this way.
function getData(callback) { // passing the function as parameter
$.ajax({
url: "http://localhost:8080/geoserver/ows?service=wms&version=1.1.0&request=GetCapabilities",
type: 'GET',
success: function(response) {
var parser = new ol.format.WMSCapabilities();
var result = parser.read(response);
var layersArray = result.Capability.Layer.Layer;
layersNameArray = [];
for(i=0;i<layersArray.length;i++){
layersNameArray.push(layersArray[i].Name)
}
callback(layersNameArray); //this will execute your function defined during the function call. As you have passed the function as parameter.
}
});
}
Let me know if this helps
Two month ago I started to build my own webapp with AngularJS, the problem is that I found out that async: false was deprecated and I need to replace it with something that will work :).
So let me show you an exemple of my script:
getContent:function(ticketid){
if(sessionService.islogged)
{
$.ajaxSetup({async:false});
var response = null;
var result = $.post( "data/ticket.php",{Action:'getContent',ticketid:ticketid}, function(data) {
response = data;
});
$.ajaxSetup({async:true});
return response;
}
},
And an exemple when I am using this function in a controller
$scope.ticket = JSON.parse(ticketService.getContent(sessionService.get('ticketID')));
As you can see I store the result of the POST request in an array but if I remove the async:false, my script will be asynchronous and I will get an undefined variable..
Pass call back function as a variable.
getContent:function(ticketid,successCallback){
if(sessionService.islogged)
{
$.ajaxSetup({async:false});
var response = null;
var result = $.post( "data/ticket.php",{Action:'getContent',ticketid:ticketid}, successCallback);
$.ajaxSetup({async:true});
return response;
}
},
And Call the getContent function
sessionService.get('ticketID',function(data) {
$scope.ticket = JSON.parse(data);
})
I have created a small JavaScript application with the following function that calls a function to retrieve JSON data:
var months = function getMonths(){
$.getJSON("app/data/Cars/12Months", function (some_data) {
if (some_data == null) {
return false;
}
var months_data = new Array();
var value_data = new Array();
$.each(some_data, function(index, value) {
months_data.push(index);
value_data.push(value);
});
return[months_data,value_data];
});
}
I have then created, in the same file, another function that does something when a specific page is loaded. In this function the variable 'months' is passed to the variable 'result'.
$(document).on('pageshow', '#chartCar', function(){
$(document).ready(function() {
var result = months;
var date = result[0];
var values = result[1];
//more code here...
});
}
the problem is that, based on the debugger, the getMonths() function works fine and produces the expected output, but the 'result' variable in the second function can't obtain the values passed to it by the variable 'months'. Do you know how to solve this issue?
The problem is that you $.getJSON() function is asynchronous, so your data gets loaded later then you read it. There're two workarounds:
1. Replace your $.getJSON with $.ajax and setting async: false;
2. Put your code in $.getJSON callback:
var months = function getMonths(){
$.getJSON("app/data/Cars/12Months", function (some_data) {
if (some_data == null) {
return false;
}
var months_data = new Array();
var value_data = new Array();
$.each(some_data, function(index, value) {
months_data.push(index);
value_data.push(value);
});
var date = months_data;
var values = value_data;
//more code here..
})
}
There must be a syntax error.
replace
});
}
With
});
});
$.getJSON() is a wrapper around $.ajax which is async by default. But you treat it like a sync call.
You can use $.ajaxSetup()
$.ajaxSetup( { "async": false } );
$.getJSON(...)
$.ajaxSetup( { "async": true } );
or use $.ajax with async: false
$.ajax({
type: 'GET',
url: 'app/data/Cars/12Months',
dataType: 'json',
async: false,
success: function(some_data) {
//your code goes here
}
});
or if possible change the behavior of your app so that you process your data in a callback function.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery ajax return value
How to return the response from an AJAX call from a function?
I have javascript. It loads data from database. I want to return true or false with respect to loading data. But I could not return it. My code has given bellow:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.get(url, {
isrc: isrc
}, function (data) {
if (data == "true") {
result = true;
}
else {
result = false;
}
});
return result;
}
It always gives false result. Anyone has faced this kind of problem? 'Thanks advance'
If it's so important to use the function synchronously you can refactor it to:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.ajax({
async: false,
success: function (data) {
if (data == "true") {
result = true;
}
else {
result = false;
}
},
data: { isrc: isrc }
});
return result;
}
As #ManseUK async is deprecated in jQuery 1.8 so if you want synchronous approach you should use older version.
The problem is that when you return result, It doesnt have value. because the ajax didn't finish its task. you make some callback function and when the result of ajax is returned from server, do what you want to.
Some thing like this:
function CheckISRC(Callback) {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
var result = false;
$.get(url, {
isrc: isrc
}, function (data) {
if (data == "true") {
Callback(true);
}
else {
Callback(false);
}
});
}
function YourCallback(result) {
//...
}
The JQuery ajax functions are asynchronous. This means that when you initialise result to false, the result is set to true or false after the "return result;" line has run.
You can make the call synchronous but this is considered worse practice. You are often better off refactoring your code to allow for the asynchronous nature of the JQuery Ajax.
For example, where you previously had:
function myFunction() {
//Code before
var result = CheckISRC();
//Code after using result
}
you could have the following:
function myFunction() {
//Code before
CheckISRC();
}
function myFunction_callback(result) {
//Code after using result
}
where you call myFunction_callback in the success option of your ajax code like so:
function CheckISRC() {
var url = "/TrackEdit/CheckISRC/" + $('#isrcid').val();
var isrc = $('#isrcid').val();
$.get(url, {
isrc: isrc
}, function (data) {
myFunction_callback(data == "true");
});
}