CodeIgniter Forums
ajax redirect to exception/error pages - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forumdisplay.php?fid=28)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forumdisplay.php?fid=30)
+--- Thread: ajax redirect to exception/error pages (/showthread.php?tid=76788)



ajax redirect to exception/error pages - kristianlake - 06-20-2020

Hi all,

When I use ajax and it returns an error, This is working great and as expected, but how do i let CodeIgniter deal with the returned error?
I looked in the manual and googled, but not sure what it is I am looking for! Smile

error: function(xhr, status, error) {
    if(xhr.status == 400) {
        //redirect to 400 page!
    }


How Do i pass this on so CodeIgniter shows its exception page(in dev)? (or any custom page in prod 400,500 etc)


RE: ajax redirect to exception/error pages - InsiteFX - 06-20-2020

Looks like you would need to do the error handling yourself.

CodeIgniter 4 User Guide - Error Handling


RE: ajax redirect to exception/error pages - kristianlake - 06-20-2020

Thanks Insite, I figured as much.
I guess I will deep dive into the code and see if i can figure it out Smile


RE: ajax redirect to exception/error pages - dave friend - 06-21-2020

You will need to use Javascript to make a redirect.

Code:
error: function(xhr, status, error) {
    if(xhr.status == 400) {
        //redirect to 400 page!
        window.location = "https://example.com/error400";
    }



RE: ajax redirect to exception/error pages - kristianlake - 06-22-2020

Spot on again Dave!.

I find that
var url= "http://localhost:8080/errors/html/error_404";
window.location = url;

is working great but
var url= "http://localhost:8080/errors/html/production";
window.location = url;

Does not return back the production "generic error" page.
Makes me wonder if my 404 is actually working or failing and redirecting me to a 404 anyway!

Any tips on this one? Smile


RE: ajax redirect to exception/error pages - dave friend - 06-22-2020

Looking at the URLs you're setting for window.location I pretty sure you are getting redirecting to a 404 anyway.

CodeIgniter expects the URL segments after to represent controller/method/args and errors/html/error_404 does not fit that pattern.

So you will need to create a controller/method to handle the error condition (or conditions) that might be returned.

The methods should either load a view detailing the error or throw an exception - possibly both. From the controller/methods, you can

PHP Code:
echo view('errors/html/error_404'); 

or

PHP Code:
echo view('errors/html/production); 

Or any other view files in errors/html or any custom pages saved anywhere you care to create them.