Getting Phonegap app to communicate to Codeigniter Server in Android and Access-Control-Allow-Origin error - codeigniter

I am extremely new to using phonegap,codeigniter and jQuery Mobile (My first project) and have currently created an app with jQuery Mobile on the Client side and on the Server side I used the Codeigniter framework to create a RESTful API. Now when I am developing locally the app with in the browser (not yet using phonegap) communicates just fine with the API and no problems occur.
I placed the Codeigniter API on a server yesterday and I am now encountering 2 problems:
The App which was built using jQuery Mobile keeps getting the
following error:
Origin localhost is not allowed by Access-Control-Allow-Origin.
Now I have done some reading up and most people say to use jsonp instead of json and also to use the following on the Server Side:
$CI->output->set_header("Access-Control-Allow-Origin: *");
$CI->output->set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
$CI->output->set_status_header(200);
$CI->output->set_content_type('application/json');
Now my problem is I'm not entirely sure which one is used to fix the problem, weather it is both that need to be implemented etc. If they need to be fixed, how is it done? Is there a place that is well documented that can teach me how to deal with this problem, preferably I would like some where to read up on so I can learn?
The second problem is when I place the jQuery Mobile app into
phonegap and build it for Android. The app fails to get the
data from the server. Now is the reason for this because of the cross
domain error above or is this problem different? I also did some
reading up in this section as well and to my Android config.xml I
added the following code:
But I'm I still can't pull anything from the server. Like I said I'm a bit of a newbie but would really appreciate some help in this matter. Also I am aware that I haven't posted code but based on the comments I'll post which ever code the community needs to help solve this problem, just simply specify which code. Thank you for the help in advance!

About the Access-Control-Allow-Origin problem, I faced the same error and solved by placing this line <?php header('Access-Control-Allow-Origin: *'); ?> in the index.php which is in the root of the project.

This question hasn't been answered 100% but for now thanks to the help of #Niloy Saha, to fix the Access-Control-Allow-Origin error with with the Codeigniter RESTful frame work simply go to your controller in the Controller folder and right at the top paste;
header('Access-Control-Allow-Origin: *');
This then should allow you to communicate from the browser to the server and be able to get a response. After a good for hours of trying I managed to fix my problem. With in the Android project in the res/xml folder there is a file called config.xml. In that file be sure to have the following code:
<access origin="http://10.0.2.2*" subdomains="true"/>
and also make sure you have the following:
<uses-permission android:name="android.permission.INTERNET" />
in your AndroidManifest.xml. For me that seemed to get everything to work

I did similar thing as yours, Zend FW with API on server and jQuery Mobile App.
I've used JSONP, didn't use any Access-Control-Allow-Origin headers.
I have a method in my controller:
function returnData($data) {
header('Content-type: text/javascript');
echo $_GET['callback']. '('. json_encode($data). ')';
die();
}
At the end of API call i use it to return data.
Getting data in jQuery:
$.ajax({
dataType: "jsonp",
url: url,
data: {someparam: 'value'},
success: function(data) { /* ur data is here */ }
});

Related

Curl works but ajax not working in Shopify private app

I have created a private app from my store and try to hit https://API_KEY:PASS#STORE_NAME/admin/orders.json URL using ajax and curl. It is working if I use curl but not with ajax. Can anyone explain here what is the issue?
This might be a Cross origin problem. If you are using jQuery try to make an ajax call with dataType set to jsonp as shown here:
$.ajax("url", {
dataType: "jsonp",
success: function(data) {
console.log(data);
}
})
Like the other answer said, it's a cross origin problem (See CORS)
Best way to deal with it normally is Shopify App Proxy, but this isn't available to private apps, only custom apps. Best bet is to build a custom app and authenticate with OAuth2, assuming there's no other reason you've chosen to build a private app instead.
If the nature of your app permits the change to a custom app, the App Proxy will give you a {store-name}.myshopify.com/{resource} end point that will bypass the cross-origin issue, but forward the request to your remote server.
Also, when you're working with JS and something is not working, check the console, and share any errors. No one can really tell you why it's not working without seeing either the code, the error, or both, but this is a common enough stumbling block with AJAX since all this cross-origin security stuff got put into place that I'm 90% sure it's the answer.

Calling SAP SOAP Webservices via Ajax Javascript – Go round the cross-domain-policies

