I am trying to write a Single Page App (SPA) based on AngularJS. The app should connect to a webserver that provides a RestFul services, but each end point requires username and password along with other parameters. Since I am a beginner in this area, before moving towards the actual development, I tried PostMan/Advanced Rest Client chrome extensions to verify the basic connections. A sample request preview :
POST /servicesNS/admin/search/search/jobs/export HTTP/1.1
Host: localhost:8089
Cache-Control: no-cache
Content-Type: application/x-www-form-urlencoded
search=search+error+|+table+host&output_data=xml&username=admin&password=unity3d
This is actually equivalent to the cURL command:
curl -k -u admin:unity3d --data-urlencode search="search error | table host" -d "output_mode=xml" https://localhost:8089/servicesNS/admin/search/search/jobs/result
After getting successful results in above mentioned ways, I am now looking for equivalent way of doing it in AngularJS.
var app = angular.module('TabsApp', []);
app.controller('TabsCtrl', function ($scope, $http)
{
login = function () {
$scope.userName ="admin";
$scope.password ="unity3d"
$http({
method :"POST",
url:"https://localhost:8089/servicesNS/admin/search/search/jobs/export",
data: { "username" : "admin" , "password": "unity3d", "search" : "search error"},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config) {
console.log('status',status);
console.log('data',status);
console.log('headers',status);
});
}
});
This gives me error 401 Unauthorized, the headers of the response:
> Remote Address:127.0.0.1:8089 Request
> URL:https://localhost:8089/servicesNS/admin/search/search/jobs/export
> Request Method:POST Status Code:401 Unauthorized Request Headersview
> source Accept:application/json, text/plain, */* Accept-Encoding:gzip,
> deflate Accept-Language:en-US,en;q=0.8 Connection:keep-alive
> Content-Length:65 Content-Type:application/x-www-form-urlencoded
> Host:localhost:8089 Origin:http://localhost:63342
> Referer:http://localhost:63342/UI/UI1.html User-Agent:Mozilla/5.0
> (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
> Chrome/39.0.2171.71 Safari/537.36 Form Dataview sourceview URL encoded
> {"username":"admin","password":"unity3d","search":"search error"}:
> Response Headersview source Access-Control-Allow-Credentials:true
> Access-Control-Allow-Headers:Authorization
> Access-Control-Allow-Methods:GET,POST,PUT,DELETE,HEAD,OPTIONS
> Access-Control-Allow-Origin:* Cache-Control:private
> Connection:Keep-Alive Content-Length:130 Content-Type:text/xml;
> charset=UTF-8 Date:Sat, 29 Nov 2014 19:53:59 GMT Server:Splunkd
> Vary:Cookie, Authorization WWW-Authenticate:Basic realm="/splunk"
> X-Content-Type-Options:nosniff X-Frame-Options:SAMEORIGIN
And the output is :
<?xml version="1.0" encoding="UTF-8"?> <response> <messages>
<msg type="ERROR">Unauthorized</msg> </messages> </response>
Any idea what is going wrong?
If you are sending response in the format of 'application/x-www-form-urlencoded' the actual data format should be the same.
What you are sending currently is a JSON object. You would need to use $http tranformer to tranform the request: Something in line of
transformRequest: function (data) {
var postData = [];
for (var prop in data)
postData.push(encodeURIComponent(prop) + "=" + encodeURIComponent(data[prop]));
return postData.join("&");
},
See a working fiddle here http://jsfiddle.net/cmyworld/doLhmgL6/
Related
I am trying to upload a file to the server , I do that successfully but after success, angular or browser or I don't know how just redirect me back to my initial state in angular js
the success callback hit and I have no error
ng-fileupload version 3.2.5.
here is my function in the controller :
$scope.uploadIssueAttachment = function (files, issue) {
if (files && files.length) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
$upload.upload({
url: '/Handlers/UploadHandler.ashx?des=HelpDesk'
, method: 'POST'
, file: file
, }).progress(function (evt) {}).then(function (data) {
var _fileName = data.headers('fileName');
var _originalFileName = data.headers('orgName');
var _type = data.headers('format');
$scope.newIssueAttachments.push({
fileName: _originalFileName
, temporaryName: _fileName
, fileType: _type
});
}).catch(function (error) {
console.log(error);
});
}
}
};
and here is my html markup
<span ng-file-select ng-file-change="uploadIssueAttachment($files,newIssue)" class="file-input btn btn-sm btn-file" >
the function hit and I upload a file, browser response with 200 status
Request URL:http://localhost:3080/Handlers/UploadHandler.ashx?des=HelpDesk
Request Method:POST
Status Code:200 OK
Remote Address:[::1]:3080
Referrer Policy:no-referrer-when-downgrade
Response Headers
view source
Cache-Control:private
Content-Length:0
Date:Mon, 17 Jul 2017 10:33:56 GMT
fileName:ea8c8799-0f48-49f4-a33c-dca0726af929.png
format:image/png
name:ea8c8799-0f48-49f4-a33c-dca0726af929.png
orgname:avator.png
Server:Microsoft-IIS/10.0
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET
X-SourceFiles:=?UTF-8?B?RDpcU291cmNlXFdvcmtzcGFjZXNcUE1PLkFDQVxEZXZcQk1TXFJheWthbS5Ccm9rZXJzLldlYi5NVkNcSGFuZGxlcnNcVXBsb2FkSGFuZGxlci5hc2h4?=
Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:16544
Content-Type:multipart/form-data; boundary=----WebKitFormBoundarylgAXmkMLtLGhRRU4
Cookie:ASP.NET_SessionId=ska22gomunzfvxqv1wwihbmh; .ASPXAUTH=A8E3E65AECDBB20189E01D261B3580E6997A7763615AD085A0E92F5F44B2D7DFA2C0E39BA47876EAE614EF06C56E692B71982D9035F84075C466E63632653E3E7CC03F042B850200EFBC2867E8A0F7EA3F8A7989AAB68E267891CB819AB9024D04DB430D6B8D8E692D64652CA2645681
Host:localhost:3080
Origin:http://localhost:3080
Referer:http://localhost:3080/admin/
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36
Query String Parameters
view source
view URL encoded
des:HelpDesk
Request Payload
------WebKitFormBoundarylgAXmkMLtLGhRRU4
Content-Disposition: form-data; name="file"; filename="avator.png"
Content-Type: image/png
------WebKitFormBoundarylgAXmkMLtLGhRRU4--
and then with no error I just get redirected to my start page, I don't know how to track the event that changed state.
the interesting thing are when I heat breakpoint in dev console and I wait just for few minute, then there is no state change and everything goes well.
near to pull my hair.
any suggestion?
You havent wrote which version you are using but I think this structure will help you .Its always good to use then...catch in angular success is now deprecated.
You can see it here
upload Structure(with then...catch)
$upload.upload({
url: '<YOUR URL>'
file: <file>
}).progress(function (evt) {
// progress = parseFloat(evt.loaded / evt.total)*100;
}).then(function(result) {
//handle successful result
}).catch(function(errorCallback){
//you can see error here
});
Let me know if it wont work.
Edited
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams) {
console.log(toState); //put break point over here try to debug
console.log(fromState);
});
I am trying to make an Ajax call to hit a webservice and get the response.But getting uncaught syntaxerror:unexpected token < in google chrome console.
Here's my Ajax Request:
$(document).ready(function(){
$.ajax({
url:"http://10.10.1.5:8089/axis2/services/cmtlpmservice/getAllMonitors",
dataType:"jsonp",
jsonpCallback:"callback",
type:"GET",
success:function(response){
console.log(response);
}
});
});
The Request header is as follows:
Request URL:http://10.10.1.5:8089/axis2/services/cmtlpmservice /getAllMonitors?callback=callback&_=1487912464838
Request Method:GET
Status Code:200 OK
Remote Address:10.10.1.5:8089
Accept:/
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8
Authorization:Basic YWRtaW46
Cache-Control:max-age=0
Connection:keep-alive
Host:10.10.1.5:8089
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
The Response Header as follows:
Cache-Control:no-cache
Content-Type:application/xml;charset=UTF-8
Date:Fri, 24 Feb 2017 05:01:05 GMT
Expires:Thu, 01 Jan 1970 10:00:00 EST
Pragma:No-cache
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
X-Powered-By:Servlet 2.5; JBoss-5.0/JBossWeb-2.1
The Response looks like :
<ns:getAllMonitorsResponse xmlns:ns="ws.core.dorado.com">
<ns:return>
{
"monitors": [{
"id": "com.dorado.broadscope.monitor.Monitor::RGNEXGvol54w2a#_1.3.6.1.4.1.20138.800.20.12.1.9.1",
"maxAttrName": "ifTemperatureValue Max",
"name": "ifTemperatureValue",
"minAttrName": "ifTemperatureValue Min",
"maxAttrId": "com.dorado.broadscope.monitor.Monitor::RGNEXGvol54w2a#_1.3.6.1.4.1.20138.800.20.12.1.9.1Max",
"minAttrId": "com.dorado.broadscope.monitor.Monitor::RGNEXGvol54w2a#_1.3.6.1.4.1.20138.800.20.12.1.9.1Min"
}]
}
</ns:return>
</ns:getAllMonitorsResponse>
Due to some error in getAllMonitors it returns whole html page instade of json deta in response. your controller is culpit insted of your ajax.
I have checked the other questions - this is not a duplicate.
I have tried all of the solutions I could find and implement.
I am trying to send data from task.php → showCats.php
task.php:
<script type="text/javascript">
$(document).on("click", ".btnCat", function () {
var filter = $(this).data("id");
alert(filter);
$.ajax({
type: 'POST',
url: 'showCats.php',
data: {'filter': filter},
});
$('div.container-fluid').load('showCats.php');
});
</script>
showCats.php:
$area = $_POST['filter'];
$sql = "select AID,name,surname,street_name,house_number, area, plz,poster,visible from addresses WHERE area LIKE '$area' AND visible LIKE 'show' ORDER BY AID DESC";
$rs = mysqli_query($con,$sql);
$str = '';
while ($res = mysqli_fetch_array($rs)) {
$str .= '
<div class="col-md-9">
<div class="task col-md-12 well" id='.$res['AID'].'>
<div>
<button class="btn btn-danger btn-xs btnDelete" id='.$res["poster"].' onclick="refresh()" data-id="'.$res['AID'].'">x</button>
</div>
<div>
<span>'. $res["name"].'</span>
<span>'. $res["surname"].'</span><br>
<span>'. $res["street_name"].'</span>
<span>'. $res["house_number"].'</span><br>
<span>'. $res["plz"].'</span>
<span>'. $res["area"].'</span>
</div>
</div>
</div>';
}
echo $str;
?>
var_dump($_POST); returns NULL, even though I can see the post value under Developer Tools in Chrome.
My GET:
Request URL:https://example.com/showCats.php
Request Method:GET
Status Code:200 OK
Remote Address:xxx:443
Response Headers
view source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Fri, 15 Jul 2016 18:43:56 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx/1.6.2
Strict-Transport-Security:max-age=31536000
Transfer-Encoding:chunked
Request Headers
view source
Accept:text/html, */*; q=0.01
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:en-US,en;q=0.8,de;q=0.6
Connection:keep-alive
Cookie:PHPSESSID=vudgbb33574tfod2vu48hst830
Host:example.com
Referer:https://example.com/tasks.php
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
X-Requested-With:XMLHttpRequest
My POST:
Request URL:https://example.com/showCats.php
Request Method:POST
Status Code:200 OK
Remote Address:xxx:443
Response Headers
view source
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Content-Encoding:gzip
Content-Type:text/html; charset=UTF-8
Date:Fri, 15 Jul 2016 18:43:56 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:nginx/1.6.2
Strict-Transport-Security:max-age=31536000
Transfer-Encoding:chunked
Request Headers
view source
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.8,de;q=0.6
Connection:keep-alive
Content-Length:12
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:PHPSESSID=vudgbb33574tfod2vu48hst830
Host:example.com
Origin:https://example.com
Referer:https://example.com/tasks.php
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
X-Requested-With:XMLHttpRequest
Form Data
view source
view URL encoded
filter:Turgi
You are trying to send data from task.php -> showCats.php ! your code does that very well by using this:
$.ajax({
type: 'POST',
url: 'showCats.php',
data: {'filter': filter},
});
The problem is when you do this : $('div.container-fluid').load('showCats.php'); a GET request will be sent to the server! so It's normal to find that var_dump($_POST) return NULL.
If you want to show/get the response you can use the success event like this:
$.ajax({
type: 'POST',
url: 'showCats.php',
data: {'filter': filter},
//A function to be called if the request succeeds.
success: function(data) {
$('div.container-fluid').html(data)
},
//A function to be called if the request fails
error: function(xhr, status, error) {
alert('An error occurred:'+error);
}
});
setting a datatype parameter tells what kind of data you are sending.
type: "POST",
dataType: 'json',
I would concur with those comments above. Loading the program a second time does not report the values of the database call. Further, wouldn't AJAX normally return values to the calling program with an echo of json_encode, instead of just echoing the variable to a run of the PHP page that does not get viewed?
I have a machine on my local lan (machineA) that has two web servers. The first is the in-built one in XBMC (on port 8080) and displays our library. The second server is a CherryPy python script (port 8081) that I am using to trigger a file conversion on demand. The file conversion is triggered by a AJAX POST request from the page served from the XBMC server.
Goto http://machineA:8080 which displays library
Library is displayed
User clicks on 'convert' link which issues the following command -
jQuery Ajax Request
$.post('http://machineA:8081', {file_url: 'asfd'}, function(d){console.log(d)})
The browser issues a HTTP OPTIONS request with the following headers;
Request Header - OPTIONS
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://machineA:8080
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
The server responds with the following;
Response Header - OPTIONS (STATUS = 200 OK)
Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:40:29 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1
The conversation then stops. The browser, should in theory, issue a POST request as the server responded with the correct (?) CORS headers (Access-Control-Allow-Origin: *)
For troubleshooting, I have also issued the same $.post command from http://jquery.com. This is where I am stumped, from jquery.com, the post request works, a OPTIONS request is sent following by a POST. The headers from this transaction are below;
Request Header - OPTIONS
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://jquery.com
Access-Control-Request-Method: POST
Response Header - OPTIONS (STATUS = 200 OK)
Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:37:59 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1
Request Header - POST
Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://jquery.com/
Content-Length: 12
Origin: http://jquery.com
Pragma: no-cache
Cache-Control: no-cache
Response Header - POST (STATUS = 200 OK)
Content-Length: 32
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:37:59 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: application/json
I can't work out why the same request would work from one site, but not the other. I am hoping someone might be able to point out what I am missing. Thanks for your help!
I finally stumbled upon this link "A CORS POST request works from plain javascript, but why not with jQuery?" that notes that jQuery 1.5.1 adds the
Access-Control-Request-Headers: x-requested-with
header to all CORS requests. jQuery 1.5.2 does not do this. Also, according to the same question, setting a server response header of
Access-Control-Allow-Headers: *
does not allow the response to continue. You need to ensure the response header specifically includes the required headers. ie:
Access-Control-Allow-Headers: x-requested-with
REQUEST:
$.ajax({
url: "http://localhost:8079/students/add/",
type: "POST",
crossDomain: true,
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
var resp = JSON.parse(response)
alert(resp.status);
},
error: function (xhr, status) {
alert("error");
}
});
RESPONSE:
response = HttpResponse(json.dumps('{"status" : "success"}'))
response.__setitem__("Content-type", "application/json")
response.__setitem__("Access-Control-Allow-Origin", "*")
return response
I solved my own problem when using google distance matrix API by setting my request header with Jquery ajax. take a look below.
var settings = {
'cache': false,
'dataType': "jsonp",
"async": true,
"crossDomain": true,
"url": "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=place_id:"+me.originPlaceId+"&destinations=place_id:"+me.destinationPlaceId+"®ion=ng&units=metric&key=mykey",
"method": "GET",
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
}
$.ajax(settings).done(function (response) {
console.log(response);
});
Note what i added at the settings
**
"headers": {
"accept": "application/json",
"Access-Control-Allow-Origin":"*"
}
**
I hope this helps.
Took me some time to find the solution.
In case your server response correctly and the request is the problem, you should add withCredentials: true to the xhrFields in the request:
$.ajax({
url: url,
type: method,
// This is the important part
xhrFields: {
withCredentials: true
},
// This is the important part
data: data,
success: function (response) {
// handle the response
},
error: function (xhr, status) {
// handle errors
}
});
Note: jQuery >= 1.5.1 is required
Well I struggled with this issue for a couple of weeks.
The easiest, most compliant and non hacky way to do this is to probably use a provider JavaScript API which does not make browser based calls and can handle Cross Origin requests.
E.g. Facebook JavaScript API and Google JS API.
In case your API provider is not current and does not support Cross Origin Resource Origin '*' header in its response and does not have a JS api (Yes I am talking about you Yahoo ),you are struck with one of three options-
Using jsonp in your requests which adds a callback function to your URL where you can handle your response.
Caveat this will change the request URL so your API server must be equipped to handle the ?callback= at the end of the URL.
Send the request to your API server which is controller by you and is either in the same domain as the client or has Cross Origin Resource Sharing enabled from where you can proxy the request to the 3rd party API server.
Probably most useful in cases where you are making OAuth requests and need to handle user interaction Haha! window.open('url',"newwindowname",'_blank', 'toolbar=0,location=0,menubar=0')
This is a summary of what worked for me:
Define a new function (wrapped $.ajax to simplify):
jQuery.postCORS = function(url, data, func) {
if(func == undefined) func = function(){};
return $.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
xhrFields: { withCredentials: true },
success: function(res) { func(res) },
error: function() {
func({})
}
});
}
Usage:
$.postCORS("https://example.com/service.json",{ x : 1 },function(obj){
if(obj.ok) {
...
}
});
Also works with .done,.fail,etc:
$.postCORS("https://example.com/service.json",{ x : 1 }).done(function(obj){
if(obj.ok) {
...
}
}).fail(function(){
alert("Error!");
});
Server side (in this case where example.com is hosted), set these headers (added some sample code in PHP):
header('Access-Control-Allow-Origin: https://not-example.com');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 604800');
header("Content-type: application/json");
$array = array("ok" => $_POST["x"]);
echo json_encode($array);
This is the only way I know to truly POST cross-domain from JS.
JSONP converts the POST into GET which may display sensitive information at server logs.
Using this in combination with Laravel solved my problem. Just add this header to your jquery request Access-Control-Request-Headers: x-requested-with and make sure that your server side response has this header set Access-Control-Allow-Headers: *.
I had the exact same issue where jquery ajax only gave me cors issues on post requests where get requests worked fine - I tired everything above with no results. I had the correct headers in my server etc. Changing over to use XMLHTTPRequest instead of jquery fixed my issue immediately. No matter which version of jquery I used it didn't fix it. Fetch also works without issues if you don't need backward browser compatibility.
var xhr = new XMLHttpRequest()
xhr.open('POST', 'https://mywebsite.com', true)
xhr.withCredentials = true
xhr.onreadystatechange = function() {
if (xhr.readyState === 2) {// do something}
}
xhr.setRequestHeader('Content-Type', 'application/json')
xhr.send(json)
Hopefully this helps anyone else with the same issues.
This function will asynchronously get an HTTP status reply from a CORS-enabled page. Only a page with the proper headers returns a 200 status if accessed via XMLHttpRequest -- whether GET or POST is used. Nothing can be done on the client side to get around this except possibly using JSONP if you just need a json object.
The following can be modified to get the data held in the xmlHttpRequestObject object:
function checkCorsSource(source) {
var xmlHttpRequestObject;
if (window.XMLHttpRequest) {
xmlHttpRequestObject = new XMLHttpRequest();
if (xmlHttpRequestObject != null) {
var sUrl = "";
if (source == "google") {
var sUrl = "https://www.google.com";
} else {
var sUrl = "https://httpbin.org/get";
}
document.getElementById("txt1").innerHTML = "Request Sent...";
xmlHttpRequestObject.open("GET", sUrl, true);
xmlHttpRequestObject.onreadystatechange = function() {
if (xmlHttpRequestObject.readyState == 4 && xmlHttpRequestObject.status == 200) {
document.getElementById("txt1").innerHTML = "200 Response received!";
} else {
document.getElementById("txt1").innerHTML = "200 Response failed!";
}
}
xmlHttpRequestObject.send();
} else {
window.alert("Error creating XmlHttpRequest object. Client is not CORS enabled");
}
}
}
<html>
<head>
<title>Check if page is cors</title>
</head>
<body>
<p>A CORS-enabled source has one of the following HTTP headers:</p>
<ul>
<li>Access-Control-Allow-Headers: *</li>
<li>Access-Control-Allow-Headers: x-requested-with</li>
</ul>
<p>Click a button to see if the page allows CORS</p>
<form name="form1" action="" method="get">
<input type="button" name="btn1" value="Check Google Page" onClick="checkCorsSource('google')">
<input type="button" name="btn1" value="Check Cors Page" onClick="checkCorsSource('cors')">
</form>
<p id="txt1" />
</body>
</html>
If for some reasons while trying to add headers or set control policy you're still getting nowhere you may consider using apache ProxyPass…
For example in one <VirtualHost> that uses SSL add the two following directives:
SSLProxyEngine On
ProxyPass /oauth https://remote.tld/oauth
Make sure the following apache modules are loaded (load them using a2enmod):
proxy
proxy_connect
proxy_http
Obviously you'll have to change your AJAX requests url in order to use the apache proxy…
This is a little late to the party, but I have been struggling with this for a couple of days. It is possible and none of the answers I found here have worked. It's deceptively simple.
Here's the .ajax call:
<!DOCTYPE HTML>
<html>
<head>
<body>
<title>Javascript Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).domain = 'XXX.com';
$(document).ready(function () {
$.ajax({
xhrFields: {cors: false},
type: "GET",
url: "http://XXXX.com/test.php?email='steve#XXX.com'",
success: function (data) {
alert(data);
},
error: function (x, y, z) {
alert(x.responseText + " :EEE: " + x.status);
}
});
});
</script>
</body>
</html>
Here's the php on the server side:
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
header('Origin: xxx.com');
header('Access-Control-Allow-Origin:*');
$servername = "sqlxxx";
$username = "xxxx";
$password = "sss";
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die( "Connection failed: " . $conn->connect_error);
}
$sql = "SELECT email, status, userdata FROM msi.usersLive";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["email"] . ":" . $row["status"] . ":" . $row["userdata"] . "<br>";
}
} else {
echo "{ }";
}
$conn->close();
?>
</body>
I am getting a JSON parseerror even though the return from the server was successful. Here is my save code where fail() is always being run
#model.save()
.fail(=> #resetForm() )
.always (obj, error) ->
console.log obj
console.log obj.responseText
console.log JSON.parse(obj.responseText)
Here is my error object:
"parsererror"
"No conversion from text to http://api2.local/users/auth"
Some notes:
I am on Jquery 1.8.3 and Backbone 0.9.9
The server responds correctly with json - here is my response header
Access-Control-Allow-Headers:origin, x-requested-with, content-type, accept
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin:*
Access-Control-Max-Age:86400
Connection:Keep-Alive
Content-Length:202
Content-Type:application/json; charset=utf-8
Date:Fri, 21 Dec 2012 18:46:25 GMT
Keep-Alive:timeout=5, max=100
Server: xxx
X-Powered-By:PHP/5.3.1
console.log JSON.parse(obj.responseText) correctly gives me a JSON object
EDIT: Request Headers
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:54
Content-Type:application/json
Host:api2.local
Origin:http://localhost:3000
Pragma:no-cache
Referer:http://localhost:3000/login
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.101 Safari/537.11
X-Requested-With:XMLHttpRequest
EDIT: Request Payload via POST
{"email":"x#x.com","password":"xxx"}
EDIT: Response Payload
{
"user_id":"xx",
"first_name":"xxx",
"last_name":"xxx",
"email":"x#x.com",
"role":"xxxx",
"date_joined":"xxx"
}
Ahhhh - Programming can be so irritating sometimes. Finally figured this out - thanks for everyones help but it was a simple coffeescript compiling issue
So before I had
$.ajaxPrefilter ( (options, originalOptions, jqXHR) ->
options.url = "#{ API_URL }" + options.url
)
which compile to return both options.url and $.ajaxPrefilter. For whatever reason, Jquery was picking up the options.url as a DataTypes argument on the ajaxPrefilter function. The solution was to return false:
$.ajaxPrefilter \
(options, originalOptions, jqXHR) ->
options.url = "#{ API_URL }" + options.url
no
which gives the correct compiled version
return $.ajaxPrefilter(function(options, originalOptions, jqXHR) {
options.url = ("" + API_URL) + options.url;
return false;
});