tim berspine
tim berspine

Reputation: 865

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?

Upvotes: 1

Views: 4226

Answers (2)

Jeff Lambert
Jeff Lambert

Reputation: 24661

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');
});

Upvotes: 1

nzt
nzt

Reputation: 378

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>

Upvotes: 3

Related Questions