Adeel Ahmad Adeel Ahmad - 5 months ago 275
PHP Question

Laravel 5: Redirecting to external link on POST request

The function below is called through a POST request. I need to retrieve URL from my database and open the link in a new tab. I'm using the

Redirect::away()
function for this. But it gives a
MethodNotAllowedHttpException
. I have tried calling this function in a GET request and it works perfectly fine.

public function generateURL(Request $request) {

$screenRow = \App\ScreenshotRow::find($request->input('row_ID'));
$baseURL = $screenRow->BaseURL;

$screenshot = \App\Screenshot::where('Setname', '=', $screenRow->Setname)->get();
$pageURL = $screenshot[0]['PageURL'];

if ($baseURL == "") {
return Redirect::away($PageURL);
}

else
return Redirect::away($baseURL);
}


Is there any way to calling this function in response to a POST request?

Answer

I would simply use an Ajax Form and redirect the User with Javascript.

Make sure to give your Form an ID

<form id="myForm" method="POST" action="{{ route('your.route') }}">
...
...
<button type="submit">Submit the Form</button>

And make this Form working with Ajax

<script>
    $('#myForm [type="submit]').click(function(e){
        e.preventDefault();

        var form = jQuery(this).parents("form:first");
        var dataString = form.serialize();
        var formAction = form.attr('action');

        $.ajax({
            type: "POST",
            url : formAction,
            data : dataString,
            success : function(data){
                var url = $.parseJSON(data.responseText);
                console.log(data); 
                // Redirect to a new tab with the given url
                window.open(url.success, '_blank');
            },
            error : function(data){
                var errors = $.parseJSON(data.responseText);
                console.log(errors);
            }
        },"json");
    });
</script>

Okay - So if the Form receives a success Message, the success function is executed, otherwise the error function.

Lets go to the Backend Controller which handles the Request

public function generateURL(Request $request) {

    $screenRow = \App\ScreenshotRow::find($request->input('row_ID'));
    $baseURL = $screenRow->BaseURL;

    $screenshot = \App\Screenshot::where('Setname', '=', $screenRow->Setname)->get();
    $pageURL = $screenshot[0]['PageURL'];

    // Return a JSON Success Message with a Success HTTP Status Code
    if ($baseURL == "") {
        return response()->json(['success' => $PageURL], 200);
    }

    // Return a JSON Error Message with a Error HTTP Status Code
    else
        return response()->json(['error' => $baseURL], 400);
}

Now if your Backend throws a Success Message the success function of the Ajax Form is called which redirects to a new tab based on the given url which you passed in your Backend Controller Success Response.

NOTE

To avoid the tokenmismatchexception on an Ajax Request, you should add the csrf_token to your meta Section in your <head>.

<meta name="csrf-token" content="{{ csrf_token() }}">

And fetch this csrf_token on every Form Request

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
Comments