Spread the love

In this article i will show you to redirect a page after successful response from Ajax request. Laravel or PHP provides itself to redirect a page using its own methods but while working with JavaScript Ajax Laravel methods are not useful because it won’t redirect the page. so in this article i will show you two to redirect using jQuery with example.

So let’s make a quick example of jQuery redirect on Ajax success.

Quick Answer

function ajaxHandle(){
 
  return response()->json(['status'=>true,"redirect_url"=>url('login')])
  //or in php
  return json_encode(['status'=>true,"redirect_url"=>url('login')]);
   
}
$.post('url-to-call',{demo:1},function(data){
    // 200 http response code
    if(data.redirect_url){
       window.location=data.redirect_url; // or {{url('login')}}
    }
}).fail(function(response) {
    
//handle errors and other http response code

});

Let’s understand it by example in Laravel and jQuery

Step 1: Create a Controller

Create a controller manually in app\Http\Controllers or create using artisan command

php artisan make:controller PostController

Above command will create a controller in app\Http\Controllers\PostController.php and now open the controller and replace code.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class PostController extends Controller
{
    function simpleform()
    {
        return view("form");
    }  
    function ajaxHandle(){
 
        return response()->json(['status'=>true,"redirect_url"=>url('login')])
       //or in php
       return json_encode(['status'=>true,"redirect_url"=>url('login')]);
    }   
}

Step 4: Create views

Create a simple view with name form in folder resources/views/form.blade.php and include jQuery and script


  <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
            <form method="post" id="handleAjax" action="{{url('ajax-handle')}}" name="postform">
              <div class="form-group">
                <label>Email</label>
                <input type="email" name="email" value="" class="form-control" />
                @csrf
              </div>
              <div class="form-group">
                <button type="submit" class="btn btn-primary">Submit</button>
              </div>
            </form>

Here we used id='handleAjax' and to handle it in javascript

<script>
    $(function() {
        // handle submit event of form
        $(document).on("submit", "#handleAjax", function () {
            $.post('ajax-handle',  $(this).serialize(), function (data) {
                // 200 http response code
                if (data.redirect_url) {
                    window.location = data.redirect_url; // or {{url('login')}}
                }
            }).fail(function (response) {
                //handle errors and other http response code
            });

        })
    });
</script>

In Laravel Controller we usually used redirect('url') method to redirect to a page but while working with Ajax we need to send JSON response so in controller

Also make sure response is JSON format if not then you need to parse it as below

function IsJsonString(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
$.post('url-to-call',{demo:1},function(data){
    // 200 http response code
     if(!IsJsonString(data)){
        data= JSON.parse(data);
     }
     
     if(jsonResponse.status){
     
     }
}).fail(function(response) {
    //handle errors and other http response code
});

Step 5: Create routes

Now, create the routes for all pages and method in routes\web.php

<?php

use App\Http\Controllers\PostController;
use Illuminate\Support\Facades\Route;

Route::get('/ajax-handle', [PostController::class,"ajaxHandel"]);

I hope it will help you to understand,.

Leave a Reply