Diogo Silva
Diogo Silva

Reputation: 39

Laravel 5.2 - Return view from controller after ajax request

I have a javascript function that sends to a Controller some information (mostly vars like arrays and ids) to be inserted in a table, the problem is after the insertion is completed I want to return to a different view with a data array and i cant seem to do this (I think its because of the ajax request)

Javascript Code

  $('#importar').submit(function(e) {
       e.preventDefault();
           fdata=preparePostData();
        $.ajax({
            type:'POST',
            url:   $(this).prop('action'), // url, from form
            data:fdata,
            processData: false,
            contentType: false,
            success:function(data) {
                window.location.replace(data.url);
            }
        });
    }); // end form.submit

Function Prepare PostData()

 var file_data=$('input:file')[0].files;
        var postdata=new FormData();
        postdata.append('_token',token);
        postdata.append('startFrom',startFrom);
        postdata.append('idList',idList);
        postdata.append('nomeCampos',nomeCampos);
        postdata.append('posicaoCampos',posicaoCampos);
        postdata.append('file',file_data[0]);
        return postdata;

Controller Expected Code Do all inserts and functions and in the end

  $data = array('listNome' => $listName, 'contacts' => $contacts, 'errors' => $erro);
        return view("XPTO", $data);

Upvotes: 0

Views: 5345

Answers (3)

Diogo Silva
Diogo Silva

Reputation: 39

SOLVED

Not the most elegant solution but what I did was set the array with errors as an session variable and get that session var in the specific controller I need.

Controller

   $request->session()->put('importErrors',$erro);
        $response = array('status' =>'success','url' => '/ListarContactos/'.$idList);
        return response()->json($response);

JavaScript

$('#importar').submit(function(e) {
       e.preventDefault();
           fdata=preparePostData();
        $.ajax({
            type:'POST',
            url:   $(this).prop('action'), // url, from form
            data:fdata,
            processData: false,
            contentType: false,
            success:function(data) {
                if(data.status=='success'){
                    window.location.replace(data.url);
                }

            }
        });
    }); // end form.submit

XPTOController

$errorArray= $request->session()->get('importErrors');

After using it you can destroy the session variable or keep it(depending if you need it or not).

Upvotes: 0

Moppo
Moppo

Reputation: 19285

You should not return a view from an ajax call, because you'd get the view processed code as a parameter to the ajax callback. Think of an ajax call as an async 'behind the scenes' call to the server in which you pass parameters and get some other parameters back

You should instead return a JSON response from the controller with all the parameters you'll need to call the route from JS, and parse it in your success callback. For example:

Controller

//here you should store all the parameters you need in your JS calback
$data = array('status' => 'ok', 'url' => $redirect_url ); 

JS

success:function(data) 
{
    //data will contain the parameters you set in the controller, so you can use them to call the route
    if ( data.status == 'ok' )
         window.location.replace(data.url);
} 

Upvotes: 1

Arnav Yagnik
Arnav Yagnik

Reputation: 792

Just elaborating previous answer , Ajax call controllers are used to supply some data behind the scenes and standard controllers are used to control the view so best practise is to return data (JSON) form Ajax controller to the same view which requested the data. while the standard controller should be used to control the views.

Upvotes: 0

Related Questions