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

habib97's avatar

controller is not working when ajax request is fired

hello! i am new to laravel and i have a issue, i want to sent data to controller from js(client side) and i have write the ajax code and it's working but my controller is not working. here is my route.php:

Route::get('/test', 'ListingsController@viewTest');
Route::post('/test', 'ListingsController@doTest');

the 'hellowolrd' in the console is appearing and here is my view:

@extends('layouts.app')

@section('content')
    {{Form::text('test', '', [ 'id' => 'test'])}}
    {{Form::submit('submit', ['class' => 'btn btn-primary', 'onclick' => 'getData()'])}}
@endsection
<script>
    function getData(){
        var value =  document.getElementById('test').value;
        console.log('----------------',value) 
        $.ajax({
            type:'POST',
            url:'/test',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data: {value},
            success:function(){
              console.log('hello world');
            }
        })
    }
</script>

but the controller is not running and here is my controller:

public function doTest(Request $request){ 
        print($request->value);
        return view('/pages.index');
    }
0 likes
32 replies
rin4ik's avatar

your first mistake return without /

 return view('pages.index');

it's very hard to read your code

Sergiu17's avatar

First, you submit with Ajax a POST request, but, your route is get

Route::get('/test', '');

And format your code, add 3 backtick before and after code

rin4ik's avatar

@habib97 can you show your full controller? what error do you get in network tab?

habib97's avatar

my doTest controller function is not working:

public function viewTest(){
        return view('listings.test');
    }

    public function doTest(Request $request){ 
        print($request->value);
        return view('/pages.index');
    }

i am not getting any error , here is my network tab details:

Request URL: http://daftar.pk/test
Request Method: POST
Status Code: 200 OK
Remote Address: 127.0.0.2:80
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-cache, private
Connection: Keep-Alive
Content-Length: 2077
Content-Type: text/html; charset=UTF-8
Date: Mon, 07 May 2018 12:10:04 GMT
Keep-Alive: timeout=5, max=99
Server: Apache/2.4.29 (Win32) OpenSSL/1.0.2n PHP/5.6.34
Set-Cookie: XSRF-TOKEN=eyJpdiI6InZVb3VTVmhWU0VLT0cwbG5DMkJXb2c9PSIsInZhbHVlIjoidHJNdGFONlNOaDNTeFFEOEVcL0tLSHV0bjVvdU4rTVRZNCt3OXc5TkI3SlVCVDZWbkRDY0ROdjV0ZVRYWmNldTVZN3pMZitCXC9DTUxrUEJld1BZMzRHZz09IiwibWFjIjoiZjQ2OGU4MTgzYzBiNzk4NWRiYmU0MTM5Y2Y5YmRhMTVkZDRhNDFkYzBhNDlhY2FlNTllODE3ZTc5MzExZDNmYSJ9; expires=Mon, 07-May-2018 14:10:04 GMT; Max-Age=7200; path=/
Set-Cookie: laravel_session=eyJpdiI6InhKeEdiSkRrYjhKZXFuclpacDNSdWc9PSIsInZhbHVlIjoiMDlPSzQ4SXplVVhlNDBqZ1ZVQkRLeFp2YnV4bUFESnY3MWk2azZQT1pMOUZqMUo2NFlsTlZERjFtM0UxblIwSTlPUTkwcjVOajRhTGF1UEhPekc4YlE9PSIsIm1hYyI6IjFmNGIzNDI4NDNjMTk2YzliNWE4ZWFkMjhjZGU5ODc0NWM5N2MzZWQ2M2Y1OGU5NzZiOWU5MjhlMjBjZDA5M2QifQ%3D%3D; expires=Mon, 07-May-2018 14:10:04 GMT; Max-Age=7200; path=/; httponly
X-Powered-By: PHP/5.6.34
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 9
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: XSRF-TOKEN=eyJpdiI6IjNLQVVobUpCUnU4eUNneHAzTmZ4Z0E9PSIsInZhbHVlIjoiOTRkU3dUWE9MYVd1dzFOaGhybEMxYWloOG5pMlRcLzcrWFBVZzVncmc0Qkx0VjZINTZwUWYxRkdMRHY1aEVEUUlOaE1hZ21WeWZtMDVEbDhibWpWZmhBPT0iLCJtYWMiOiJmMzY2ZjAwYjNiNDMwYjVjNzc0OWMwZDYzYjc2NzNiY2ZmYTEzNmMyYjhmODM1OTRhMzRiMTFiYWVmYWJiMzJlIn0%3D; laravel_session=eyJpdiI6IlIyMzk1dkJpYUlxZXZ3NEtYQUV5S2c9PSIsInZhbHVlIjoiM1Vqck8ycXVtYWIxVVJ2d3p2UnRoRFNFYmVjWlhHVlhOVlRxM3RNUENkdVJsRjF5MCt5Q0NybzJYdXFxWFViS1BIS0kxM2VuSWk1cHFBcVVUN3pNbUE9PSIsIm1hYyI6ImI3NTI2Nzk0NDVkNWI1ZjU0NDMxNmVmMTYzMGQ4YmI4NjJmY2ViMjI1OTZiMGVjNDg5NjIwNDRlMzk4ZjM3YzQifQ%3D%3D
Host: daftar.pk
Origin: http://daftar.pk
Referer: http://daftar.pk/test
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36
X-CSRF-TOKEN: AhtMdnMK9U4WcmBdIDeiVyVW8UiHZ7F0510TAudF
X-Requested-With: XMLHttpRequest
value: FOOTBALL
rin4ik's avatar

