Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel passing data using ajax to controller

How do I pass the id from this ajax call to the TestController getAjax() function? When I do the call the url is testUrl?id=1

Route::get('testUrl', 'TestController@getAjax');

<script>
    $(function(){
       $('#button').click(function() {
            $.ajax({
                url: 'testUrl',
                type: 'GET',
                data: { id: 1 },
                success: function(response)
                {
                    $('#something').html(response);
                }
            });
       });
    });    
</script>

TestController.php

public function getAjax()
{
    $id = $_POST['id'];
    $test = new TestModel();
    $result = $test->getData($id);

    foreach($result as $row)
    {
        $html =
              '<tr>
                 <td>' . $row->name . '</td>' .
                 '<td>' . $row->address . '</td>' .
                 '<td>' . $row->age . '</td>' .
              '</tr>';
    }
    return $html;
}
like image 224
learntosucceed Avatar asked Oct 14 '14 00:10

learntosucceed


Video Answer


2 Answers

Your ajax's method is GET but in controller you use $_POST to get value. This is problem.

You can you

$id = $_GET['id'];

But in Laravel, it have a pretty method to do this. It's here. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs.

$id = Input::get("id");

If you want, you can filter request type to control exception. Docs here

Determine If The Request Is Using AJAX

if (Request::ajax())
{
    //
}
like image 90
Tam Nguyen Avatar answered Sep 19 '22 17:09

Tam Nguyen


In the end, I just added the parameter to the Route::get() and in the ajax url call too. I changed $_POST['id'] to $_GET['id'] in the getAjax() function and this got my response back

Route::get('testUrl/{id}', 'TestController@getAjax');

<script>
    $(function(){
       $('#button').click(function() {
            $.ajax({
                url: 'testUrl/{id}',
                type: 'GET',
                data: { id: 1 },
                success: function(response)
                {
                    $('#something').html(response);
                }
            });
       });
    });    
</script>

TestController.php

public function getAjax()
{
    $id = $_GET['id'];
    $test = new TestModel();
    $result = $test->getData($id);

    foreach($result as $row)
    {
        $html =
              '<tr>
                 <td>' . $row->name . '</td>' .
                 '<td>' . $row->address . '</td>' .
                 '<td>' . $row->age . '</td>' .
              '</tr>';
    }
    return $html;
}
like image 43
learntosucceed Avatar answered Sep 18 '22 17:09

learntosucceed