Cross-domain issue with Jquery - javascript

I am trying to create a chrome extension which will look up the meaning of input vocabulary from this URL: http://hanviet.org/ajax.php?query=%E6%97%A5&methode=normal
I made an ajax call by using jquery but got an error because of the cross-domain issue: "No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access". Ok, I guest that instead of make a request directly to the URL, I need to call it through a proxy pages as below:
$.get("/myproxy.php?query=日&methode=normal", function( data ) {
alert( "Load was performed." );
});
After doing a google search, there is another chrome extension named DHC to makes http request: https://www.sprintapi.com/dhcs.html. and It works perfectly!
I am wondering that does DHC tool also send a request through its proxy or there is another way to make a direct request that I dont know.
Thank you!

$.ajax({
type: "GET",
url: 'URL',
jsonp: 'callback',
dataType: 'jsonp',
data: {},
success: loginSuccess,
crossDomain: true,
error: ajaxFailed,
contentType: 'application/json',
async: false
});
function ajaxFailed(result) {
alert("Failed: " + result.status + ' ' + result.statusText);
}
function loginSuccess(data) {
alert('Result: ' + data.d);
}

If you use the developers tools of chrome on that site, on Network tab you will see that after pressing the sendbutton it loads the content from https://www.sprintapi.com/api/proxy, so yes, it should be using a proxy.
Even more, as you say the Access-Control-Allow-Origin would'nt let they did it on another way I think.

Related

Getting parse error while fetching text file content in JQuery

I am trying to fetch data from text file which resides on server. I have access of that location and able to see content when I put URL in browser tab.
I am trying to make AJAX call and get file content, but I am getting Error: Uncaught SyntaxError: Unexpected identifier
Code
function logResults(json){
console.log(json);
}
$.ajax({
url: u,
dataType: "jsonp",
jsonpCallback: "logResults"
});
on console,
I tried below code too, but same result,
$.ajax({
type: 'GET',
url: u,
crossDomain: true,
dataType: 'jsonp',
async: false,
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function(succ) {
console.log("Success: ", succ)
},
error: function(err) {
console.log("Error: ", err)
}
});
This code is always going into error block.
You said:
dataType: "jsonp",
But the URL is responding with:
Deployment automatically finished…
Which is not JSONP, it is plain text.
You get the error when it tries to execute the plain text as JSONP.
Don't put wrong information in the dataType field.
async: false,
That's deprecated. Don't use it. It's also pointless since you are using callbacks.
It's also incompatible with JSONP so it is ignored (until you remove the incorrect dataType).
crossDomain: true,
This has no effect unless you are making a:
non-JSONP request
to the same origin
which gets redirected to a different origin
… which is very rare.
headers: {
"Access-Control-Allow-Origin": "*"
},
Access-Control-Allow-Origin is a response header. It doesn't belong the request. Trying to add it to the request will cause extra problems as it will make the request preflighted.
(At least, that would be the case if you hadn't said dataType: 'jsonp' because adding request headers is incompatible with JSONP).
All you need on the client
The only code you need on the client is:
function logResults(result){
console.log(result);
}
$.ajax({
url: u,
success: logResults
});
The server you are requesting the data from will need to use CORS to grant you permission to access it if it is a cross-origin request.
It is because you have added dataType as jsonp, so that it will try to parse the response to JSON and if the response is not a JSON it will throw error.

Authentication in URL for javascript

I am trying to write a simple script to obtain JSON data but the target requires login information in the actual URL like so:
http://login:password#URL/theapi
It appears that when using either getJSON or straight ajax the login details get skipped though even when passed on. I get an 401 error in developer tools in Chrome where it's interesting that the link in the error, when clicked, will actually go through and get he JSON data in to the browser
Is there a way around this?
Is there a way around this?
Yes, while making the AJAX call, don't attach login:password in the url. Instead, add Authorization header with Base64 encoded value of login:password. This is how we can do using JQuery:
$.ajax({
type: "GET",
url: "https://domain.tld",
dataType: "json",
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(login + ":" + password));
}
});

Firefox extension missing Referer url in ajax header when making ajax calls

