Ajax GET request turning into OPTION request - php

I'm experiencing a weird behavior with an ajax request on a godaddy shared linux server.
The request works perfectly on many other servers I've tested it on, but on this one, the GET request turns into an OPTIONS request for some reason.
Here's the js code (using mootools 1.1):
var a = new Ajax(myurl,{
method: 'get',
onComplete: function( response ){
$('my_div').style.display="none";
output_display( response );
}
});
a.request();
You can see that the method is defined as GET. Yet when I watch the request happen with Firebug, it gets passed as an OPTIONS request. Any thoughts on how or why this would happen?

usually, there are two reasons for this sort of behaviour during XHR (ajax) requests.
protocol bridging (from https to http or vice versa) whereby request url protocol differs to requested url
subdomain difference (eg, domain.com requests from www.domain.com)
bottom line: for XHR to work, protocol and hostnames need to match due to access control restrictions.
reads:
http://www.w3.org/TR/access-control/#cross-origin-request-with-preflight0
ways around cross-domain policy restrictions:
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
etc etc.

Related

How do I get HTML back from a cURL in PHP vs. an actual link?

I am new to cURL.
When I make the following GET in jquery/ajax, I receive HTML in the response that creates a popup login window (oauth2).
When I use the following code in a backend php script to hit the same endpoint, I get back a clickable link...which, when clicked takes you to a login page.
What am I missing?
The PHP
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://oauthserverxxx.com//login/oauth2/auth?client_id=11111&response_type=code&scope=/auth/userinfo&redirect_uri=http://localhost/oauth_complete.php");
$result = curl_exec($curl);
Response from cURL
You are being redirected.bool(true)
1
The AJAX/jquery
$.ajax({
type: "GET",
url: "https://client.instructure.com//login/oauth2/auth?client_id=6666&response_type=code&redirect_uri=http://oauth_complete.php",
// dataType: 'html',
processData: true,
success: function(canvasAuthHTML) {
$('#flexModalHeader').html('Login...');
$('#flexModalMsg').html(canvasAuthHTML);
$('#flexModal').modal('show');
console.log('Called Canvas - response: ' + canvasTok);
},
error: function (data) {
console.log('Fail - could not get LTI auth token...');
chrome.runtime.sendMessage({ msg: "oauthLTI", token: "failed"});
}
});
Response
This will pop the login form inside the modal - the response from the server is detailed HTML.
could be several things,
first off, the jQuery request probably uses an pre-existing cookie session, your curl request doesn't have any cookies.
second, the jQuery request follows "Location" http-header-redirects, your curl code doesn't, but if that is the problem, you can instruct curl to do the same by setting CURLOPT_FOLLOWLOCATION to 1.
third, the jQuery request has an user-agent string, your curl request does not (libcurl has no default user-agent. the curl cli program does, but libcurl, which you use through php's curl_ functions, doesn't.), some websites block requests with no user-agent. if that's the problem, you can simply copy jQuery's user-agent string and tell curl to use it with CURLOPT_USERAGENT
fourth, by default, most browsers use compression where possible, but your curl request doesn't support compression. it's unlikely, but possible, that the server handles curl's request differently because it doesn't support compressed transfers, if that's the problem, you can enable compression in your curl request by setting CURLOPT_ENCODING to emptystring (that will enable all compressions that libcurl was compiled with, which is usually gzip and deflate) - actually, i recommend doing this regardless, because you're fetching HTML, which compresses really well, so unless your cpu is really slow, it will also make the code execute faster. that's the same reason browsers do it by default.
.- the most reliable way to find the culprit, is to record both requests, compare them side by side, and take away every single difference in the 2 requests, 1 by 1, until the requests are identical. sooner or later, you'll find the difference that made the server respond differently (and my best guess here is a location redirect), for that, i recommend the program FiddlerProxy

Google drive api file_get_contents and refferer

