简体   繁体   中英

Making an asynchronous AJAX call from within Laravel

I'm trying to make an asynchronous jquery/ajax call from within a View in Laravel. There is a background worker task that is processed by Redis Queue which is then in turn stored in key:value form on Redis.

Let's say the view is:

project > app > views > main > search.blade.php

The script that accesses this key:value pair is in:

project > app > views > main > getVal.blade.php

I'm calling getVal.blade.php asynchronously through search.blade.php :

<script>
    var userID = {{ isset($userID)?$userID:'0' }};
    $.ajax({
        type: "POST",
        url: 'main/getVal',
        data: { id: userId }
    }).done(function( msg ) {
        alert( msg );
    });
</script>

In routes.php, I have defined getVal as:

Route::get('main/getVal',function() {
    return View::make('main.search');
});

I'm not seeing the alert box . What am I doing wrong?

I found the following:

  • There is a typo (userID vs userId) which causes an error
  • url: 'main/getVal' is a relative address, in Laravel I would use this so it works on any page: url: '{{ url('main/getVal')}}'
  • As noted by watcher , you need to handle the POST request

The complete code that works for me:

 # routes.php Route::get('main/getVal',function() { return view('main.search'); }); Route::post('main/getVal',function() { return 'This is a test'; }); # search.blade.php <!DOCTYPE html> <html> <head> <title></title> <script src="//code.jquery.com/jquery-1.11.2.min.js"></script> <script> var userID = {{ isset($userID)?$userID:'0' }}; $.ajax({ type: "POST", url: "{{ url('main/getVal')}}", data: { id: userID } }).done(function( msg ) { alert( msg ); }); </script> </head> <body> </body> </html> 

Your 'main/getVal' route is defined in the routes.php file to respond to GET requests, but your jQuery is performing an AJAX POST request. Check your network tab, I imagine you're getting a 404 error from Laravel. You can also add a .fail() function chained to the end:

var userID = {{ isset($userID)?$userID:'0' }};
$.ajax({
    type: "POST",
    url: 'main/getVal',
    data: { id: userID }
}).done(function( msg ) {
    alert( msg );
}).fail(function() {
    alert('failed!');
});

The solution? Make an AJAX GET request instead:

var userID = {{ isset($userID)?$userID:'0' }};
$.ajax({
    type: "GET",
    url: 'main/getVal',
    data: { id: userID }
}).done(function( msg ) {
    alert( msg );
}).fail(function() {
    alert('failed!');
});

Or, change your route in Laravel to respond to POST requests:

Route::post('main/getVal',function() {
    return View::make('main.search');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM