API call using ajax not working - javascript

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

Related

CORS Error:Response to preflight request doesn't pass access control check when trying to access Azure Search Api

I am using an ajax put request to perform a merge operation to update a field named DocType for a particular document in azure search index. But getting the error: Failed to load resource: the server responded with a status of 404 (Not Found)
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
The ajax request I am performing:
var jsonMeta = {
"value": [
{
"#search.action": "merge",
"metadata_storage_path": "*******jkio********",
"DocType": "Test_Merge"
}
]
};
var jsonString = JSON.stringify(jsonMeta);
var url = "https://documentsmartdetect.search.windows.net/indexes/document-smartdetect-index/docs/index?api-version=2017-11-11";
$.ajax({
url: url,
method: 'PUT',
data: JSON.stringify(jsonMeta),
// This is the important part
xhrFields: {
withCredentials: true
},
crossDomain: true,
contentType: 'application/json',
headers: {
"api-key": "***************89**",
},
success: function (response) {
},
error: function (xhr, status) {
alert('error');
}
});
I have also tried using Allowed origin type : all on the azure portal. Need some assistance to fix the CORS issue.
Azure Search does not allow calls from front-end JavaScript, so you cannot do what you want directly.
You will have to call Azure Search from a back-end.
This is actually a serious security problem as well since your Search key is now public within the JavaScript that is sent to all visitors of your web app.

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 use transactional Cypher HTTP endpoint and new REST API Authentication and Authorization in Neo4j 2.2.x with JQuery

I'm looking for a code example creating a REST POST request with JQuery on Neo4j 2.2.x Transactional Cypher HTTP endpoint with new REST API Authentication and Authorization parameters.
Before Neo4j 2.2 version I used the Legacy Cypher HTTP endpoint (which is deprecated) to execute Cypher queries with the following code:
$.post("http://localhost:7474/db/data/transaction/commit",
{
"query": query,
"params": {}
}, "json")...
But I would like to move to 2.2 and use the transactional endpoint with user authentication parameters.
I can't find the right headers and parameters combination to use to create such a request. That's why I'm looking for a code example.
Best would be an example using a cross domain request but an example on same domain would be helpful too.
For authentication you need to supply an additional HTTP header to your request:
Authorization: Basic realm="Neo4j" <base64>
where <base64> is the base64 encoded string of username:password.
Not being a jquery ninja, but I guess the most simple way is to set the authorization header using ajax defaults:
$.ajaxSetup({
headers: { "Authorization": 'Basic realm="Neo4j' <base64>'}
});
When this default has been applied your $.post above should work.
The issue has been fixed in 2.2.0-RC01 and I can use transactional Cypher HTTP endpoint with authentication using the following example code:
$.ajaxSetup({
headers: {
// Add authorization header in all ajax requests
// bmVvNGo6cGFzc3dvcmQ= is "password" base64 encoded
"Authorization": "Basic bmVvNGo6cGFzc3dvcmQ="
}
});
$.ajax({
type: "POST",
url: "http://localhost:7474/db/data/transaction/commit ",
dataType: "json",
contentType: "application/json;charset=UTF-8",
data: JSON.stringify({"statements": [{"statement": "MATCH (n) RETURN n LIMIT 10"}]}),
success: function (data, textStatus, jqXHR) {
// use result data...
},
error: function (jqXHR, textStatus, errorThrown) {
// handle errors
}
});
Authorization means that the browser will send a preflight OPTIONS request which does not embed authorization headers.
This is most known as CORS.
Currently the Neo4j server do not reply to the OPTIONS request with the appropriate Access-Control-Allow-Headers.
This feature has been implemented in the source code and will be shipped with the GA release which I hope will come out this week.

Creating an API in yii for cross domain communication

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

IOS Webpage - Not Allowed by Access Control Allow Orgin

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: *');

Categories

Resources