I am trying to list files from google drive folder.
If I use jquery I can successfully get my results:
var url = "https://www.googleapis.com/drive/v3/files?q='" + FOLDER_ID + "'+in+parents&key=" + API_KEY;
$.ajax({
url: url,
dataType: "jsonp"
}).done(function(response) {
//I get my results successfully
});
However I would like to get this results with php, but when I run this:
$url = 'https://www.googleapis.com/drive/v3/files?q='.$FOLDER_ID.'+in+parents&key='.$API_KEY;
$content = file_get_contents($url);
$response = json_decode($content, true);
echo json_encode($response);
exit;
I get an error:
file_get_contents(...): failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden
If I run this in browser:
https://www.googleapis.com/drive/v3/files?q={FOLDER_ID}+in+parents&key={API_KEY}
I get:
The request did not specify any referer. Please ensure that the client is sending referer or use the API Console to remove the referer restrictions.
I have set up referrers for my website and localhost in google developers console.
Can someone explain me what is the difference between jquery and php call and why does php call fails?
It's either the headers or the cookies.
When you conduct the request using jQuery, the user agent, IP and extra headers of the user are sent to Google, as well as the user's cookies (which allow the user to stay logged in). When you do it using PHP this data is missing because you, the server, becomes the one who sends the data, not the user, nor the user's browser.
It might be that Google blocks requests with invalid user-agents as a first line of defense, or that you need to be logged in.
Try conducting the same jQuery AJAX request while you're logged out. If it didn't work, you know your problem.
Otherwise, you need to alter the headers. Take a look at this: PHP file_get_contents() and setting request headers. Of course, you'll need to do some trial-and-error to figure out which missing header allows the request to go through.
Regarding the referrer, jQuery works because the referrer header is set as the page you're currently on. When you go to the page directly there's no referrer header. PHP requests made using file_get_contents have no referrer because it doesn't make much sense for them to have any.

Cross Origin $http Requests | Resource

So I was writing an app when I got across this issue.
This is the PHP : Slimframework Corresponding :
$app->delete('/products/:id',function($id) use($app){
$db = new mysqli('notsocoolhost','verycooluser','verycoolpassword','verycooldatabase');
$db->query("DELETE from products WHERE id='$id'");
});
I removed the part where I confirm that you can actually delete it from the database.
This is Angular.JS :
$scope.del = function(product){
$http({
method: "DELETE",
url: baseUrl + product.id
}).success(function(){ ...... //Returns 0 -> WTF?
This buddy here returns in error status : 0
and this one below returns 405:
$scope.delete(baseUrl + product.id).success ... //Returns 405 : Method Not Allowed
To sum it up, I added couple of tests on Hurl.it and the RESTApi from Slimframework is fully functioning. which leaves it as Angular.js problem ? I guess?
UPDATE:
After further inspection I've revealed the following:
1) Mysteriously the : Request Method (Field by Firefox) is OPTIONS.
2) Access-Control-Request-Method : "DELETE"
3) Access-Control-Allow-Methods: "GET,POST,DELETE,PUT"
I hope this serves people in the future.
Back to basics, having trouble sending $http requests in cross-origin requests has nothing to do with the server nor Angular.js.
If you are like me hosting your webapp on:
https:\\www.beautifuldomain.com
and your API on :
https:\\api.beautifuldomain.com
Whenever you try to perform a request between Webapp and API you are performing Cross-Origin Request.
What does it mean?
It means that your message will be considered as Cross-Origin and it will be preflighted.
Preflighted?
It means that when you use any method other than GET,HEAD or POST.
Also POST if used to send request data with Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g.
It will be sent as method: OPTIONS. -- That is preflighted.
OK, OK I understand, but what do i do?
Now that is clear we have two options to move on:
First Option:
Leaving the web-server structure as is i.e:
www.example.com -> Angular Web-App
api.example.com -> API - subdomain
FOR POST:
And add a transformRequest setting to $httpProvider like so:
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
(Remember preflighted, well it does allow us to send x-www-form-urlencoded.)
What is left from there is make sure you set your data in x-www-form-urlencoded format looks like so :
name=Andy&nickname=RainbowWarrior&....
FOR DELETE:
This one is a bit more complicated since you have to do some server side tweak.
If you are using Slimframework for PHP like I do, all you got to do is:
$response = $app->response();
$response->header('Access-Control-Allow-Origin', '*');
$app->options('/path/to/resource',function(){}); // This one just so you can accept OPTIONS it does nothing.
$app->delete('/path/to/resource',function()
{//your delete code is here
});
Now whenever you try to perform DELETE from angular you will see on XHR tab in w/e browser you are using that There is OPTIONS request that was made and right after DELETE.
Second Option:
Much less of a headache .
Move your API into the same domain i.e
www.example.com - Webapp
www.example.com/api - API
And you are protected from all of that above.
This took me 7 hours of research I hope it will help you guys and save you time!.

