I'm trying to call a function that returns me a json object from a servlet through a link.
My HTML link, call fTest function:
<td>ver</td>
My controller:
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {$scope.descargas = response.descargas;});
$window.alert(JSON.stringify($scope.descargas));
};
});
when I press for the first time the link appears "undefined" in the alert
but when I press a second time if I can see the json object that returns in the alert
What may be happening when I press first the link? please help
thanks
The problem here is your are alerting $scope.descargas outside of the success callback therefore it truly is not defined yet try modifying it like this.
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
$window.alert(JSON.stringify($scope.descargas));
});
};
});
Since every server side request using $http in Angular is an AJAX i.e. an asynchronous call to server, you are assuming that your alert method will be called after the success response execution complete. But this is wrong.
This is where the concept of promises comes in Angular.
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga) {
console.log("1");
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
console.log("2");
});
console.log("3");
$window.alert(JSON.stringify($scope.descargas));
};
});
So when you execute this code with a delay at server side, you will see the order of console log as: 1, 3 and 2.
So, your success function is executed when the response received from the server. So for the first time, the value in descargas variable is null but get's stored using first server response and next time, value from previous call is being displayed.
Related
I want to build a server that when invoked, it simply fetches the url that you pass it and sends the result back
I'm pretty sure there are many of these projects on guthub but I don't know what to search. I tried 'proxy server' but the results are not what im looking for
eg : myserver.com?/fetch?url=reddit.com fetches reddit.com and returns the result
Easy do it with express and request package
var app = require('express')(),
request = require('request');
function addHttp(url) {
if (!/^(?:f|ht)tps?\:\/\//.test(url))
return "http://" + url;
return url;
}
app.get('/fetch', function (req, res) {
console.log(req.query.url);
request.get(addHttp(req.query.url)).pipe(res)
});
app.listen(3000, function (err) {
if (err) console.log(err);
else console.log('magic start at port 3000')
})
Then try
localhost.com:3000/fetch?url=reddit.com
I need to send ajax request to java back-end and to response (from java back-end) with two html-blocks as answer. I want to generate those two html-blocks using two different JSPs. I do this as following:
req.setAttribute(...);
...
resp.setContentType("text/html");
RequestDispatcher dispatcher = req.getRequestDispatcher("one.jsp");
dispatcher.include(req, resp);
dispatcher = req.getRequestDispatcher("two.jsp");
dispatcher.include(req, resp);
And it works. But on the front-end I receive an answer like one solid html code (rendered one.jsp + rendered two.jsp). But I need to receive it as two separate html blocks to put each block to it's own .
What is the proper way to do this?
Ajax code:
function addNew() {
var request = $.ajax({
url: "myUrl",
type: "post",
dataType: "html",
success: function(data) {
$("#divNameOne").html(<one part of data>);
$("#divNameTwo").html(<second part of data>);
},
error:function() {
alert("fail");
}
});
}
In your success function ,
var reponseHtml = $(data); // or you can use $($.parseHtml(data));
$("#divNameOne").html(responseHtml.find("#div1").html());
$("#divNameTwo").html(responseHtml.find("#div2").html());
It might work.
I am making ajax call to a java method for every 30 seconds.
I am setting few request parameters in the java method.
How can I get them from ajax response.
<script LANGUAGE="JavaScript1.2">
var tId = window.setTimeout(function () {
location.reload(true);
alert('<s:property value="#disableReload" />');
if('<s:property value="#disableReload" />' == "true"){
alert("clearing");
}else{
var url = 'moveETHAction_fetchExecutorData.action';
var form = document.getElementById('moveForm');
var params = Form.serialize(form) + '&ms=' + new Date().getTime();
form.action = "fetchExecutorData";
var myAjax = new Ajax.Request(url, {method: 'post', parameters: params, onComplete: showResponseAction} );
}
}, 30 * 1000);
function showResponseAction(originalRequest){
alert(originalRequest.responseText);
alert('<s:property value="#request[\'DISABLE_FLOW'\]" />');
document.getElementById('actionChange').innerHTML = originalRequest.responseText;
}
</script>
In Java method I am setting this parameter
request.setAttribute(GenericConstants.DISABLE_FLOW, false);
But I am not getting the updated value from the ajax
Any changes to the HttpServletRequest on the server side will not be visible on the client side. Moreover setAttribute method will not affect the incoming HTTP request string. It's additional store within HttpServletRequest to pass-around information on the server-side.
You need to add the information to the existing response, in a structured away (JSON is preferable for your client to convert into a javascript object right away and access the individual values within response). Hope this helps.
I am trying to do a Spring MVC 3 ajax call to populate a drop down from json serialized data.
The problem I am seeing is I am not sure what format of JSON Spring is returning for my list, and why.
The method which returns the Ajax data looks like this:
#RequestMapping(value="/getMyObjects", method=RequestMethod.POST)
#ResponseBody
public List<MyObject> getMyObjects () {
List<MyObject> myobjects = // populate list
return myobjects;
}
And as far as I understand that should be all I need to do, right?
In my app logs I see it is indeed converting the response to JSON, as follows:
2012-06-20 11:08:21,125 DEBUG (AbstractMessageConverterMethodProcessor.java:139) - Written [[MyObject [id=1376, name=Something test], MyObject [id=1234 name=More test]]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter#d1b7e5]
But that JSON string looks odd to me, is that valid?
I was expecting stuff like [{ id : 1376, name="Something test"}, { id : 1234, name="More test"}]
On the client side when I get the response and do an alert I see it says its an array of objects like this: [Object object] [Object object] and I dont know how to deal with this data.
I try:
alert(data); -- gives the output I just described above
$(data).each(function() {
alert(this.id); // undefined!
});
How do I use this kind of JSON data or how do I convert it to something more manageable?
[Edit] Attaching my client side code with current alert responses I am trying:
$.ajax({
type : "POST",
url : "getMyObjects",
success : function(data) {
alert(data); // [Object object] [Object object]
alert(data.value); // Undefined
$(data).each(function() {
alert(this.id); // Undefined for each iteration
});
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Spring 3 provides integration with DWR(direct web remoting) which is very cool framwrork for AJAX calls. In DWR you can handle lists very easily just like in core java.
This is it! you should get the json format that you were expected. no more code (parser, formatting ) in necessary.
What you dont see is the actual json returned. well you try your url right away in the browser without calling it by ajax like http://yourdomain/yourservlet/getMyObjects you then will see your json as it is.
or else, use firfox with firebug, and you can see your ajac call (request & and response)
UPDATE
$.ajax({
url: "path/to/your/url",
cache: false,
async: false,
success: function(data){
for (var i = 0; i < data.length; i++) {
alert(data[i].id);
alert(data[i].name);
}
}
});
I am using Dojo and making an AJAX call to a JAVA Class and trying to get the output of the program to an Alert box to the client.
var showResult = function(result){
console.log("Showing Result()");
var store = new dojo.data.ItemFileReadStore({ data: result});
console.dir(store);
store.fetch( { onItem: function(data) { alert("Hie"); },
onError: function(error,request){ alert("ERROR");}
});
};
This is my code, showResult basically is call back function from xhr request. I can see console.dir(store) printed onto Firebug but the fetch function always returns the onError block.
My store array is of the form {info="Test Message"} and I need to retrieve "Test Message" and display it in an Alert box. Any help?
If the result is just an array, you should use new dojo.data.ItemFileReadStore({data : {items : result}}) to create the store.
For example, result is [{info : "Test Message 1"}, {info : "Test Message 2"}], then the code should be:
var store = new dojo.data.ItemFileReadStore({data : {items : result}});
store.fetch({
onItem : function(item) {
alert(store.getValue(item, "info"));
},
onError : function(error) {
alert("Error!");
}
});
Try
store.fetch({query: {info: '*'}},
onItem: function(data) {
alert("Hie");
},
onError: function(error, request) {
alert("ERROR");
}
);
as well you may want to see if onComplete: function(items){console.log(items);} works instead of onItem, it is worth a try.
As well console.log your error so that you can see what the issue is.
A few other things do you store have an identifier and label set?