Long polling with ajax and servlets - javascript

I'm doing a project using javascript for client side and servlets for server side. I'm trying to implement a way to update client info real time. i.e when a client update some info in the web application, other clients will also see the update. I found that long polling is a good technique for this. This is the code I tried to get to work.
function poll() {
setTimeout(function() {
$.ajax({
type: "GET",
url: "server",
contentType: "application/json",
data: {
type: "update",
card: "string"
},
success: function(data) {
alert(data);
},
error: function(data) {
alert('eroor');
},
dataType: "json",
complete: poll });
}, 5000);
}
I'm trying to send a request to the server every 5 seconds and get the response with new updates. But in all the skeleton codes I saw in the web, data: is not set. Without setting it, how would the sever know the type of request it received since there are other types of requests too. But when I set data: no requests are sent from the client. But without setting data: requests are sent to the server. Is it wrong to set data: ? Without it how would I let the servlet know the type of the request?
I understand that like mentioned in here long polling is not what I'm trying to do. But can anyone explain what I should do and where I'm doing wrong.

Since you make a GET request, the data values are appended to the URL as URL parameters. Your servlet must then use request.getParameter("type") and request.getParameter("card") to extract the information from the request.
If you think that no request is sent, first check your console for errors and look at the net communications panel in the developer tools of your browser.

data:
issue is how you set the data. If you want to send json object, you have to stringify before you send it, like below.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Without it how would I let the servlet know the type of the request?
What you mean by this? to know the contentType? If so, send contentType parameter as above.
I understand that like mentioned in here long polling is not what I'm trying to do. But can anyone explain what I should do and where I'm doing wrong.
Yes. This is not exactly a long polling. This is how you send a request to the server in every 5 seconds. Anyway server should support to long polling.

Related

Retrieve value from open external API - visual studio - javascript - AJAX

I would really appreciate some advice, I'm trying to retrieve information from an open API for the first time.
The API details are here,
https://data.police.uk/docs/method/neighbourhood-locate/
I want to retrieve the 'force' and 'neighbourhood' values and save them into variables, I want to save them as variables as I'm then calling googlemaps to display the KML map. I managed to get quite far on other sections of my code, such as geocoding a user inputted address and retrieving the Long/Lat, but I am now struggling to send the long/lat to the external API and save the response.
I've hardcoded the long/lat into the below URL for this advice request, I think I'm getting a response from the API but failing to capture the values into my variables. The debugger shows the following response, {"force":"metropolitan","neighbourhood":"00BK17N"}, below is my code,
var ForceId; //returned from the API
var Neighbourhood; //returned from the API
accessURL = "https://data.police.uk/api/locate-neighbourhood?q=51.500617,-0.124629"
//Use the zip code and return all market ids in area.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: accessURL,
dataType: 'jsonp',
success: function (data) {
ForceId.push(val.force);
Neighbourhood.push(val.Neighbourhood)
console.log(ForceId);
console.log(Neighbourhood);
}})
I made a few mistakes, after seeing the responses were coming back as errors for its syntax, I adjusted some settings, I removed contenttype as 'application/JSON' and the response could be seen in the consolelog to contain the needed parameters. I'm not sure of the implications of doing this or if its bad practice as I'm extremely new at this, its my first attempt at working with API's. So other may advise better.
function GetPolice(){
$.ajax({
type: "GET",
// contentType: "application/json; charset=utf-8",
url: accessURL,
dataType: 'json',
success: function(data) {
ForceId = data.force;
Neighbourhood = data.neighbourhood;
},
})
}
If your new at this, then my suggestion is to tinker with 'success, error, complete' to see what responses are being returned to consolelog. Have a look at what your 'datatype' should be from the external API. Again, i'm not best placed to give advice but hope other new people find this helpful.
I now need to make the above a callback response, as it completes the function before the responsehas been recieved, I wish to use the response in another fucntion elsewhere, but thats a different challenge :)

Sending data to server using get request header

I use jQuery to contact my REST service on server side. The URL looks like this:
http://bla.com/?userid=1,2,3,4,5,6...
The userid string could be very long and it could happen that the max url size will be exceeded.
I can't do a post request, so my question is, whether it would be a good solution to send the userid data within the header? Something like this:
$.ajax({
url: 'someurl',
headers:{'foo':'bar'},
complete: function() {
alert(this.headers.foo);
}
});
Would this be possible?
Thanks
Yes you can send header using Ajax request
$.ajax({
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("Authority", authorizationToken);
},
url: "entities",
data: "json=" + escape(JSON.stringify(createRequestObject)),
processData: false,
success: function(msg) {
$("#results").append("The result =" + StringifyPretty(msg));
}
});
you can read more about header on jQuery AJAX page
Also check this example here
This is totally possible, alhough it would be advisable to just use POST, because it was meant to transfer lots of data.
Using headers is a workaround which results in the same results as POST; losing the ability to navigate forward and back without re-submitting (or re-sending headers in this case, will be impossible if the data is gone).

How do I do an ajax call to a database using Javascript, a URL and a key

