Im doing a simple ajax request like:`
$.ajax({
type: 'POST',
url: 'http://' + serverIP + '/saveJSON.php',
crossDomain: true,
data: 'helloooooooooo',
dataType: 'text',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
console.log(responseData);
console.log(textStatus);
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.' + responseData);
console.log(responseData);
console.log(textStatus);
}
});`
And when running this in IOS Safari i get the error ...
"XML HttpRequest cannot load ...... Orgin ... is not allow by Access Control Allow Orgin
... Is to replace long URL's
I know I chrome I can by pass this by loading chrome with a -disable-web-security or other flags.
How can I get around this in iOS ? Security is not an issue as the devices will be locked down and only allow communication between certain IP address's.
Is there any other method of retrieving information from a server php script in JavaScript? That will be allowed?
Also any links to good websites for AJAX communication with PHP would be helpful.
Just to add, All my pages the client uses/sees are HTML (.html) and the server side is (.php)
Also when following THIS link for sorting this issue i added the header to my IIS 6 for my htmls are hosted and the ipad still doenst allow this.
Thanks guys
You can do this by adding Access-Control-Allow-Origin header.
In PHP it can be doing for example by adding new header in your PHP file:
header('Access-Control-Allow-Origin: *');
Related
I am trying to send a file creation request to a remote RESTful API.
Whenever I do this from a local server, it works fine. Whenever I do this from an iOS device, it fails with a CSRF validation failed error. As far as I can tell, that shouldn't happen as it is the exact same code executing on both devices...
This is built using PhoneGap/Cordova. The version of iOS is iOS 11 and the iOS device is an iPhone 8.
Here's the code:
var mathRandom = Math.random();
var data = {"file": {
"file": base64,
"filename": localStorage.username + mathRandom + ".jpg",
"filepath": "public://" + localStorage.username + mathRandom + ".jpg"
}
};
var result = $.ajax({
type: "POST",
data: data,
url: SITE_URL + "/" + ENDPOINT + '/file.json',
dataType: 'json',
async: false,
error: function (jqXHR, textStatus, errorThrown) {
moduleDebugger('account', errorThrown, "FILE SAVE ERROR");
return 'null';
},
success: function (data, textStatus, jqXHR) {
moduleDebugger('account', data, 'success');
}
});
(Yes, I know it is async, but this block of code absolutely MUST execute before anything after it - I am fine with the UX degradation)
I am using the same user, permissions are currently set so that ANYONE should be able to create files, even anonymously (for testing).
My CORS settings are these:
Internal path
Access-Control-Allow-Origin. Use <mirror> to echo back the Origin header.
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
*|<mirror>|GET, PUT, POST, DELETE|Content-Type, Authorization, X-CSRF-Token|true
What would prevent a mobile user from saving a file, but not a user from localhost? Note, the server where the file will be saved is remote to both of these devices.
This is the error message:
Failed to load resource: the server responded with a status of 401
(Unauthorized : CSRF validation failed)
I am also getting the error:
Failed to load resource: Data URL Decoding Failed
But I am unsure if it is related to the above error - it comes a while after this error occurs. I have been unable to pinpoint what is causing it to occur.
EDIT: Even a static base64 string that I've tested repeatedly on localhost doesn't work.
I am using CI3 for one of my application.
I do have some api created which is using different domain than that of application.
$.ajax({
url: "http://www.example.com/restapi/index.php/api/user",
type: "GET",
data: {"user_id": user_id},
username: "****",
password: "****",
success: function(response){
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
},
xhrFields: { withCredentials: true }
});
When I call this api to get some data using jquery ajax I get error
NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
so I get to know that due to different subdomain of my application and api I can not access it.
Is there any way to allow access to api of different subdomain.
I am using authorization in API.
I don't want to call some php file in which I call that API using some php function, that make no sense. I want to call API directly.
Let me know way to do this and access API.
You are breaking the same origin policy (https://www.w3.org/TR/cors)
Sub domains, different ports, different protocols are considered different domains.
<?php
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: GET, OPTIONS"); //Or post
header("Access-Control-Allow-Origin: http://clientdomain");
?>
Here more details for CI: https://github.com/chriskacerguis/codeigniter-restserver/issues/345
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,"maxItems":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,"maxItems":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
});
I've got the following problem: I need to download a JSON file from an API via JQuery / JavaScript. In theory this should be quite basic.
I tried $.ajax and all of its siblings like $.get or $.getJSON. I alway get an 200 OK but my Firebug reports an error. Printing the error just says: "error" - so not that helful.
I read that maybe the JSON file is corrupt. So I tried it with a plain text file (*.txt). Same result.
The JSON file is valid, I check it against a validator.
I also tried ContentType and dateType and experimented with json and jsonp...
I basically used something like this (with a million variations for testing purposes):
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
...
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.statusText);
}
});
Am I missing something important here? It's really odd that nothing seems to change the behavior of the AJAX-call.
In fact I don't really need AJAX because I need to grab the JSON file when loading the page...
And the JSON file is not on the same domain as the AJAX caller.
Is that URL located on the same server you're trying to get the data from?
If not, you ran into a cross-domain request, which can only be handled using JSONP. So, the JSON file itself must be compatible with JSONP format, otherwise jQuery won't be able to process it (even if you provide a 'jsonp' dataType).
P.S.: Firebug will always show response code 200 but give an empty response body for such requests
Try in this way by disabling security
$.ajax( {
type : 'GET',
contentType : "application/json; charset=utf-8",
url : surl, \\specify your url
async : false,
dataType : 'json',
headers : {
Accept : "application/json",
"Access-Control-Allow-Origin" : "*"
},
crossDomain : true,
success : SucceedFunc,
error : function(data, textStatus, errorThrown) {
console.log("error" + ' ' + JSON.stringify(data) + ' ' + textStatus + ' ' + errorThrown);
}
});
function SucceedFunc(data) {
alert("success");
}
}
Did you try to catch the error the correct way?
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.message);
}
});
If you are using chrome go to cmd prompt and run the chrome by disabling the security. You can disable security using pathwhere_chrome_is_located\chrome.exe --disable-web-security
and run the html page. I think this may help you.
I'm trying to build a .js file that sends data to an external API, waits for a response and interprets the results. The external API is XML-based and accepts an HTTPS Post with the XML as body (content-type; text/xml). I can call the API correctly via cURL.
This is what I have so far:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body onload="CallService()">
<script type="text/javascript">
var webServiceURL = 'https://www.url.com';
var xmlString = '<xml><parameter1>value1</parameter1>
<parameter2>value2</parameter2></xml>';
function CallService() {
$.ajax({
url: webServiceURL,
type: "POST",
dataType: "xml",
data: xmlString,
processData: false,
contentType: "text/xml; charset=\"utf-8\"",
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert(data.d);
}
function OnError(request, status, error) {
alert('error');
}
$(document).ready(function() {
jQuery.support.cors = true;
});
</script>
</body>
</html>
When I open the HTML I get an alert saying "error" and nothing appears on the other end (the external API's). Is there a way to do this using just JavaScript/Ajax/jQuery or do I need a "supporting" code that receives the JS call?
When you want to make cross domain queries, you have basically 3 types of solution :
1) use JSONP, which won't interest you if you're using XML and not JSON
2) not really do cross-domain, by setting a kind of proxy (or any type of get) on the server serving the main html page
3) changing headers on the server to specify to the browser that you accept cross-domain queries. This is new but yet accepted by all major browsers. That's called CORS. It's easy to change the headers ("Access-control-...") in all server-side languages so that should now be the preferred way (if you have issues (security, rights, bandwidth, ad, etc.) with cross-domain access to the data you serve, you can restrain the allowed origins).