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

Share this:

  • Facebook
  • X

Related

Javascript jQuery

Post navigation

Previous post
Next post

Related Posts

Javascript Setup Client side javascript validation

How to Setup Client side javascript validation ?

September 16, 2021September 29, 2021

In this tutorial we will learn javascript validation without using any third party library. we will validate the simple form with 5 inputs fields. Let’s start with simple steps Step 1: Create a html file Firstly we are going to create html file which contains a form with basic fields….

Share this:

  • Facebook
  • X
Read More
Javascript how to install angular

What is Angular and how to install angular ?

August 29, 2021October 1, 2021

Angular is a framework of javascript. It’s used for creating efficient and single page application with ease. We can define the angular as follow: Angular is a component based component framework. Angular is collection of libraries which include routing, forms, validations, http requests etc. Angular is easy to use and…

Share this:

  • Facebook
  • X
Read More
Javascript Angular KeyDown Event on Input Example

Angular KeyDown Event on Input Example

September 22, 2022November 8, 2023

Angular KeyDown Event on Input is an Angular event binding it triggers when user interacts with DOM like text based input element and when we key down the input. Input events in angular can be handled using input and output decorators and in this tutorial we will learn Angular KeyDown…

Share this:

  • Facebook
  • X
Read More

Leave a ReplyCancel reply

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 9
  • Mysql
  • Php
  • Softwares
  • Ubuntu
  • Uncategorized

Archives

  • 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

  • How to Call Controller Method from Another Controller in Laravel ?
  • How to Get Domain Name in Laravel ?
  • How to Append Query String to Route in Laravel ?
  • How to Append URL Query Params to Pagination Laravel ?
  • How to Get Today Records in Laravel ?
©2023 Readerstacks | Design and Developed by Readerstacks
Go to mobile version