4
votes

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 ..

4
Have you searched around at all? We're here to help, but you learn so much more by trying to do it yourself first! Just google ajax validation. Look at the results and try something - then you can come back with any trouble you have using an actual example of what you have tried.James
Sure I did .. but nothing what could suite my need... because everything I've found was just about submitting the form .. not the realtime validation .. I was googling for it for about 2days ... that's why I am asking here right nowMr.P
You are basically looking to write some jquery that checks for a .blur() event on the element you want to check. The blur element checks for when an element loses focus. When this happens you want to run your ajax call to check the value of what was typed. This is an example of it in action, just change the alert to an ajax call; w3schools.com/jquery/….James
yes, that's what I can do as well.. but what's not clear to me, how can I call db query from *.blade.php file ...Mr.P
Just get Ajax to post to a route that does this for you. E.g Ajax posts to a validate route, which you have defined in your routes to point to a function. Inside the function you run the validation query and return the result.James

4 Answers

4
votes

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

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

1
votes

Give your form an id:

<form action="../create_employee" method="POST" id="employee_form">     
    <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" id="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>

your js will look like this

$('#employee_form').submit(function(e){
    e.preventDefault();
    var first_name = $('#first_name');
    $.ajax({
        method: "POST",
        url: "checkUserExistence.php",
        data: { first_name: first_name }
    })
    .done(function( msg ) {
        if(msg == 'exist') {
            //employee exists, do something...
        } else {
            //employee does not exist, do something...
        }
    });
})  
1
votes

also add csrf_field in your form to generate token, and use this token while sending request. in your form:

 {{ csrf_field() }}

in your ajax request:

$.ajax({
        headers: {'X-CSRF-Token': $('input[name="_token"]').val()},
        //other data....        
 })

you can also do it with meta teg. in your head teg

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

in your request

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