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

How to use ngFor and ngIf on same element in angular 12 ?

October 23, 2021October 23, 2021

In this tutorial we are going to resolve the issue of using *ngFor and *ngIf on same element. so, in angular ngIf and ngFor is a structural directives, and we can not use two structural directive on same element.ngIf is used for to make conditional logic and ngFor is used…

Read More
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 Angular Dynamic Style CSS with Example

Angular Dynamic Style CSS with Example

October 5, 2022March 16, 2024

In this blog post, we’ll explore Angular dynamic style CSS with example in component’s styles based on certain conditions. Sometimes in our application we want dynamically change the color, size, font, background images so Angular provides various ways to conditionally apply styles to elements. In this post, we’ll explore three…

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

  • 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

  • The Resilience of Nature: How Forests Recover After Fires
  • Understanding Laravel Cookie Consent for GDPR Compliance
  • Understanding High Vulnerabilities: A Critical Overview of the Week of May 12, 2025
  • Installing a LAMP Stack on Ubuntu: A Comprehensive Guide
  • Understanding High Vulnerabilities: A Deep Dive into Recent Security Concerns
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version