Juliver Galleto
Juliver Galleto

Reputation: 9037

laravel 5 simple ajax retrieve record from database

How can I retrieve data using ajax? I have my ajax code that I've been using in some of my projects when retrieving records from database but dont know how to make it in laravel 5 because it has route and controller.

I have this html

<select name="test" id="branchname">
    <option value="" disabled selected>Select first branch</option>
    <option value="1">branch1</option>
    <option value="2">branch2</option>
    <option value="3">branch3</option>
</select>

<select id="employees">
    <!-- where the return data will be put it -->
</select>

and the ajax

$("#branchname").change(function(){
    $.ajax({
        url: "employees",
        type: "post",
        data: { id : $(this).val() },
        success: function(data){
            $("#employees").html(data);
        }
    });
});

and in my controller, I declared 2 eloquent models, model 1 is for branchname table and model 2 is for employees table

use App\branchname;
use App\employees;

so I could retrieve the data like (refer below)

public function getemployee($branch_no){
    $employees = employees::where("branch_no", '=', $branch_no)->all();
    return $employees;
}

how to return the records that I pulled from the employees table? wiring from routes where the ajax first communicate to controller and return response to the ajax post request?

any help, suggestions, recommendations, ideas, clues will be greatly appreciated. Thank you!

PS: im a newbie in Laravel 5.

Upvotes: 3

Views: 31457

Answers (3)

umesh kadam
umesh kadam

Reputation: 1181

First check url of page from which ajax call initiates
example.com/page-using ajax

In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to example.com/page-using ajax/datalists

In Routes
Route::get('page-using-ajax/datalists', xyzController@abc)

In Controller Method

if (Request::ajax())
    {
        $text = \Request::input('textkey');
        $users = DB::table('datalists')->where('city', 'like', $text.'%')->take(10)->get();
        $users = json_encode($users);
        return $users;
    }

In Ajax Success Function

function(data) {
    data = JSON.parse(data);
    var html = "";
    for (var i = 0; i < data.length; i++) {
        html = html + "<option value='" + data[i].city + "'>";
    };
    $("#datalist-result").html(html);
}

Upvotes: 1

The Alpha
The Alpha

Reputation: 146191

At first, add following entry in your <head> section of your Master Layout:

<meta name="csrf-token" content="{{ csrf_token() }}" />

This will add the _token in your view so you can use it for post and suchlike requests and then also add following code for global ajax setting in a common JavaScript file which is loaded on every request:

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

So, you don't need to worry or add the csrf_token by yourself for methods who require this _token. Now, for a post request you may just use usual way to make an Ajax request to your Controller using jQuery, for example:

var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
    // ...
});

Here, url should match the url of your route declaration for the employees, for example, if you have declared a route like this:

Route::post('employees/{branch_no}', 'EmployeeController@getemployee');

Then, employees is the url and return json response to populate the select element from your Controller, so the required code for this (including javaScript) is given below:

$.post('/employees/'+$(this).val(), function(response){
    if(response.success)
    {
        var branchName = $('#branchname').empty();
        $.each(response.employees, function(i, employee){
            $('<option/>', {
                value:employee.id,
                text:employee.title
            }).appendTo(branchName);
        })
    }
}, 'json');

From the Controller you should send json_encoded data, for example:

public function getemployee($branch_no){
    $employees = employees::where("branch_no", $branch_no)->lists('title', 'id');
    return response()->json(['success' => true, 'employees' => $employees]);
}

Hope you got the idea.

Upvotes: 5

Vladimir Djukic
Vladimir Djukic

Reputation: 2072

Add in your route:

Route::post('employees', [
    'as' => 'employees', 'uses' => 'YourController@YourMethod'
]);

Ajax:

Change:
url: "employees"
to:
url: "/employees"

Upvotes: 0

Related Questions