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

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 :)

Related

Authenticate Javascript Program for Gcloud AutoML Vision API

I am currently working on a project whereby I have used gcloud automl to train an image classifier. I have got it working fine and it is able to handle my requests using access-tokens. However, my issue lies in that access-tokens only last for an hour. I would like to be able to create a method in my client-side javascript or another way to authenticate such that it is indefinite and I do not need to manually generate new tokens.
I have looked through the samples and docs on gcloud and found a sample that describes a possibility with the People API but I am not sure how to translate this to the Vision API.
Currently I am sending a request like the following:
$.ajax({
url: "https://automl.googleapis.com/v1beta1/projects/(project-id)/locations/us-central1/models/(model-id):predict",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + "access-token");
},
type: 'POST',
dataType: 'json',
contentType: 'application/json',
processData: false,
data: objString,
success: function (data) {
alert(JSON.stringify(data));
},
error: function(){
alert("Cannot get data");
}
});
If there is a way to alter this method (or write a new one) to make a permanent token or another authentication form that is indefinite, then that would be much appreciated.
You should use an environment variable along with a service account. Depending on your OS, you could use it until you turn off your machine, or set it as a permanent environment variable.

Long polling with ajax and servlets

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.

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!

Consuming web service in HTML

I have created a web service and saved its .wsdl file. I want to consume this service in my HTML file by providing its URL.
Can anybody tell me how to call the URL in HTML and use it?
Like its done here.
http://www.codeproject.com/Articles/14610/Calling-Web-Services-from-HTML-Pages-using-JavaScr/
The only difference is my web service does not have an extention like "asmx?wsdl".
Does that makes any difference.
I followed that tutorial too but it does not produce any output.
Thank You////
You definitly should get familiar with AJAX.
You could use the ajax functionalities provided by jQuery. That's the easiest way, I assume. Take a look at http://api.jquery.com/jQuery.ajax/
You can use this like
$.ajax({
url: "urltoyourservice.xml"
dataType: "xml",
}).done(function(data) {
console.log(data);
});
HTML itself cannot consume a webservice. Javascript ist definitely needed.
The existence of your WSDL File looks like you are probably using a XML format as the return of the web service. You have to deal with XML in javascript. Therefore take a look at Tim Downs explanation.
But keep in mind, that your web service URL must be available under the same domain as your consumption HTML-File. Otherwise you'll receive a cross-site-scripting error.
yes you can use ajax but keep in mind you wont be able to make a request across domains. Consuming web services should be done in server side.
To further gain more knowledge about this, read How do I call a web service from javascript
function submit_form(){
var username=$("#username").val();
var password=$("#password").val();
var data = { loginName: username, password:password };
$.ajax( {
type: "POST",
url:"Paste ur service address here",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
var value = data.d;
if(value.UserID != 0){
alert.html('success');
}
},
error: function (e) {
}
});
}
Try this it will help

Categories

Resources