what is your controller name? make sure it is ListingsController and try to dd inside doTest

  public function doTest(Request $request){ 
        dd($request->value);
        return view('pages.index');
    }
habib97's avatar

yes my controller name is correct and

dd($request->value);

is still not working

rin4ik's avatar

try this

Route::post('/test',function(){
    dd(request()->value);
});
habib97's avatar

nothing happened but in my network tab of dev tools i got the value in preview tab

habib97's avatar

is there anything which i am forgetting to add for e.g any library??

habib97's avatar

now the problem is , it is not showing me pages.index view

public function doTest(Request $request){ 
        dd($request->value);
        return view('pages.index');
    }
rin4ik's avatar

because of dd

public function doTest(Request $request){ 
        return view('pages.index');
    }
habib97's avatar

i have removed dd but it is not going to pages.index in the preview tab of dev tools it is showing me index page but not in the browser

rin4ik's avatar

with this?

public function doTest(Request $request){ 
        return redirect()->route('pages.index');
    }
habib97's avatar

getting error

Route [pages.index] not defined.

however i have defined index page:

Route::get('/',  'PagesController@index');

here its controller:

class PagesController extends Controller
{
    public function index(){
        return view('pages.index');
    }
 }
rin4ik's avatar

that's correct use this

public function doTest(Request $request){ 
        return redirect('/');
    }
habib97's avatar

nope not redirect to index route still on the same page

rin4ik's avatar

hmmm....

Route::get('/',  'PagesController@index')->name('index');
public function doTest(Request $request){ 
        return redirect()->route('index');
    }
habib97's avatar

again nothing happen and showing in preview tab but not redirecting in the browser

rin4ik's avatar

@habib97 I think you are in that exact page and redirecting to that page again

habib97's avatar

no i am at the daftar.pk/test page and after submitting the button and successfully firing ajax request i am not redirecting to daftar.pk which has just some text written ...

36864's avatar

You're making an ajax request, and then completely ignoring the result of that request in the success callback function.

What exactly are you expecting to happen?

habib97's avatar

@36864 i will save the result in database then redirect to other route but the problem is it not redirecting

36864's avatar

It's not redirecting because you're not telling the browser to redirect.

What you're doing is using ajax to make an HTTP request to a uri. That uri is then responding with a redirection, which is followed, and the page that your ajax request was redirected to then responds with some data. This data is what is now available to your ajax success callback function.

If you want to redirect the user after an ajax call, you have to do the redirection on the success callback of your ajax call.

1 like
habib97's avatar

@36864 thank you! i just searched this problem and found the same answer you gave... and @rin4ik thank you so much for helping me :)

Grelav's avatar

You have to add the CSRF TOKEN to your ajax request.


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


jlrdw's avatar

I do not understand all the trouble people have posting with ajax:

    $(function () {

        $("#postjq").click(function (event)
        {
            event.preventDefault();
            var $post = {};
            $post.petid = $('#petid').val();
            $post.species = $('#species').val();
            $post._token = document.getElementsByName("_token")[0].value
            $.ajax({
                url: 'petupdate', 
                type: 'POST',
                data: $post,
                cache: false,
                success: function (data) {
                    return data;
                },
                error: function () {
                    alert('error handing here');
                }
            });

        });
    });

The url line needs adjustment sometimes.

But this works 100%

And controller

    public function petupdate(Request $request)
    {

        $petid = $request->input('petid');
        $species = $request->input('species');
        $postdata = [
            'species' => $species
        ];
        DB::table('pets')
                ->where('petid', $petid)
                ->update($postdata);

        //return redirect(Session::get('areturn'));
    }

This was just a very quick example I did a while back for another post. But it works

And here is video:

https://drive.google.com/file/d/1rg9oMb8Ke9ZonzOjKuQ6MJWw_XNJgGUY/view?usp=sharing

and for a redirect after ajax use

window.location.href = "yourchoice";

With all the examples of this, I cannot understand.

Next

Please or to participate in this conversation.