Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 - ajax check if value exists in database

I am creating an employee hierarchy and while setting up the superior for new employee I would like to check if the employee already exists in database ... but :) I would like to do it with AJAX to know it realtime without sending the form ..

I have absolutely no idea how to do it, since I am a newbie to Laravel ..

                           ***UPDATED BASED ON ADVICES:***

I have a form in add_emp.blade.php:

<form action="../create_employee" method="POST">     
    <button class="button" type="submit" style="float:right"><span>Save</span></button>
    <div style="clear:both"></div>
    <fieldset>
      <legend>Personal data</legend>
        <label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />  
        <label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
        <label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br /> 
    </fieldset> 
</form>

Here is a script in add_employee.blade.php

<script type="text/javascript">
    $('#superior_list').blur(function(){

      var first_name = $('#superior_list');

      $.ajax({
        method: "POST",
        url: '/check_superior',
        data: { superior: superior }
      })
      .done(function( msg ) {
        if(msg == 'exist') {
           //employee exists, do something...
           alert( "good." );
        } else {
          //employee does not exist, do something... 
           alert( "bad." );
       }
      });
    })
</script>

route for handling the superior:

Route::post('check_superior', 'EmployeeController@check_superior'); 

This is the Controller function check_superior:

public function check_superior(Request\AjaxUserExistsRequest $request){ 

        if(Employee::where('superior','=',$request->input('superior'))->exists()){
           return "exist";
        }else{                                                                    
           return "not exist";
        }
}

But still not working ... can you advice where could be the issue?

                             *** FINAL SOLUTION ***

Form:

<form action="../create_employee" method="POST">     
    <button class="button" type="submit" style="float:right"><span>Save</span></button>
    <div style="clear:both"></div>
    <fieldset>
      <legend>Personal data</legend>
        <label for="first_name">First name:</label><input type="text" class="add_emp required" name="first_name" value="" /><br />  
        <label for="last_name">Last name:</label><input type="text" class="add_emp required" name="last_name" value="" /><br />
        <label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><span id="check-superior-status"></span><br />
    </fieldset> 
</form>

Add to app.blade.php

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

Controller

public function check_superior(Request $request){ 

            if(Employee::where('first_name','=',$request->input('superior_fname'))
                        ->where('last_name','=',$request->input('superior_lname'))
                        ->exists()){
               return "exist";
            }else{                                                                    
               return "not exist";
            }
    }

final emp.blade.php AJAX script

// place data after SEPERIOR selection
        $( "#superior_list" ).blur(function() {

                  var sup_list = $(this).val();
                  var sup_arr = sup_list.split(' ');
                  var superior_fname = sup_arr[0];  
                  var superior_lname = sup_arr[1];
                  var superior = superior_fname+" "+superior_lname;

                  // control print out
                  //$('#check-superior-status').text(superior);

                  // get real data 
                  $.ajax({  
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    method: "POST",
                    url: '/check_superior',
                    data: { superior_fname: superior_fname, superior_lname: superior_lname },
                    /* // debug only 
                    error: function(xhr, status, error){
                        $('#check-superior-status').text(xhr.responseText);
                    },
                    */
                    success: function(data){
                        $('#check-superior-status').text(data);
                    } 
                  })

        });

This works like a charm :) thank you guys .. hope this will help someone ..

like image 393
Mr.P Avatar asked Mar 11 '16 05:03

Mr.P


2 Answers

First make the request.

php artisan make:request AjaxUserExistsRequest

Then open the request file (App\Http\Requests) and find the following:

public function validate(){
    return [
        //rules
    ];
}

This is where you would stick your validation rules so you can check against the form elements being submit.

Then you should use dependency injection to force your request into the first argument of the user_exists() function:

public function user_exists(Requests\AjaxUserExistsRequest $request){
    return User::where('first_name', $request->first_name)->first();
}

This will return nullif no user exists, otherwise we don't care about the response.

Finally, of course we need our route.

Route::post('employee_exists', 'EmployeeController@user_exists');

Lastly, we'll go ahead and capture the form submit and check if the user exists with our jQuery.

$('#employee_form').submit(function(e){
    e.preventDefault();

    var first_name = $('#first_name').val(),
        $this = this; //aliased so we can use in ajax success function

    $.ajax({
        type: 'POST',
        url: '/employee_exists',
        data: {first_name: first_name},
        success: function(data){
           if(data == null){
               //then submit the form for real
               $this.submit; //doesn't fire our jQuery's submit() function
           } else {
               //show some type of message to the user
               alert('That user already exists!');
           }
        } 
    });
});
like image 67
Ohgodwhy Avatar answered Sep 28 '22 07:09

Ohgodwhy


The below will give alert message the user already exists! if the first_name exists in your db or it will give alret nothing.(if you want to check with superior change the code vice versa)

first make sure you have jquery.min.js in your public folder.

Now in blade.php add id for first_name, last_name, and superior as below:

<form action="../create_employee" method="POST">     
    <button class="button" type="submit" style="float:right"><span>Save</span></button>
    <div style="clear:both"></div>
    <fieldset>
      <legend>Personal data</legend>
        <label for="first_name">First name:</label><input type="text" id="first_name" class="add_emp required" name="first_name" value="" /><br />  
        <label for="last_name">Last name:</label><input type="text" id="last_name" class="add_emp required" name="last_name" value="" /><br />
        <label for="superior">Superior:</label><input type="text" class="add_emp" name="superior" value="" id="superior_list" /><br /> 
    </fieldset> 
</form>

<script>
$(document).ready(function(){
    $("#superior_list").blur(function(){
        var first_name = $('#first_name').val();
        var last_name = $('#last_name').val();
        var superior = $('#superior_list').val();                

        $.ajax({
                type: 'POST',
                url: '/check_superior',
                data: {first_name: first_name, last_name: last_name, superior: superior},
                success: function(data){
                   if(data == 0){
                       alert('nothing');
                   } else {
                       alert('the user already exists!');
                   }
                } 
            });

    });
});
</script>

and in your route.php

Route::post('/check_superior', array('as' => '', 'uses' => 'EmployeeController@check_superior'));

in EmployeeController.php

public function check_superior(){
    // can get last_name, superior like first_name below
    $first_name = Input::get('first_name');
    $data = YourModel::where('first_name',$first_name)->get();
    return count($data);
}

It should work. if it doesn't please show us your error

like image 34
m2j Avatar answered Sep 28 '22 09:09

m2j