Ajax request works in remote server but not in local server (with Codeigniter) - javascript

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/)

try this,
http://localhost/CI-example/index.php/control/controlHome
instead of
http://localhost/CI-example/site/index.php/control/controlHome
in your ajax URL.
As from your folder structure, there is no need to include "site" in your URL

Related

blocked by CORS policy but still POST request is performed, HOW?

I had a server running on localhost port 3000 using NodeJs.
There I had a database linked and had 2 basic POST methods (Create and Delete)*.
*(I had not written any extra checking for request headers)
I was curious to know if only client-side JS (with a dummy HTML page) can perform the deletion by itself!
I wrote THIS in the client-side js (in a separate directory )
After trying the POST Delete operation like this ,
I got this ERROR
But even though error was raised, the "Deletion Operation" was still performed succesfully and the data with the specific id was deleted!
My Question is "what exactly is blocked if it was not the deletion operation ?
With CORS, requests are never blocked on server-side. It will only instruct the browser to not send the requests if possible (with PRE-FLIGHT).
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

Handling Ajax auto redirect

I am struggling from 2 days to solve the issue with my Laravel app which I have uploaded on Heroku server. This application is uploading a file through ajax request showing upload progress also on the page and it returns json response.
I have set the Content-Type: application/json and X-CSRF-TOKEN is also valid in the header but still after completing the upload instead of returning valid json response, it setting status to 301 and 302 and move to home page.
I have tested this Laravel app on my local server and its very stable there. I am thinking if there is any way to pause chrome before loading the redirection page by hitting a breakpoint, so I could know whats happening before the redirection. I have already tried this in console:
window.addEventListener("beforeunload", function() { debugger; }, false)
but it never trigger a breakpoint. Any help will be appreciated.
Finally after 2 hectic days in scrubbing my head with Heroku server, I figured out that Heroku Apache server requires that Laravel route should be set to handle both POST and GET method. In my case I have to use this:
Route::match(['get', 'post'], '/xls2db', 'HomeController#xls2db')->name('xls2db');
This does makes sense because after Ajax POST method it returns json response which will only be handled if the route accepts GET method also.
On my local server I was testing my app with php artisan serve which can GET json response with only POST route.

something wrong with jsonp data, How to get the data

But it returns -403 why
but when I click that, It comes out this
how can I get the message
The HTTP 403 Forbidden client error status response code indicates that the server understood the request but refuses to authorize it.. After one-line check with Fetch API the answer is: server is not handling Cross Origin Resource Sharing - making cross-origin AJAX is not possible. You can avoid it by using simple local HTTP server (e.g. in Python) to get data from server (e.g. with requests) and self-serve it (e.g. with Flask).
Check it in JS console:
fetch('https://api.bilibili.com/x/web-show/res/loc?jsonp=jsonp&pf=7&id=1695').then(r=>r.json()).then(json=>console.log(json))

How to get the status code of the page before it is loaded

There is a javascript line (you can try it in the browser console)
window.location.href='http://example.com'
that will push you to http://example.com
In the Browser(Google Chrome)-> Developer Tools-> Network section you may see the Status is 200 for it.
The question is:
how to get the status code 200/404/302 right BEFORE executing
window.location.href='http://example.com'
Thank you.
P.S. jQuery is OK for using.
The only way to get the status code would be to make the request before you navigate there. That means make an Ajax call to the resource and check the status. Only downside to this is the Same Origin Policy so the sites need to be in the same domain or they have to have CORS enabled for your resource.
The HTTP status code are generated by the server, so some HTTP request against the server needs to be executed BEFORE you can get a status code -- so you would need to do an Ajax call on the url -- adapting the simple example in JQuery.get you will have something like;
$.get( "http://example.com", function( data ) {
// Yeahh the URL works, we can do the page switch
window.location.href='http://example.com';
});
There are other examples in JQuery.get which deals with error handling etc, but you can read those for yourself.
Of cause, you don't need the entire page to get just the status, you can execute just a HTTP-HEAD which you can see discussed here
With all of this you may run into cross-site scripting restrictions which you can go an research separately -- there are lot of stack-overflow questions on that already.

Not cross-domain. XMLHttpRequest cannot load localhost:portNo1 . Origin localhost:portNo2 is not allowed by Access-Control-Allow-Origin

I have a server created from BaseHTTPServer.HTTPServer in Python at localhost:portNo1
Client-side is at localhost:portNo2 and at client-side, I am making a jQuery $.ajax POST request like this:
var request = $.ajax({
url: "http://localhost:portNo1",
type: "post",
dataType: 'json',
data: json_data
});
At server side, server gets the data from client and replies with its data.
def do_POST(self):
# Get client data
length = int(self.headers.getheader('content-length'))
data_string = self.rfile.read(length)
print data_string;
# Create response object
jsonObjStr = json.dumps(jsonObj);
self.send_response(200)
self.end_headers()
self.wfile.write(jsonObjStr);
What happens is that server is getting the data I sent, but there is no reply to the client and the callback at the fail event of $.ajax object executes at the client-side(error msg). I debugged and verified there is nothing with jsonObj. But I cannot see what is inside self.wfile object.
At the JS console, I get the following error also (it shows up at the JS console of Google Chrome and it doesn't show up in Firefox JS console):
XMLHttpRequest cannot load localhost:portNo1 . Origin localhost:portNo2 is not allowed by Access-Control-Allow-Origin. client.html:1
The JS console at Google Chrome points to html file, but that didn't make sense for me, either.
I checked the website and it seems that the error is generally caused due to cross-domain requests. However, I am communicating from one localhost port to another.
Well, that's the problem. Cross-origin restrictions do not allow you to communicate across ports without sending a Access-Control-Allow-Origin: * header.
A better solution would be to use Nginx or some other webserver to reverse proxy those two running applications to the same domain and port.

Categories

Resources