ajck's avatar
Level 1

How to get Laravel to return correct HTTP response to trigger JQuery $.ajax() success?

I'm doing an AJAX POST of a simple HTML form using JQuery on my front end, to my Laravel back end, and upon success want to return the correct response to trigger JQuery's $.ajax() 'success' block rather than it's 'error' block. Unfortunately whatever I try seems to trigger the 'error' block.

My route is:

Route::post('/signup', 'AccessController@signup');

Back end:

public function signup()
    {
    [main code]
    return response('OK', 200); // I also tried return response('OK', 200)->header('Content-Type', 'text/plain'); and just: return "OK";
    }

Front end:

$('#signupbtn').click(function(e)
{
$.ajax({
    headers: { 'X-CSRF-TOKEN': $('#signup-form > input[name="_token"]').val() },
    type: 'POST',
    url: 'signup',
    data: { email: $('#email').val(), name: $('#name').val() },
    dataType: 'json',
    success: function (data)
        {
        console.log(data);
        $('#signupmodal').modal('hide'); // Close sign up modal
        $('#thanksmodal').modal(); // Open thanks modal
        },
    error: function (data)
        {
        console.log('Error:', data.responseText);
        }
    });
});

Also, if I DO want to trigger the $.ajax() 'error' block, what's the correct Laravel code for that?

Thanks.

0 likes
4 replies
Snapey's avatar

Are you definitely hitting this code?

Open your browser inspector tool and look in the network tab. Post the form then check the response. You should see the response code and any message.

Cronix's avatar

is #signupbtn in a form? If so, you should use e.preventDefault(); in your js before the ajax call. Also try /signup for the ajax url.

1 like
ajck's avatar
Level 1

@Snapey @Cronix thanks very much - good suggestions which I've now tried but unfortunately makes no difference. I am definitely hitting the correct code on the back end in Laravel as it's doing the things it's supposed to, and if I modify the response sent back it appears in the JS console but is always triggering JQuery's error block rather than success block, and yes the response is definitely an HTTP 200 OK code. Hmmm....

ajck's avatar
Level 1

OK, fixed it! In case anyone else comes across the same issue... basic problem was JQuery's success block only gets triggered for 200 OK (which I had) and if it can deserialise the response, which I take to mean response is in the same format as the AJAX request which in my case is JSON, but I was returning MIME type text/plain. So the fix was in my Laravel response code, changing it to:

return response()->json(['ok' => 'ok']); // Return OK to user's browser

More info here: https://stackoverflow.com/a/14114816/4059141

1 like

Please or to participate in this conversation.