I have been given a url of type xxxx.xxxxx.com as well as a key of type FGHyehgvc787vbhj
in order to gain read-only access to an sql database and retrieve data from it using javascript.
I have no prior experience with databases and maybe my question will sound completely stupid but I was wondering how can I combine the above information in order to get access to the database (e.g. do an ajax call and retrieve data from it..)
I'm familiar with doing ajax calls to a webpage and getting data from it using jQuery, as in :
$.ajax(/*url of website*/, function (data)
{
var dataRetrieved = $(data);
// do something with the data retrieved...
});
so I was wondering whether there is something equivalent to the above when it comes to making an ajax call to a database, using however a key.
Thank you for any help, and please delete this post if you find it completely pointless and excuse me in advance for that by the way.
It is usually very bad design to allow client side code to interact with your database in any way. This can be a huge security issue. Generally you will want your server side code to do this (e.g PHP, node, etc.). You would send a request to your server with client side code, and the server side code would do the actual work of updating the database.
you can create a wcf service and call that service through ajax, that wont be huge security issue.
try this
$.ajax({
cache: false,
type: "GET",
async: false,
data: {},
url: http:xxxxxxxxxxxx.svc/webBinding/Result?metaTag=" + meta,
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
success:function(result){},
error: function(){alert(err);}
});
Use this
$.ajax({
url: 'path/to/server-side/script.php', /*url*/
data: '', /* post data e.g name=christian&hobbie=loving */
type: '', /* POST|GET */
complete: function(d) {
var data= d.responseTXT;
/* Here you can use the data as you like */
$('#elementid').html(data);
}
});
Hope this helps...

getting json string from web service

I have got a web service which gets list of users from an external system and returns as json. and I call that webservice via jquery ajax.; I have placed ajax code below
$.ajax({
type: "GET",
url: webMethod,
data:"",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function(msg) {
alert(msg.d);
},
error: function(e) {
alert(e);
}
});
Even though, the output is in correct format, the output I get from jquery.ajax seems to be wrong. it returns big chunk of the data correctly, then adds "; (" and continues to show the output.
Basically, the output is ("around %75 of data");(rest of the data) which makes my json invalid. I am not sure whether it is related to the maxJasonLenght or not but I also set it to the maximum. there seems to be a limitation on how much data you can get from web service as if I add more data to that json, the break down point changes.
Sample Output
[{"UserName":"a.b","FullName":"a b"},{ Many other users},{"UserName":"c.d","FullName":"c d"},{"UserName":"e.f",);jsonp1364397526212("FullName":"e f"}, {"UserName":"g.h","FullName":"g f"},{other users}}
do you have any idea why I am having this issue?
Thanks
Do you set the crossDomain option to TRUE? If I'm not wrong, if you set the crossDomain option to TRUE, the response would be JSON-P.
Look at this post so you can figure out how to handle the response:
What is JSONP all about?
I hope it would help!

jQuery .getJSON vs .post which one is faster?

Using
$.getJSON();
or
$.post();
I'm trying to send some parameters through a page that is just for AJAX request
and get some results in JSON or html snippet.
What I want to know is that which one is faster?
Assume the HTML file would be simply plain boolean text (true or false)
As others said there is no real difference between the two functions, because both of them will be sent by XMLHttpRequest.
If the server is handling both of the requests with the same code then the handling times should be the same.
Therefore the question can be translated to which one is faster the HTTP GET request or the POST request?
Because the POST request needs two additional HTTP headers (Content-Type and Content-Length) comparing to the GET request the latter should be faster (because less data will be transferred).
But that's just the speed, I think it's better to follow the REST guidelines here. Use POST if you're modifying something, use GET if you want to fetch something.
And one another important thing, GET responses could be cached, but I was having problems caching POST ones.
i dont think it will make a difference both make use of ajax, .post loads the data using http post request where as getJSON uses a http get request more over you dont have to explicitly tell getJSON the dataType
If it is a HTTP action that is retrieving data from the server without persisting (updating) anything, GET is the correct semantic to use.
Both post and get use HTTP so performance difference will be negligible, especially considering the variables of WAN communication.
They are both wrappers/shorthand methods for jQuery.ajax, so there wont be a performance difference.
This is old but ...
We all have to remember about: CSRF/XSRF.
If you do it this way:
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: {
token : 'pass-some-security-token-here'
},
cache: false,
success: function(data) {
//do your stuff here
}
});
you can receive it then like this, nullifying most CSRF/XSRF
if (isset($_POST['token'])) { //you can also test token further
//do your stuff her and send back result
} else {
//error: sorry, invalid, or no security token
}
In many cases GET is an invitation for bad guys, as getJSON uses GET HTTP request.
$.getJSON(); is a shortcut to $.ajax(); which also calls $.post(); so you won't see much difference (but it will be easier to use $.getJSON() directly).
See the jquery doc
[EDIT] NimChimpsky was faster than me...
There are no difference, Because both are using XMLHttpRequest.
First, $.getJSON() is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
https://api.jquery.com/jQuery.getJSON/
Second, $.post() is also a shorthand Ajax function, which is equivalent to:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
https://api.jquery.com/jquery.post/

Categories

Resources