There exist some parameters in the HERE Advanced Routing REST API which is not available in the Javascript API. Is it possible to combine the two APIs somehow (ie. request json route from REST API and display it in the Javascript map?)
The JavaScript API just maps the REST API up in a nice package but there is nothing unique about it. You should be able to call any of the REST API functions with jQuery using $.ajax. Looking at the API explorer I see that they use query parameters for most things so you will want to use the data attribute for all the params.
$.ajax({
url: "http://image.maps.cit.api.here.com/mapview/1.6/route",
type: "GET",
data: {
app_id: "xxxxx",
app_code: "xxxxx",
r0: "52.5338,13.2966,52.538361,13.325329"
r1: "52.540867,13.262444"
...
},
success: function () {...}
error: function () {...}
});
I actually ended up implementing this a bit differently, but I think both ways work equally well. The important part that gave me grief was the &routeattributes=all. Without it, shapes aren't returned so you can't draw the polyline, etc. In the PDF doc it's referred to as responseattributes in a few places which really messed me up. Anyways, I did:
var url = "https://route.st.nlp.nokia.com/routing/6.2/calculateroute.json?
app_id=XXX&app_code=XXX&routeattributes=all&jsoncallback=myCallBackFunction
&jsonattributes=41&waypoint0=[...]";
and then:
var script = document.createElement('script');
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
and
var myCallBackFunction = function (data) { ... }
Related
I'm very new to web development.
When I input this link
https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412
into my browser, I can see the JSON object.
What do I need to do so can I use this JSON object in my javascript? I've tried using JQuery's $.getJSON with no luck.
EDIT
Using JSONP worked! Appending &jsonp=readJSON&?callback=? to the URL gave me back the JSON I wanted. Thank you for all the informative answers.
$.getJSON( "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412&jsonp=readJSON&?callback=?", function() {
console.log( "success" );
})
function readJSON(response){
console.log (response);
}
The question is, is this domain (api.locu.com) the same from where you serve your files? I suppose it isn't. In this case, you have two options:
Your backend can proxy the request from this site
You have to use a JSONP object if it's supported by the API
I'm no clear about your question, but I think you can use a call ajax, something like:
$.ajax({
url: "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412",
type: 'get',
cache: false,
success: function (response) {
console.log(response);
}
});
This should get the concept across if you are using JQuery... but you can use just about anything.
var url = "https://api.locu.com/v1_0/venue/search/?name=jimmy%20johns&api_key=b1f51f4ae241770f72fca5924d045733c4135412";
var result;
var settings = {
success: function(data){
result = data;
//do anything else related to this data here as you need it fetched, and is not linear.
}
}
$.ajax(url, settings);
Now, I noticed you used getJSON, which is pretty much the exact same. I did not however see you use a success function, so if you did your way, have you tried:
$.getJSON(url, function(data){
result = data;
});
I may be mistaken, but you say: "With no luck" so i have a limited understanding as to what you tried with $.getJSON
Not directly from inside a web browser, no. You would need to use a proxy: another server that makes this request in your behalf and then gives you the result.
Why not?
Web browsers are pretty tight on security. One of the strategies for protecting users from malicious activity is restricting the domains your Javascript can make HTTP requests to.
An HTTP request from your domain (the origin) to another domain is called a cross-origin request. These are forbidden by default, and you won't be able to read the response body, unless the received HTTP response includes the header Access-Control-Allow-Origin.
How then?
By using a proxy as an intermediary. The proxy is not a web browser, it doesn't care about Access-Control-Allow-Origin, and will read the response anyway.
There are a number of proxies you can use. An easy one is YQL (the Yahoo Query Language). Here's an article on the topic, using jQuery: http://ajaxian.com/archives/using-yql-as-a-proxy-for-cross-domain-ajax
I am attempting to teach myself some JQuery/REST/Google API by putting together a simple page that does the following:
Authenticates with Google
Validates a token
Gets a list of Google Calendars for the user
List events for a selected calendar
Add an event for a selected calendar
I have #1 through #4 working (although no doubt in an ugly manner), and am getting tripped up on #5. Here's the JQuery ajax call:
var url = 'https://www.googleapis.com/calendar/v3/calendars/[MY_CALENDAR_ID]/events?sendNotifications=false&access_token=[GOOGLE_API_TOKEN]';
var data = { end: { dateTime: "2012-07-22T11:30:00-07:00" }
, start: { dateTime: "2012-07-22T11:00:00-07:00" }
, summary: "New Calendar Event from API"
};
var ajax = $.ajax({ url: url
, data: data
, type: 'POST'
}).done(addEventDone)
.fail(function (jqHXR, textStatus) {
console.log("addEvent(): ajax failed = " + jqHXR.responseText);
console.log(jqHXR);
});
The results are a global parseError: "This API does not support parsing form-encoded input.". The first four steps are all using GET ajax calls, so I'm not sure if that is what is tripping me up.
Here's the API in question: https://developers.google.com/google-apps/calendar/v3/reference/events/insert
I think I may be doing things the long and hard way, and my new approach is to tackle this using the javascript API instead of going straight at it with manual JQuery and REST. This is the approach I am attempting going forward http://code.google.com/p/google-api-javascript-client/wiki/Samples#Calendar_API, although I would still love to use this as a learning opportunity if there is something simple I am screwing up in the code above.
Thanks for any help, insights, pointers, etc. I will post updates if I make any progress using the javascript API.
Interestingly, I just answered a similar question here. Your intuition to use Google's JS client library is a good one. It's going to handle OAuth 2 for you, which is a requirement if you're going to do any manipulation of the Calendar data.
My other answer has both a link to a blog post that I authored (which demonstrates configuration of the client and user authorization), as well as an example of inserting a Calendar event.
you need to set contentType: "application/json", to do JSON.stringify for your data and method : 'POST'
var ajax = $.ajax({
url: url,
contentType: "application/json",
data: JSON.stringify(data),
method : 'POST',
});
Im trying out the new graph api for facebook. I'm trying to fetch some data using jquery ajax.
This is a sample of my javascript code, very basic...
var mUrl = 'https://graph.facebook.com/19292868552';
$.ajax({
url: mUrl,
dataType: 'json',
success: function(data, status) {
$('#test').html(data);
alert(data);
},
error: function(data, e1, e2) {
$('#hello').html(e1);
}
});
The url is to a page that does not need access tokens (try it using a browser), but the success function returns an empty object or null.
What am I doing wrong? Thankful for all help!
I have covered this and asked this question before. I made a quick tutorial which covers exactly this and explains it all.
In short:
JSON is not made for cross domain usage according to its same-origin policy. However the work around is to use JSONP which we can do in jQuery using the supported callback parameter in facebook's graph api. We can do so by adding the parameter onto your url like
https://graph.facebook.com/19292868552?callback=?
by using the callback=? jQuery automatically changes the ? to wrap the json in a function call which then allows jQuery to parse the data successfully.
Also try using $.getJSON method.
I was trying to do something similar, in testing I was able to get a working result which I saved on jsFiddle: http://jsfiddle.net/8R7J8/1/
Script:
var facebookGraphURL = 'https://graph.facebook.com/19292868552';
$.ajax({
url: facebookGraphURL,
dataType: 'json',
success: function(data, status) {
$( '#output' ).html('Username: ' + data.username);
},
error: function(data, e1, e2) {
$( '#output' ).html(e2);
}
})
HTML:
<html>
<body>
<div id="output">BorkBorkBork</div>
</body>
</html>
Hope that helps! :)
...The Graph API supports JSONP. Simply pass callback=methodname as an extra parameter and the returned content will be wrapped in a function call, allowing you to use a dynamically inserted script tag to grab that data.
http://forum.developers.facebook.com/viewtopic.php?pid=253084#p253084
You can't do cross-domain AJAX requests like that due to the same-origin policy. Instead, use Facebook's JavaScript SDK, which is based on a script tag.
I have read a lot about jquery and i have a webservice where i convert a companyID to the real companyName. Now i want to call that webservice with jquery or javascript. The webservice is on host http://webservice/service.asmx en i'm working on http://tlmos. I don't work and i always get an error
Here is my code:
<script type="text/javascript" src="http://kmosvi24/_layouts/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var test = "KBEACDNV";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://webservice/service.asmx/getCompanyByCompanyID",
data: "{'sCompanyID:' + 'test'}",
dataType: "json",
succes:function(response){ alert("good"); },
error: function(response) { alert("Uh oh"); },
complete: function(response) { alert("" + response); }
});
</script>
Can someone help me?
thx
Umm.. you spelled success wrong on line 11
.. and you probably want to format your data as
data: "sCompanyID=test"
Take a quick pass through the jQuery API page on this one to verify you are passing the parameters that your service expects. It looks like you are expecting a SOAP packet with an ASMX service, and jQuery is more suited to hitting a restful service generated from an ASHX file or WCF service.
You can make a request to a different server, but only if the call uses GET. Since all you do is lookup anyway, a GET request should be fine.
As some othe people have pointed out you cannot call a webservice on another domain, however as you are using ASP.NET, you can write a raw HTTP handler (normally with an .ashx extension to proxy your request from client to server.) Which you'd place on your "timos" server
so in your ashx file you can write something along the lines of...
public void ProcessRequest (HttpContext context)
{
XmlDocument wsResponse = new XmlDocument();
string url = "http://webservice/service.asmx/getCompanyByCompanyID?CompanyID="
context.Request.Form["CompanyID"].ToString()
wsResponse.Load(url);
string XMLDocument = wsResponse.InnerXml;
context.Response.ContentType = "text/xml";
context.Response.Write(XMLDocument);
}
Hope this helps.
You can't do AJAX calls to hosts other than your own. If you really have to do this make a call to your own server and use a simple proxy to redirect to the domain you need.
You could do this for example by using a ProxyPass-directive in your webserver:
ProxyPass /service/ http://webservice/service.asmx
ProxyPassReverse /service/ http://webservice/service.asmx
Then you can issue an AJAX-request to /service/getCompanyByCompanyID and it will be proxied to the correct URL.
I don't think you are using the data parameter right, usually it's a key-value pair like:
data: {sCompanyID: 'test'}
I believe that they way you are using it will result in jQuery attempting to post to http://webservice/service.asmx/getCompanyByCompanyID?sCompanyID:blah
Also aren't .NET web services SOAP? I don't think jQuery can parse that...
edit: Nevermind, didn't realize you were passing these as json data. Thanks commenters!
In order to run your web-services from Jquery, you should use either WCF or just usual web services, but you should add [ScriptMethod] to your service's method and [ScriptService] to your webservice description.
Wow wow
just noticed that you're trying to call the service from one host to another... that one won't work. service should be hosted on the same domain as the page where it's being called from.
as a reply to Jeff's answer, correct way to format data is data: {key: "value"}
With jQuery Ajax Requests you need to use the following format when defining the variables to be sent in the request:
data: "variableName=variableContent",
You wrote:
data: "{'sCompanyID:' + 'test'}"
This won't work for two reasons:
- You have included curly brackets which don't need to be there.
- You have used a semi-colon,":", instead of an equals sign,"=".
So long as you change these it should work.
P.S I only just realized that Jeff Fritz has already given you the right answer. His answer is spot on!
I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.
I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.
Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.
Here's an except from MVC RC1 release notes - Jan 2009
IsMvcAjaxRequest Renamed to IsAjaxRequest
The IsMvcAjaxRequest method been
renamed to IsAjaxRequest. As part of
this change, the IsAjaxRequest method
was updated to recognize the
X-Requested-With HTTP header. This is
a well known header sent by the major
JavaScript libraries such as
Prototype.js, jQuery, and Dojo.
The ASP.NET AJAX helpers were updated to send this header in
requests. However, they continue to
also send it in the body of the form
post in order to work around the issue
of firewalls that strip unknown
headers.
In other words - it was specifically renamed to be more 'compatible' with other libraries.
In addition, for anyone who hasnt read the full release notes but has been using previous versions - even as recent as the beta - I STRONGLY recommend you read them in full. It will save you time in future and most likely excite you with some of the new features. Its quite surprising how much new stuff is in there.
Important note: You will need to make sure you upgrade the .js file for MicrosoftAjax.MVC (not the exact name) if upgrading to RC1 from the Beta - otherwise this method won't work. It isn't listed in the release notes as a required task for upgrading so don't forget to.
See Simons answer below. The method I describe here is no longer needed in the latest version of ASP.NET MVC.
The way the IsMvcAjaxRequest extension method currently works is that it checks Request["__MVCASYNCPOST"] == "true", and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the __MVCASYNCPOST value into your request and then you could take advantage of the IsMvcAjaxRequest extension method.
Here is a link to the source of the IsMvcAjaxRequest extension method for your convenience.
Alternatively, you could create a clone of the IsMvcAjaxRequest extension method called
IsjQueryAjaxRequest that checks Request["__JQUERYASYNCPOST"] == "true" and you could dynamically insert that value into the HTTP POST.
Update
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
public static class HttpRequestBaseExtensions
{
public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
{
if (request == null)
throw new ArgumentNullException("request");
return request["__JQUERYASYNCPOST"] == "true";
}
}
Checking from an action if a method is a jQuery $.ajax() request:
if (Request.IsjQueryAjaxRequest())
//some code here
JavaScript
$('form input[type=submit]').click(function(evt) {
//intercept submit button and use AJAX instead
evt.preventDefault();
$.ajax(
{
type: "POST",
url: "<%= Url.Action("Create") %>",
dataType: "json",
data: { "__JQUERYASYNCPOST": "true" },
success: function(data) {alert(':)');},
error: function(res, textStatus, errorThrown) {alert(':(');}
}
);
});
Why don't you simply check the "X-Requested-With" HTTP header sent automatically by most Javascript libraries (like jQuery) ?
It has the value 'XMLHttpRequest' when a GET or POST request is sent.
In order to test it you should just need to check the "Request.Headers" NameValueCollection in your action, that is :
if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
return Json(...);
else
return View();
This way, you can simply differentiate regular browser requests from Ajax requests.
Ok, I have taken this one step farther and modified my jQuery file to load the additional parameter into the post data, so I don't have to repeat the "__JQUERYASYNCPOST: true" for every call to post. For anybody that's interested, here's what my new definition for $.post looks like:
post: function(url, data, callback, type) {
var postIdentifier = {};
if (jQuery.isFunction(data)) {
callback = data;
data = {};
}
else {
postIdentifier = { __JQUERYASYNCPOST: true };
jQuery.extend(data, postIdentifier);
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
}
I added the "postIdentifier" variable as well as the call to jQuery.extend. Now the Helper explained in spoon16's response works without having to add any thing special to my page-level jQuery code.