Ajax request works in remote server but not in local server (with Codeigniter)
I've a web application wich makes Ajax requests to a server with Codeigniter-php code. The Ajax requests work correctly in local server but not when the application is hosted in remote server. The console errors are:
XMLHttpRequest cannot load http://localhost/CI-example/index.php/control/controlHome. Origin http://www.page.com is not allowed by Access-Control-Allow-Origin.
Surprisingly, the request is made in the server but not the response.
The URL that I use to Ajax request is:
AJAX_URL = "http://localhost/CI-example/site/index.php/control/controlHome";
But, also I've tried with:
AJAX_URL = "http://www.page.com/CI-example/site/index.php/control/controlHome";
And the next error is captured:
POST http://www.page.com/webdom/site/index.php/control/controlHome 500 (Internal Server Error)
How can I do?
Edit: www.page.com is a subdomain. Is necessary to do some configuration when a subdomain is used to Ajax request?
And the folders organization is:
/CI-example ---/application/controllers/control.php ---/system ---/site/js/ajaxRequest.js
As I am getting here, while you are sending ajax requests to the server than it's returning 500 (Internal Server Error). I'm sure that the error is from server side, and there may be following reason-
- If everything is fine in the codes, then may be your base_url is different from what you are requesting. Yes this can cause the problem, for example if you have hosted your web application and your base_url is www.mysite.com and you are requesting for mysite.com.
- Next reason may be, that you have developed your project in windows or any system which is in-case-sensitive but when you will upload to any linux like server than each and every file name will be case-sensitive. For example suppose a model file name you have given is MyModel.php but when you will load the model, it will generate the error like Unable to find the specific class.
You cannot make HTTP POST requests using AJAX to a different domain, unless that page allows you to do so using a special header called "Access-Control-Allow-Origin".
localhost is different to page.com which is why this will not work.
Response on the http://www.page.com's url say something has gone wrong during the page execution. Your PHP error log should help you to find what.
Adding the line ini_set('display_errors', 1) might return the error to the ajax request, in the error handler. Don't forget to remove the line after use, you don't want this lying around in production code.
The second error is : 500 (Internal Server Error)
This means there was an error on the server side - not a cross-origin policy problem. This is probably an error in the execution of your PHP script.
Check your error log (e.g : if you use the standard LAMP stack, the error log should be somewhere in /var/log/apache2/)
in your ajax URL. As from your folder structure, there is no need to include "site" in your URL