Cross-domain AJAX request error on HTTP 200 - php

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.

Related

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.

php http post response for web hook

I'm trying to create a web hook notification. The documentation of the service i want to use requires that i specify a URL where POST requests can be performed. This URL will receive the following object, in json format, and must respond with a Status Code between 200-299.
{
"type": "ping"
}
I don't know how to proceed making my server on localhost respond with a 200 status code. http_response_code(200) works well on live server but nothing seem to be happening on localhost.
Is there any way i can make it work with localhost?
I've included the link to the documentation here (i hope it's not against the rule).
I am thinking that you wouldn't have to send them the response. The webhook would know about the response. If it reached your URL successfully, it would be a 200 OK right off the bat. If the API is requesting a response back then I imagine that you would have to call it back somehow. Is this a well-known API? Any documentation?
The response code is in the response header, not in the content.
PHP defaults to a response code of 200, so if you don't mess with it at all, you should be good.
If you want to set a different response code (202 for example), just call:
http_response_code(202);
Or set the full header yourself:
header('HTTP/1.1 202 Accepted');
Proper way to explicitly set 200 (or any other) status code with http_response_code function is just as following (don't echo or json_encode it):
http_response_code(200);
It should force webserver to use 200 status code in it's response. However, webserver could possibly ignore it. To check what response code your webserver sends, use telnet or any REST tool like Postman

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.

Ajax GET request turning into OPTION request

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.

AJAX, Subdomains and the 200 OK response

A non-hypothetical but abstracted situation:
I have a domain www.foo.com, from which I'm making an AJAX POST to beta.foo.com. Examining the XHR object, I see a response header of 200 OK, but no response text - I even get a response 12B long, which is the exact response (a 12-character string) that I'm expecting - but the response text is blank.
If this is a cross-domain issue, why am I getting 200 OK, and better yet - why am I seeing the PHP functions fire on the beta.foo.com side - yet getting no response?
You can't do cross subdomains ajax calls that easy. There is something called Same origin policy that prevents you from doing that. If you want sort this issue you need to use JSONP or Iframes.
Install firebug and you will see an http 200 code and an error: that error is SOP acting.
You mentioned that you're checking the responseText property. Is it possible your response is in XML format?
If you send an XML request, or the response type is 'text/xml', you will get a value for responseXML. I believe that the responseText property can be blank if it's in XML format.
Random example from google:
http://javascript.about.com/library/blajax08.htm

Categories