Skip to content
Readerstacks logo Readerstacks
  • Home
  • Softwares
  • Angular
  • Php
  • Laravel
  • Flutter
Readerstacks logo
Readerstacks

jQuery redirect after Ajax success Laravel PHP

Aman Jain, December 4, 2021December 4, 2021

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,.

Related

Javascript jQuery

Post navigation

Previous post
Next post

Related Posts

Javascript Custom form control in angular 12

Create custom form control in angular 12 / 13

December 19, 2021March 19, 2022

In this article i will show you to use FormControl in child component. By default child component can not access the FormGroup and we can not use FormControl or FormControlName in parent child component approach. You can also read How to make reusable components in angular? for how child and…

Read More
Javascript How to set and get cookies in angular using package

How to set and get cookies in angular using package ?

April 15, 2022April 15, 2022

In our last article we have covered how to use set and get cookies using a service in angular and in this article i will show you to set and get cookie using package. Cookies are used to store the data in client computer, Cookie can hold tiny information in…

Read More
Javascript Password and confirm password validation in javascript

Password and confirm password validation in javascript

September 17, 2021November 21, 2021

In this tutorial, we will cover password strength validation , password not empty validation and confirm password validation. we will check on every submission of form whether the entered password pass or fail the criteria. Password Strength validation in javascript Password field must contain At least 8 characters Should be…

Read More

Aman Jain
Aman Jain

With years of hands-on experience in the realm of web and mobile development, they have honed their skills in various technologies, including Laravel, PHP CodeIgniter, mobile app development, web app development, Flutter, React, JavaScript, Angular, Devops and so much more. Their proficiency extends to building robust REST APIs, AWS Code scaling, and optimization, ensuring that your applications run seamlessly on the cloud.

Categories

  • Angular
  • CSS
  • Dart
  • Devops
  • Flutter
  • HTML
  • Javascript
  • jQuery
  • Laravel
  • Laravel 10
  • Laravel 11
  • Laravel 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • October 2024
  • July 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • July 2023
  • March 2023
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Recent Posts

  • Mapping Together: The Vibrant Spirit of OpenStreetMap Japan
  • Understanding High Vulnerabilities: A Deep Dive into the Weekly Summary
  • Building a Million-Dollar Brand: The Journey of Justin Jackson
  • Mastering Schedule Management with Laravel Zap
  • The Resilience of Nature: How Forests Recover After Fires
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version