ralanyo's avatar

[Solved]Check if record exist with ajax post

I'm having trouble figuring out the best approach to checking if a record exists while using an ajax post. If the first name exist, i want it to kick open a modal that says, "Your already in this game". If it doesn't exist, I want it to insert the user into the database. I've got the controller to return a json response when the record exists, but i don't know how to get it to work conditionally in my jquery/view. Any help would be appreciated. Thanks in advance.

    public function store(Request $request) {
        
       $input = $request->all();
        if($request->ajax()){
            if (DB::table('tm_players')->where('fname', '=', $request->input('fName'))->exists())   {
                return response()->json(['success' => true, 'msg' => 'You are already in this game.']);
                }    else {      
        DB::table('tm_players')->insert([
            'fName'=>$input['fName'],
            'lName'=>$input['lName'],
            'created_at'=>Carbon::now()
    
            ]);
        }
        } 
    }//end store

Jquery

<script>

    
    $(document).ready(function() {
        var form = $('#checkin');
    $('form').on('submit', function (e) {  
        e.preventDefault();
        $.ajax({
           type: "POST",
           url: "/show_teams",
           data: form.serialize(),
           dataType: 'JSON',

           success: function(data) {
             //console.log(data.msg);
             //show success modal
             $('#myModal').modal('show');
             //hide success modal after  2k ms
             setTimeout(function(){
              $('#myModal').modal('hide')
            }, 2000);
           
           },
            error: function(e) {
                
            }
         });
        
         $("#checkin")[0].reset();
        });//end form submit
    });//end doc ready
</script>
0 likes
4 replies
ralanyo's avatar

Actually think i got this figured out. Is this the best way to do this?

 
           success: function(data) {
               if (data.msg){
                    //show already in modal
                 $('#alreadyModal').modal('show');
                 //hide success modal after  2k ms
                 setTimeout(function(){
                  $('#alreadyModal').modal('hide')
                }, 2000);
                
               } else {
               
                
                 //show success modal
                 $('#successModal').modal('show');
                 //hide success modal after  2k ms
                 setTimeout(function(){
                  $('#successModal').modal('hide')
                }, 2000);
                }//end else
           },//end success
Snapey's avatar
Snapey
Best Answer
Level 122

As well as msg how about returning an extra status 'created' = true or false.

public function store(Request $request)
{        
    $input = $request->all();
    if($request->ajax()){
        if (DB::table('tm_players')->where('fname', '=', $request->input('fName'))->exists())   {
            return response()->json(['success' => true, 'created'=> false, 'msg' => 'You are already in this game.']);
        } else {      
            DB::table('tm_players')->insert([
                'fName'=>$input['fName'],
                'lName'=>$input['lName'],
                'created_at'=>Carbon::now()
            ]);
            return response()->json(['success' => true, 'created'=> true, 'msg' => 'Welcome, new player.']);
        }
    } 
}//end store

Then you can test for this created in your javascript

ralanyo's avatar

@Snapey Thanks. That's a great idea. One thing I don't understand is the data in the Success function. I mean i got it to work using data.msg but i honestly don't understand what is in data or why its used. why can't i just use success: function(msg)?

 success: function(data) {
               if (data.msg){...

Is it coming from here in my ajax call?

data: form.serialize(),
Snapey's avatar

Its because jquery places the ajax call and then looks at the http response provided by the server.

this line success: function(data) is registering a callback for when the 200 (success) response is received. The callback accepts the json from the client and passes it to the callback in the data variable. So, data.msg is the msg element of the payload.

It could just as well say success: function(reply) and then msg would be reply.msg.

If you pass back a created element then this would be read with 'data.created'

Don't confuse success in your json data with success: in the jquery ajax object.

data: form.serialize() is wrapping up the browser form data to send in the ajax query, so again, nothing to do with the reply.

1 like

Please or to participate in this conversation.