jquery fileupload cross domain - php

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.

Related

Angular $http executed twice when using headers

I'm developing an ionic project and I'm using header parameters in each POST and GET Request. How ever When I test the project on Android Phone and monitor all requests that come into my server through my android device there are no issues. But when I deploying my ionic project and testing it in my web browser ( Chrome Web Browser ) I see that each request has been executed twice,( one without headers params and without inputs when I use POST method, and the second one is with all params ).
I've solved it in my server if there are no header parameters to ignore the request each time. How can I prevent the duplicated execution for the $http (POST and GET)?
These parameters I've set in the angular.config js file.
$httpProvider.defaults.headers.common['Accept'] = 'application/json; q=0.01';
$httpProvider.defaults.headers.common['Authorization-Token'] = value;
and my PHP service starts with
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization-Token");
header('Access-Control-Max-Age: 60');
header('Access-Control-Allow-Methods: ["GET","POST"]');
header("Content-Type: application/json; charset=UTF-8");
Sounds like an OPTION call indeed.
It should be done, and not carry any payload, it is just to check with the server what actions are allowed on the resource before performing the actual call (post/get/whatever).
Check the answer to this similar question : Angular 2 HTTP POST does an OPTIONS call
The first request is the preflight.
This is part of the browser mechanism.
You cannot avoid it.
It all comes down to how browsers manage CORS. When making a cross-domain request in JavaScript that is not "simple" (i.e. a GET request), the browser will automatically make a HTTP OPTIONS request to the specified URL/URI, called a "pre-flight" request or "promise". As long as the remote source returns a HTTP status code of 200 and relevant details about what it will accept in the response headers, then the browser will go ahead with the original JavaScript call
Please look here and here

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!.

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.

How to get json data coming from another domain?

I want to use the google images api. In the past when I worked with json I simply used the ajax function to get the json from my own server. But now I will be getting it from an external domain:
https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy monkey&v=1.0
Obviously I can't load this using js since its not from an internal url. So in these cases how does one work with json data. Are you supposed to load it via CURL using a server side script or is there another way?
You can make use of JSONP by adding a callback GET param.
https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=hello
Then you can request it with jQuery's $.getJSON().
$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=?', function(response) {
console.log(response.responseData);
});
jsFiddle.
You must use Cross Origin Resource Sharing (CORS http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing)
It's not as complicated as it sounds...simply set your request headers appropriately...in Python it would look like:
self.response.headers.add_header('Access-Control-Allow-Origin', '*');
self.response.headers.add_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
self.response.headers.add_header('Access-Control-Allow-Headers', 'X-Requested-With');
self.response.headers.add_header('Access-Control-Max-Age', '86400');

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.

Categories