I am a new programmer whose primary background is in Java. I am attempting to write in fault handling to a program in Javascript as I would in Java. In java I use the Apache HTTP client to both create the client and call the Httpget request.
HttpClient cli = new DefaultHttpClient();
cli.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000);
HttpResponse resp = null;
for (int i = 0 ; i < 5 ; i++) {
try {
resp = cli.execute(new HttpGet("http://example.org/products"));
}
catch{//code}
}
I am unsure how to emulate this behavior in a javascript environment. Does anyone have insight or knowledge into this field?
In javascript, as in some other languages, "exception" handling is mostly replaced by error checking. For example you'll check the status of your xmlhttprequest object when issuing a request :
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
// ok, no "exception"
} else {
// BOOM ! "exception"
}
}
}
}
Exceptions are only useful in a few places, like parseInt.
But I'm not sure that a heavy "fault tolerant" javascript code makes a lot of sense :
you really don't know where and how your code will be executed
all the important checks and all important persistence is client side
Your global system must be though with the idea that the browser is a foreign domain : nothing entering your server can be trusted.
Here's the exact equivalent of your code snippet, but in JavaScript!
var cli;
var callback = function(resp) {
// due to the asynchronous nature of XMLHttpRequest, you'll need to put all logic that uses the response in a callback function.
// code below using responseText
console.log(resp);
};
var timeout = 5000;
var handler = function() {
var errorSeries;
if (this.readyState === 4) { // indicates complete
errorSeries = parseInt(this.status.toString().charAt(0)); // will be "2" or "3" for 200 or 300 series responses
if (errorSeries === 2 || errorSeries === 3) {
callback.call(this, this.responseText);
} else {
// handle http error here
}
}
}
for (var i = 0 ; i < 5 ; i++) {
cli = new XMLHttpRequest(); // ActiveXObject('Microsoft.XMLHTTP') in IE8 and below
cli.timeout = timeout;
cli.onreadystatechange = handler;
try {
cli.open('GET','http://example.org/products');
cli.send();
}
catch(e) {
}
If the above looks wordy, that's because it is. Other commenters have steered you right: look into using a library like jQuery to abstract away this kind of boilerplate.
Related
I am using Spark framework for my application.
I have a middleware which checks (among other things) if the body is of JSON format:
// Middleware
before((req, res) -> {
// Method check
if (!req.requestMethod().equals("POST")) {
halt(403, "{\"result\":\"ERR\",\"errMsg\":\"Only POST allowed!\",\"code\":403}");
}
// JSON Check
JSONObject body_json = new JSONObject();
try {
body_json = new JSONObject(req.body());
} catch (JSONException e) {
halt(403, "{\"result\":\"ERR\",\"errMsg\":\"No valid JSON!\",\"code\":403}");
}
// At this point (end of middleware) the request body is still unchanged !
});
Then I have my normal function for processing POST requests:
post("/post_some_data", (req, res) -> {
String body = req.body() // This string is empty !!
int length = req.contentLength(); // This remain unchanged
});
But the request body suddenly becomes empty (other attributes and headers remain unchanged).
Is that a bug or am I doing something wrong ??
There was a bug in the spark framework. Updating the library to the 2.1 version will solve this and all of the similar problems.
I am working on a news summarizer and one of its requirements is to display a list of article titles dynamically on a webpage using AJAX called from a database. I have been able to successfully configure the datastore(google app engine) and use the AJAX call to display article title. However, there is one big issue here. I am only able to call and show a single title. I want to run the AJAX call inside a loop so that I can display 10 news articles stored in datastore from 1 to 10 using the variable i of the loop as the unique reference.
The AJAX CODE :
function change(element) {
var xmlhttp;
var i = 1;
var param = "category=" + element + "&no=" + i; // This i is the key to my operation.
alert(param); //testing purpose
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//alert('function()');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var div = document.getElementById('content');
div.innerHTML = '';
for (i = 1; i <=10; i++) {
var a = document.createElement('a');
a.href = "#";
a.onclick = rem.bind(null, i);
a.innerHTML = '<h2 id="theading'+i+'">'
+ xmlhttp.responseText + '</h2>'; //the title will go here.
div.appendChild(a);
div.appendChild(document.createElement('br'));
}
}
}
xmlhttp.open("POST", "/display?" + param, true);
xmlhttp.send();
}
I also request to suggest JavaScript code and not jquery, as I am unfamiliar with it. These are my humble beginnings.
UPDATE
MY SERVLET CODE:
public class ArticleHandler extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
String category=req.getParameter("category");
String number=req.getParameter("no");
int i = Integer.parseInt(number);
List<EntityArticles> articles = RegisterClass.ofy().load().type(EntityArticles.class).filter("category ",category).list();
out.write(articles); // Is this the correct way to send this list articles ?
}
}
Is this the correct way to send the list ?
10 articles in responseText, you can render html in server code to responseText(loop in server code). And then in ajax sucess you call
var div = document.getElementById('content');
div.innerHTML = xmlhttp.responseText;
I have created a fiddel for you to understand check it. Ajax Example in fiddle
Are you doing post request or get request? I'm asking this because I saw method as "POST" and parameter passed as "GET" by putting it in url. Please correct that part too in your code.
loadXMLDoc=function()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/ahmadfaizalbh/LaH8F/show/",true);
xmlhttp.send();
}
The best choice is to call the ajax one time and get 10 items.
But, if you have no alternative, you can modify the function a little:
function change(element, i){
var xmlhttp;
//var i=1;
var param = "category=" + element + "&no=" + i;
...
}
Call the function this way (10 times as you need):
for(i=1;int <= 10; i++){
change(element, i);
}
UPDATE
To make one time the ajax call, you can do:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
//append html node
//the object is xmlhttp.responseText. The loop will depend if this is json, html objects, string, etc
}
xmlhttp.open("POST", "/display?" + param, true);
xmlhttp.send();
To obtain 10 results you need (necessarily) to modify the server side script or servlet. If you cannot have access to modify the servlet, is impossible to get 10 items in a single ajax call.
if(xmlhttp) {
xmlhttp.open("GET","DokterWeek_KlantoverzichtServletAjax?" + $(this).prop("href").split("?")[1],true);//gettime will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
});
});
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera,chrome Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function handleServerResponse() {
document.getElementById("pop1").innerHTML = xmlhttp.responseText; //Update the HTML Form element
}
Hello,
I have the following problem (the code works), the xmlhttpRequest(ajax-call) refreches when I use firefox or Chrome (so it works nice). But IE 9.0+ caches the XMLHttprequest, so it never refreches. I read alot about this problem on the internet,but i really cannot find any solution to this problem.
Can anybody tell me the possibilities to fix this?
I think it is fixable with using the jquery ajax, but I don't have the brains to tune this whole script into jquery. Some say you can set the live-time to 0 but I don't find this. (I communicate my Ajax with a servlet)
Somebody knows an clear,easier solution?
Thank you very much
Once of the accepted practice is to add a random parameter to the url like the timestamp.
Add a parameter like _d to the url with the value new Date().getTime()
Ex:
xmlhttp.open("GET","DokterWeek_KlantoverzichtServletAjax?_d=" + (new Date().getTime()) + '&' + $(this).prop("href").split("?")[1], true);//gettime will be the servlet name
in facebook fql theres this code
https://developers.facebook.com/docs/reference/api/batch/
curl \
-F 'access_token=…' \
-F 'batch=[ \
{"method": "GET", "relative_url": "me"}, \
{"method": "GET", "relative_url": "me/friends?limit=50"} \
]'\
https://graph.facebook.com
it suppose to to be sent with json
but I really dont understand how to do this
any help ?
thanks
You can simple use the BatchFB api its very powerful and easy , you dont have to deal will all of these stuff and it use the fql
for example to get all your friends
Later<ArrayNode> friendsArrayList = this.Batcher.query("SELECT uid FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me())");
for (JsonNode friend : friendsArrayList.get()) {
.......
}
and its batched
I believe your question is how to execute a batch request using Facebook Graph API. For this you have to issue a POST request to
"https://graph.facebook.com"
and the post data to be sent should be
"batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#accesstoken"
in your case [#accesstoken must be replaced with your access token value].
This request will return the details of the owner of the access token(normally the current logged in user) and a list of 50 facebook friends(contains id and name fields) of the user along with page headers(can be omitted).
I am not sure whether you meant java or Javascript. Please be specific on it.
I am a C# programmer basically. Will provide you a code to execute the above request in C# here.
WebRequest webRequest = WebRequest.Create("https://graph.facebook.com");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-UrlEncoded";
byte[] buffer = Encoding.UTF8.GetBytes("batch=[{'method': 'GET', 'relative_url': 'me'}, {'method': 'GET', 'relative_url': 'me/friends?limit=50'}]&access_token=#ACCESSTOKEN");
webRequest.ContentLength = buffer.Length;
using (Stream stream = webRequest.GetRequestStream())
{
stream.Write(buffer, 0, buffer.Length);
using (WebResponse webResponse = webRequest.GetResponse())
{
if (webResponse != null)
{
using (StreamReader streamReader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
{
string data = streamReader.ReadToEnd();
}
}
}
}
Here the variable data will contain the result.
Salah, here is the example i use as reference, i am sorry though i do not remember where i found.
FB.api("/", "POST", {
access_token:"MY_APPLICATION_ACCESS_TOKEN",
batch:[
{
"method":"GET",
"name":"get-photos",
"omit_response_on_success": true,
"relative_url":"MY_ALBUM_ID/photos"
},
{
"method": "GET",
"depends_on":"get-photos",
"relative_url":"{result=get-photos:$.data[0].id}/likes"
}
]
}, function(response) {
if (!response || response.error) {
console.log(response.error_description);
} else {
/* Iterate through each Response */
for(var i=0,l=response.length; i<l; i++) {
/* If we have set 'omit_response_on_success' to true in the Request, the Response value will be null, so continue to the next iteration */
if(response[i] === null) continue;
/* Else we are expecting a Response Body Object in JSON, so decode this */
var responseBody = JSON.parse(response[i].body);
/* If the Response Body includes an Error Object, handle the Error */
if(responseBody.error) {
// do something useful here
console.log(responseBody.error.message);
}
/* Else handle the data Object */
else {
// do something useful here
console.log(responseBody.data);
}
}
}
});
Download popup dialog can be displayed by
window.location = "someUrl"
or just simply have a link that send HTTP GET method and so on. I've done this successfully.
But now I want to do Ajax with HTTP POST. The POST body has JSON like
{"val1":"key1", "val2":"key2"}
Then in servlet side, it read the JSON and execute query against DB to get data then generate Excel based on the query data.
The part I can't get it working is client side.
Assugming that my servlet at resources/report/schedule generates Excel file.
This does not popup download dialog when using Ajax :(
Can anybody help me how to have download dialog with Ajax?
function post25() {
var jsonInput = {};
jsonInput['作業区コード'] = "481";
jsonInput['機械コード'] = "11";
jsonInput['作業日'] = "2000/01/01";
jsonInput = JSON.stringify(jsonInput);
var ajaxRequest = new XMLHttpRequest();
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
var res = ajaxRequest.responseText;
//location.href = "../resources/report/schedule";
}
else if(ajaxRequest.status == 409 || ajaxRequest.status == 500 || ajaxRequest.status == 204) {
alert(ajaxRequest.status);
document.getElementById("showMessage").innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("POST", "../resources/report/schedule", true);
ajaxRequest.setRequestHeader("Content-Type", "application/json");
ajaxRequest.send(jsonInput);
}//end post25()
For security reason it is not allowed to download file using ajax.