Creating an API in yii for cross domain communication - javascript

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' ,

Related

Algolia analytics API cannot be called from frontend application?

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.

How to get a json response from yaler

I create an account with yaler, to comunicate with my arduino yun. It works fine, and i'm able to switch on and off my leds.
Then i created a web page, with a button that calls an ajax function with GET method to yaler (yaler web server accept REST style on the URL)
$.ajax({
url: "http://RELAY_DOMAIN.try.yaler.net/arduino/digital/13/1",
dataType: "json",
success: function(msg){
var jsonStr = msg;
},
error: function(err){
alert(err.responseText);
}
});
This code seem to work fine, infact the led switches off and on, but i expect a json response in success function (msg) like this:
{
"command":"digital",
"pin":13,
"value":1,
"action":"write"
}
But i get an error (error function). I also tried to alert the err.responseText, but it is undefined....
How could i solve the issue? Any suggestions???
Thanks in advance....
If the Web page containing the above Ajax request is served from a different origin, you'll have to work around the same origin policy of your Web browser.
There are two ways to do this (based on http://forum.arduino.cc/index.php?topic=304804):
CORS, i.e. adding the header Access-Control-Allow-Origin: * to the Yun Web service
JSONP, i.e. getting the Yun to serve an additional JS function if requested by the Ajax call with a query parameter ?callback=?
CORS can probably be configured in the OpenWRT part of the Yun, while JSONP could be added to the Brige.ino code (which you seem to be using).
I had the same problem. I used JSONP to solve it. JSONP is JSON with padding. Basically means you send the JSON data with a sort of wrapper.
Instead of just the data you have to send a Java Script function and this is allowed by the internet.
So instead of your response being :
{"command":"digital","pin":13,"value":0,"action":"write"}
It should be:
showResult({command:"analog",pin:13,value:0,action:"write"});
I changed the yunYaler.ino to do this.
So for the html :
var url = 'http://try.yaler.net/realy-domain/analog/13/210';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'showResult',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.action);
},
error: function(e) {
console.log(e.message);
}
});
};
function showResult(show)
{
var str = "command = "+show.command;// you can do the others the same way.
alert (str);
}
My JSON is wrapped with a showResult() so its made JSONP and its the function I called in the callback.
Hope this helps. If CORS worked for you. Could you please put up how it worked here.

Feeding webpage data via remote Web API

I'm trying to operate two servers.
MVC Web API service.
MVC Web application.
The idea is that the web application renders a page filled with javascript requests, which populate the actual data from the remote API service. The web application will never itself touch the database, or the API service (besides setting up authorisation tokens initially).
What is the best way to achieve this?
So far I've been using JQuery AJAX requests, attempting to use JSONP. However I always get "x was not called" exceptions.
$.ajax({
url: '#(ViewBag.API)api/customer',
type: 'get',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: function (data) {
debugger;
// code to load to ko
},
error: function (xhr, status, error) {
alert(error.message);
}
});
Also the jsonpCallback function is called before the request is sent, so I assume its actually trying to call a function to generate a string? If I reform this request:
window.success = function (data) {
debugger;
// code to load to ko
};
... with jsonpCallback being "success", I still get the same error (but the success method is never called.
Any ideas? Thanks.
Edit: I've gotten started on the right course from this:
http://www.codeproject.com/Tips/631685/JSONP-in-ASP-NET-Web-API-Quick-Get-Started
Added the formatter, and replaced jsonCallback with success, like a normal ajax. However this only seems to work for get. I cannot delete or update. :(
Can you get it to work using the $.getJSON method?
$.getJSON( "ajax/test.json", function( data ) {
//handle response
});
Have you fired up developer tools in IE and watched the network traffic to see precisely what is being sent and returned?

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

Ajax get request to wsdl web-service

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

Categories

Resources