I am trying to make an ajax call to a server and the server needs referer url to identify my request
$.ajax({
url: abc + '/123/xyz/',
cache: false,
type: 'GET',
crossDomain: true,
headers: {
"key": "xxxxxxxxxxx"
}
}).done(function(result) {
executeOnSuccess();
});
The expected result on the server should be that if i execute this line request.getHeader("referer");
I should get the referer url but i get a null, but if i make the same ajax request using chrome extension it works and i get the referer url.
I have been stuck on this for a while now. The other option is to add referer url manually to the ajax header but i was expecting it to work like chrome?
Does any one has any idea about it ?
Thanks in advance.
The browser will always overwrite the referrer. Meaning you can't change the referrer of an ajax call. But you can try!
$.ajax({
url: abc + '/123/xyz/',
type: "GET",
headers: {
"Referer": "Change here reference"
},
success: function (data) {
alert("Success");
},
error: function (data) {
console.log(data);
}
});
Also, note that if you are planning to submit your extension in AMO, you should always use https in your calls to any server.

Calling External API with Javascript

I need to make a POST request to an external server from my webpage using Javascript. The body and response are both json. I can't figure out how to make this call or what tools to use. How do I make this call?
This is what I have so far using jQuery and ajax:
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'json',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
It is throwing a alerts that just says "Status:" and "Error:"
The console says this "XMLHttpRequest cannot load http://[domain]/vizportal/api/web/v1/getViews. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[domain]' is therefore not allowed access. The response had HTTP status code 405."
Are you the owner of the destination of the call? If yes, implement the CORS headers in server-side.
If no, you can fiddle using JSONP (it bypasses CORS) or you can even implement a server-side proxy that you own to route external requests (and of course, implement CORS there).
Check out the article on CORS in MDN if you want more information : HTTP access control (CORS) on MDN
You can use JQUERY and AjAX. You can send/get information information to/from your API either by post or get method.
It would be something like that:
$("#ButtonForm").click(function(){
$.ajax({
url:(Your url),
dataType:'json',
type: 'post',
data: yourForm.serialize(),
success:function(response){
** If yout API returns something, you're going to proccess the data here.
}
});
});
Ajax:
http://api.jquery.com/jquery.ajax/
You are violating the so called same-origin-policy here. Most browsers don't allow a script to access URLs that do not have the same hostname and port than the page where the script is located. This is a very strict security policy and has often been very difficult to overcome even for testing purposes.
Traditionally the easiest way to go around this has been to use your own web site as a proxy and forward the request through it to the external server. But if you don't have enough control on your own site to implement such a solution, things have been more complicated. If you search the Internet with "same-origin-policy", you'll find a lot of discussion on the topic and other ideas to solve it.
My first suggestion would be to check the "Access-Control-Allow-Origin" that your error message mentions, though I'm not familiar with it myself. It is related to a new scheme called CORS that has been added to W3C recommendations quite recently (2014), and seems to have a wide support in the newest versions of many browsers. Maybe we developers are finally getting some tools to work with this irritating issue.
When you want to use different domain ajax call then you need to use the JSONP datatype which will allow browser to do cross domain request.
Here is more document for the JSONP : https://learn.jquery.com/ajax/working-with-jsonp/
var body = '{"method":"getViews","params":{"filter":{"operator":"and","clauses":[{"operator‌​":"matches","value":"'+ inputValue +'"}]},"order":[{"field":"name","ascending":true}],"page":{"startIndex":0,"maxIt‌​ems":5}}}';
var response = $.ajax({
url: "http://" + environment + "/vizportal/api/web/v1/getViews",
method: "post",
dataType:'jsonp',
data: JSON.stringify(body),
headers: {
'Content-Type': 'text/plain',
'X-XSRF-TOKEN' : XSRFToken,
'Cookie': 'workgroup_session_id='+workgroupSessionId+';XSRF-TOKEN='+XSRFToken
},
success:function(response){
alert("success");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
If you use jquery, use .post, or .ajax, to submit
$.post(url, data, callbackSuccess, callbackError);
more about these methods here http://api.jquery.com/jquery.ajax/
example:
var url = 'http://example.com/path/endpoint';
$.post(url, {name: 'Darlan', lastname: 'Mendonça'}, function(response){
// callback success
}, function(response) {
// callback error
});

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.

Categories

Resources