I’m trying to develop a web application, which should submit a SOAP-Request (POST) to a SAP Webservice using Ajax / Javascript. After that the appropriate data from the SAP System should be displayed on the web application.
However, I’m now faced with the cross-domain problem, because of the web application and the system are on different domains. If I adjust my IE (btw. IE11) security settings, the application will run correctly.
But I want to avoid that, because the application will not be only used on my computer, but also it’s to be used by many other users. It’s important that it supports all browsers and mobile devices, without the need to adjust the security settings.
With the default security level, the application no longer works for me and I get the error message “XMLHttpRequest: Access denied” because apparently CORS and CORS Preflight is required.
Looking for a solution, I’m first stumbled upon JSONP. But since this are standard SAP Webservices and the data are transmitted in XML-form (not json) by means of the WSDL, this method in my opinion, falls out. In addition, I use “POST”-methods. In JSONP only “GET”-methods will be supported.
I would also like to avoid to solve the problem via another server or a proxy which is stored between the SAP system and the web application, because I had no knowledge of those topics related with SAP Systems and does not know how to implement this.
CORS seems to be a good option in my case.
From the request header I can deduce that following attributes are sent to the host of the SAP System:
Option: with the domain of the Web application
Access-Control-Request-Method: with the value “POST”-method
Access-Control-Request-Header: with the entries “content-type, accept”
Requirement: with “OPTION”
See request header: http://up.picr.de/23122262lo.png
If I understood CORS correctly, the SAP system must now respond appropriately to this request to allow the cross-access. I’ve tried using a “crossdomain.xml” – file like in flash or adobe which I’ve provided in the root of the SAP System domain. Calling via the path “SAP domain/crossdomain.xml”, the XML-file is shown as follows:
<?xml version="1.0" ?>
<cross-domain-policy xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
</cross-domain-policy>
Unfortunately, this is apparently not entirely sufficient. From the response header I can see that the XML-file is not taken.
See response header: http://up.picr.de/23122265yp.png
How should I attach that CORS permissions to the response headers in SAP? Is this solution only possible for adobe or flash? Can I also use this in my case or can I bind the appropriate permissions in the webservice settings (SOAMANAGER), eg. in a binding?
How it looks with a SAP sided proxy? Would that be an option and if so, do you have any advice for the implementation?
I would be very grateful about helpful tips and answers, especially since I have no other ideas at the moment, how to solve this cross-domain problem.
Thank you in advance for your assistance.
Here is my request-snippet:
`//jQuery.support.cors = true;
$(document).ready(function () {
var wsUrl = "http://BCSW-SAP016.xxxxxx.net:8000/sap/bc/srt/rfc/sap/z_agbs_webservice_xxxx/001/service/binding";
var soapRequest ='<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:urn="urn:sap-com:document:sap:soap:functions:mc-style">'
+ '<soap:Header/>'
+ '<soap:Body>'
+ '<urn:ZAgbsWebserviceComTab>'
+ '<Aosuser>'+aOSUser+'</Aosuser>'
+ '<Asystem>'+aSystem+'</Asystem>'
+ '<EvTabelle>'
+ '</EvTabelle>'
+ '</urn:ZAgbsWebserviceComTab>'
+ '</soap:Body>'
+ '</soap:Envelope>';
$.ajax({
type: "POST",
url: wsUrl,
contentType: "application/soap+xml", // charset=UTF-8", //
action: "urn:sap-com:document:sap:soap:functions:mc-style:Z_AGBS_WEBSERVICE_xxxx:ZAgbsWebserviceComTabRequest",
dataType: "xml",
data: soapRequest,
success: processSuccess,
error: processError
});
});
Check out this blog post
You need to add a custom handler that sets the "Access-Control-Allow-Origin" header and then assign the header in SICF.

Ajax Request gets blocked in Firebug but works in Genymotion. Why?

I am trying to build an "app version" of my website (a social network).
I am using PhoneGap + jQuery Mobile (i started learning them today).
The app simply needs to retrieve new posts from the website and show them to the user. Therefore I thought a simple Ajax Request would do the job.
So, i created a php test file on the server (URL: http://www.racebooking.net/it/moto/app/get_post_test.php), which simply Echoes Alien contact SUCCESS!
I've made a simple html page in localhost (on my PC) called index.html with a div called #post-container and an AJAX request:
var root = "http://www.racebooking.net/it/moto"
$.get(root + "/app/get_post_test.php", function(data){
$("#posts-container").html(data);
});
If everything is correct, i expect to see Alien contact SUCCESS! in the post-content div.
What happens looks strange:
If i run the app from eclipse using Genymotion, everything works fine
and i see the message Alien contact SUCCESS! -> the AJAX request
went fine
If i open the index.html file on firefox, i don't see anything
and FireBug informs me that the cross-origin request was blocked.
He also tells me to activate CORS.
1) Why is that happening and how can i make FireBug work (which is better and faster for debugging)?
2) Am i following the right procedure or i am missing something?
I found the solution from this post.
I just needed to add header('Access-Control-Allow-Origin: *'); at the top of my php file.

Angular JS $http request does not reach the server in ie8

I'm having issues with using $http on ie8. The request does not reach the server, until I hit a refresh. Coming back to the same link still has the same problem until I hit refresh again.
The weird thing is if the web server is on LAN and the request is made to a server in LAN, it works fine. But if the webserver is hosted remotely, it does not work!
Here is the code:
Index.html
{{test}}
Controller
app.controller(
"TestController",
function( $scope, $http) {
var url = '/test/get_data';
$http.get(url).success(function(data) {
$scope.test = data;
});
}
);
I got this error: TypeError: Object doesn't support this property or methodundefined
I prepared a JSFiddle earlier but JSFiddle is broken in ie8 so I don't provide it here.
Unfortunately I don't have a remote server that I can share with you.
Edit
Previously I used an external url which gave me 'Access Denied' error in ie because of Same Origin Policy as mentioned by one answer below. But this was not my original problem. I still have the issue above when request is from the same origin
This is a cross domain request, which is not allowed in ajax because of Same Origin Policy.
There are two solutions for this
1. JSONP: It is a cross browser way to handle cross domain ajax requests using javascript callback mechanism
2. CORS: It is a HTML5 standard, it is implemented by most of the modern browsers except IE
Mongodb lab is not supporting jsonp since it has support for CORS, that is why your request is failing in IE and works in Chrome and other browsers.
As per this post they do not have any plan to support jsonp, so I don't thick there is a way to make this work in IE.
So I found the fix... Hope this helps anyone out there that experience this problem
Angular script needs to be loaded after jQuery. I didn't have this because Yii framework that I use autoloads jQuery and the angular was not included after the jQuery.
All the controller functions need to be at the end of body section (just before the closing )
Updating to angular 1.0.5 seems to fix the problem. The problem occurred in 1.0.4 with all the above tricks. I think is related to fix 791804bd

Can I use XMLHttpRequest on a different port from a script file loaded from that port?

I have website that use XMLHttpRequest (jQuery, actually). I also have another site running on the same server, which serves a script file that makes XHR requests back to THAT site, ie.
http://mysite:50000/index.html includes
<script src="http://mysite:9000/otherscript.js"></script>
and http://mysite:9000/otherscript.js includes
$.ajax({
url: 'http://mysite:9000/ajax/stuff'
});
The problem is - this doesn't work. The AJAX requests from the loaded script simply fail with no error message. From what I've been able to find this is the old same origin policy. Given that I control both sites, is there anything I can do to make this work? The "document.domain" trick doesn't seem to do a thing for XMLHttpRequest.
Nope- can't do this with XHR. Same-domain policy is very restrictive there- same host, same port, same protocol. Sorry! You'll have to resort to other tricks (iframes, title manipulation, etc) to get it to work.
You can do this by adding Access-Control-Allow-Origin header.
If you are using PHP
header("Access-Control-Allow-Origin: http://example.com");
or in Node.js
response.writeHead(200, {'Access-Control-Allow-Origin':' http://example.com'});
This should do the trick for you. It always works for me.
I just solved a similar issue with a PHP service I'm currently playing around with (not sure how relevant a PHP solution is to this directly, but...) by making a single line proxy PHP page, SimpleProxy.php:
<?php
echo file_get_contents('http://localhost:4567');
?>
And in my XMLHttpRequest I use 'SimpleProxy.php' in place of 'http://localhost:4567', which effectively puts the request on the same domain as my .js code.

Resources