jquery fileupload cross domain

I have a small problem i need to create a fileuploader to a remote server using jquery Blueimp Fileupload, if i work locally for testing it is working perfectly now when I tested it on live, Im having a problem with cross origin resource sharing.
Now, how can I retrieve the json response from another domain without using jsonp because I tried jsonp and it does not work with the fileuploader so now I want to do it using json alone and get the response that i need if thats possible
I also tried putting callback=? at the end of url .. also did not work
Or if its possible how can I integrate jsonp with this fileuploader
$( '#fileuploader' ).fileupload( {
sequentialUploads: true,
url: 'http://www.domain.com/test/upload?callback=?',
dropZone: $( '#fileuploader' )
} );
Server Side this is on another domain
echo json_encode( array( 'test' => 'value1') );
Also: i am not allowed to use ftp / curl for this.. thanks
you can allow CORS request at server as:
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
When CORS is enabled at server, Ajax first send OPTIONS request to detect whether server allow CORS request or not. if enabled, it send actual request.
If you have allowed the CORS policy on the remote server as suggest above and you still get the Cross Origin error it could be that there is something else not working in your code. Many times Firebug or similar tools show a Cross Origin error and in reality it was a 404 or something else. First question to answer is if you actually at a CORS pre-flight request/response. That's your permission ticket. Check out these posts here here and here
You might consider using the iframe transport option. This will let you keep away from issues with browser that doesn't support cross-domain file uploads, like our old (but still widely used) friend IE 9 or previous versions.
Hope this helps.

Cross-domain AJAX request error on HTTP 200

I'm writing a very basic Facebook app, but I'm encountering an issue with cross-domain AJAX requests (using jQuery).
I've written a proxy page to make requests to the graph via cURL that I'm calling via AJAX. I can visit the page in the browser and see it has the correct output, but requesting the page via always causes jQuery to fire the error handler callback.
So I have two files:
Proxy, which does the cURL request
<?php
//Do some cURL requests, manipulate some data
//return it as JSON
print json_encode($data);
?>
The facebook canvas, which contains this AJAX call
$.getJSON("http://myDomain.com/proxy.php?get=stuff",
function(JSON)
{
alert("success");
})
.error(function(err)
{
alert("err");
});
Inspecting the call with Firebug shows it returns with HTTP code 200 OK, but the error handler is always fired, and no content is returned. This happens whether I set Content-Type: application/json or not.
I have written JSON-returning APIs in PHP before using AJAX and never had this trouble.
What could be causing the request to always trigger the error handler?
Recently I experienced the same issue and my problem was the fact that there was a domain difference between the webpage and the API, due to the SSL.
The web page got a HTTP address (http://myDomain.com) and the content I was requesting with JQuery was on the same domain but HTTPS protocol (https://myDomain.com). The browser (Chrome in this case) considered that the domains were differents (the first one with HTTP, the second one with HTTPS), just because of the protocol, and because the request response type was "application/json", the browser did not allowed it.
Basically, the request worked fine, but your browser did not allowed the response content.
I had to add a "Access-Control-Allow-Origin" header to make it work. If you're in the same case, have a look there: https://developer.mozilla.org/en/http_access_control.
I hope that'll help you, I got a headache myself.

Categories