Is it possible to call analytics API from javascript with jQuery?
I've been struggling with this for couple of days with no luck. I tried using CORS wich is sending OPTIONS request first which is rejected (405 error). Also tried with jsonp - but from what I read it has to be configured on server side?
Sample code (nothing fancy):
$.ajax({
url: 'https://analytics.algolia.com/1/searches/test/popular',
method: 'GET',
beforeSend: (xhr) => {
xhr.setRequestHeader('X-Algolia-Application-Id', 'sample');
xhr.setRequestHeader('X-Algolia-API-Key', 'sample');
},
success: (response) => {
console.log(response);
}
});
Also tried with crossOrigin: true, and dataType: 'jsonp'.
This API has not been designed to be called from the frontend (and therefore doesn't support CORS). You will need to build a proxy through your backend.
Related
I am planning to create a Restful API in yii for cross domain communication. As what I have researched, cross domain communication can only be done via jsonp and my implementation is as follows:
UsersController:: actionCrossDomain
public function actionCrossDomain(){
$this->layout=false;
$data['data']['User']['name']= 'Johny';
$this->_sendResponse(200, CJSON::encode($data),'application/json');
}
UsersController::_sendResponse methdod it is the same as you can see in :Click here
On another server that i configured using virtual host, I am invoking the above method via ajax:
$( document ).ready(function() {
$.ajax({
type: "POST",
dataType: "jsonp",
url:'http:'http//uxaserver.local/alpha2/app/users/crossDomain' ,
data: null,
processData: false,
crossDomain: true,
contentType: "application/json",
success: function (data) {
console.log("done");
},
error: function (request, status, error) {
console.log(request);
}
});
});
The issue is my firebug is is complaining that : SyntaxError: invalid label
My requirement is such because I am helping my client's to do some customized analytic to his other websites and I need to put a script in his web pages of different domains so that the analytic data is recorded in the main server. I understand that I need to use the rest interface to communicate thus I am taking this approach. I am not sure if I have taken the right approach and please advice. I want to make it in a way where a client has an api key and can communicate with the api provided by me.
Is there any other approach to do this? Rather than jsonp?
As i see this string contents error
url:'http:'http//uxaserver.local/alpha2_uxarmy/app/users/crossDomain' ,
Should be
url:'http//uxaserver.local/alpha2_uxarmy/app/users/crossDomain' ,
so far as I can tell my issue is that my GET request is not authorised. But my attempts to add authorisation in headers or as values in the URL (api key, username, password) are not being successful.
eg.
$.ajax({
type: 'get',
async: false,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});
Can anyone advise as to correct Javascript syntax for interacting with the Pingdom API? I believe I'm trying to authorize incorrectly Their documentation focuses on PHP which I'm unable to use in this situation.
https://www.pingdom.com/services/api-documentation-rest/#authentication
I don't think it's possible to use the Pingdom API from Javascript in a web browser.
You'll need to use jsonp to get your browser to allow ajax requests across sites, but according to this response it's impossible to set headers in a jsonp request.
Use CORS Anywhere.
I wanted to get a simple jQuery request working that checked the last Pingdom result for our platform. Because of CORS and the need to specify custom headers for authentication, this didn't seem possible.
I didn't want to setup a proxy server for something so simple so I found this answer and was able to use the CORS Anywhere method, which looks something like this:
// Will use the cors-anywhere proxy if jQuery supports it and crossDomain option is passed in.
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
// options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
// Use ajax requests as normal.
$.ajax({
type: 'get',
async: false,
crossDomain: true,
beforeSend: function(xhr){
xhr.setRequestHeader('Authorization', 'Basic encodedusername:passwordhere');
},
url: "https://api.pingdom.com/api/2.0/checks",
success: function(Data) {
console.log(Data);
},
error: function(Data) {
}
});
NOTE: Do not use this if you're passing or retrieving confidential information. You should use your own proxy if you're doing that. But if you're just getting public data, like we were, then this should be a nice and clean method to get around the CORS limitation.
I am trying to make a pure JavaScript Twitter application. I'm not concerned about the security involving the tokens since this is for internal use.
Currently, my code looks like this:
$.ajax({
url: 'https://api.twitter.com/oauth/request_token',
type: 'post',
data: {
oauth_callback: callbackurl
},
dataType: "jsonp",
headers: {
"oauth_nonce": nonce1,
"oauth_callback": callbackurl,
"oauth_signature_method": "HMAC-SHA1",
"oauth_timestamp": Math.round(new Date().getTime()/1000),
"oauth_consumer_key": "IQKbtAYlXLripLGPWd0HUA",
"oauth_signature": "Pc%2BMLdv028fxCErFyi8KXFM%2BddU%3D", //generate
"oauth_version": "1.0"
},
success: function(data)
{
console.info(data);
}
});
This code is rather incomplete, but the goal is to get what Twitter is returning (the request tokens). Obviously this code is not going to work because it violates cross origin policy. I have heard that this is possible with pure JavaScript, though. I need to send Twitter headers (at least, I think they have to be headers) then retrieve what they return.
Is there a workaround for this?
i have wsdl file and i need get data from. How i can do this ? i'm trying do this with ajax
like this:
jq.ajax({
url: 'http://url.wsdl',
type: 'get',
success: function(data){
alert("OK " + data);
},
error: function (x, y, z) {
alert("ERROR");
}
});
what i do wrong ?
Any other way to get data from wsdl web service using javascript, jquery and etc. is?
I think what you are missing is a data: {}
I read that there was some sort of bug if you did not include that when using $.ajax
Oh, and most likely you are going to need dataType: "json" or whatever datatype the service is using.
Here is an example i am using against an online webservice:
jQuery.support.cors = true; //enables cross domain queries for Ajax
$('#jqueryBtn').click
(function ()
{
$.ajax
(
{
type: "GET",
url: "http://www.webservicemart.com//uszip.asmx/ValidateZip",
data: { 'ZipCode': '22553' },
dataType: 'html',
success: jqSuccess,
error: jqError
}
);
}
Hopefully you can use this example to fix your own code
http://forum.jquery.com/topic/jquery-ajax-to-call-a-wsdl-web-service
The following link should explain why you cannot use AJAX for cross domain queries:
http://www.w3schools.com/xmL/xml_parser.asp:
Access Across Domains
For security reasons, modern browsers do not allow access across
domains.
This means, that both the web page and the file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your web pages, the file you load must be located on your own server.
You can create a proxy web page in your web server to access to WSDL web service and return result to the AJAX request
Can i Call web service from java script?
Thanks
Yes, you can do this.
Definitely. We would need a bit more information to know what kind of service you are using and if you are using a JS library. This is very easy with Dojo or EXT.
I'll show you a Dojo example as that is what I'm working with the most lately. I mostly create my services as REST services at this point. Depending on the service and how it's going to be used, I either send the response back as JSON or JSONP.
Below is an example for services that send the response as JSONP, which I use for cross-domain calls. You would need to use dojo.io.script.get (if using the Dojo library):
dojo.io.script.get({
callbackParamName: 'method',
url: 'http://mydomain/myservicename/mymethodname/param1/param2',
timeout: 20000,
load: dojo.hitch(this,function(response,ioArgs) {
this.doSomething(response);
}),
error: dojo.hitch(this,function(error) {
alert('uh oh, something went wrong');
})
});
For services that send the response back as JSON, you can use the following Dojo functions:
dojo.xhr, dojo.xhrDelete, dojo.xhrGet, dojo.xhrPost, dojo.xhrPut, dojo.rawXhrPost, and dojo.rawXhrPut depending on the type of call you make. Below is an example:
dojo.rawXhrPost({
url: url,
handleAs: 'json',
postData: parametersJSON,
headers: { "Content-Type": "text/json" },
timeout: 45000,
//function to be run in case of successful call to the specified Web method
load: function(data) {
onComplete(data);
},
//function to be run in case of failed call to the specified Web method
error: function(error) {
onError(error.message);
}
});
You can call a webservice on the same server as the page with a normal XHR call. If the server is on a different server then you should use a JSONP call. NOTE the JSONP doesnt have the best error handling.
You can easily call a JSON or a RESTful web service.
For SOAP web services you need a library.