Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ali2535's avatar

Redirect To Another Page In ajax

how i can redirect to another page in ajax with data? for exaple i have an view that i must pass 2 array argument to this. and this must redirect in ajax success body .

0 likes
6 replies
mushood's avatar

If done with Ajax, the actual redirection needs to be in Javascript code.

Once the Ajax is done, window.location = "http://www.yoururl.com";

$.ajax({
  type: 'POST',
  url: 'AJAX URL',
  data: "YOUR DATA"
  success: function(data){
   window.location = "http://www.yoururl.com";
  },
  error: function(xhr, type, exception) { 
    // if ajax fails display error alert
    alert("ajax error response type "+type);
  }
});
1 like
ali2535's avatar

@mushood : Thank u for ur reply but i want to send to array data to view;

return view('test' , compact('data' , 'data1'))

mushood's avatar

Then why use Ajax?

Usually ajax is used to load data without page refresh.

You can use a form with hidden input fields and then a submit button that POST the data to your page or some javascript to submit the form when your event takes place.

Do post some code for more specific answer.

1 like
ali2535's avatar

@mushood i have multi input that with ajax i validate this . and when validate is ok i call an api and get 2 arrays . i want pass this 2 array to a view and redirect to this view

ali2535's avatar

@mushood

this is wrong :

   $decoded = json_decode($response);
    if (isset($decoded->msg) && $decoded->code == 1) {
      $data = $decoded->data;
      $informations = $decoded->data->params;])]);
          return view('flight.info-confirm', compact('data', 'informations'));
Asonn's avatar

In your controller do something like this:

if($request->ajax()) {
  return response()->json([
       'view' => view('test', compact('data', 'data1'))->render(),
  ]);
}

and in your javascript file.

$.ajax({
  type: 'POST',
  url: 'AJAX URL',
  data: "YOUR DATA" // don't forget to pass your csrf_token when using post  
  success: function(data){
   $("what_ever_you_want_to_replace").html(data.view);
  },
  error: function(xhr, type, exception) { 
    // if ajax fails display error alert
    alert("ajax error response type "+type);
  }
});

This is how you render a view. however this is not really a redirect as it's only meant for passing and loading data on the current page.

3 likes

Please or to participate in this conversation.