Home > Software design >  How to check if a record already exists in a database before submitting the form using jQuery Larave
How to check if a record already exists in a database before submitting the form using jQuery Larave

Time:10-05

I'm having trouble figuring out the best approach to checking if a record exists while using an ajax. If the CNIC exists, I want to alert, "user already exists". If it doesn't exist, I want it to insert the form data into the database. I've got the jquery function that only submits data using ajax but I want to validate CNIC if it exists it gives an alert message. Any help would be appreciated. Thanks in advance.

** jquery **

$(document).ready(function() {
    $("#save1").on('click', function(e) {

        var cnic = $("#cnic").val();
         
        if (cnic == '') {
            alert("Kindly Enter CNIC");
            return false;
        }

        var gender = $("#gender").val();
        if (gender == '') {
            alert("Kindly Enter Gender");
            return false;
        }  
       
        var contactno = $("#contactno").val();
        if (contactno == '') {
            alert("Kindly Enter Contact No");
            return false;
        }

        var fname = $("#fname").val();
        if (fname == '') {
            alert("Kindly Enter Contact No");
            return false;
        }else{
            $.ajax({
                url: "/save",
                type: "get",
                data: $('#registrationform').serialize(),
                dataType: 'json',
                success: function(data) {
                    $("#patientid").val(data.patientid);
                    // console.log(data);
                }
            })
        }
        
    });
});


**

controller

**


<?php

namespace App\Http\Controllers;

use Haruncpi\LaravelIdGenerator\IdGenerator;

use Illuminate\Http\Request;
use App\Helpers\Helper;
use Illuminate\Support\Facades\DB;
use App\User;
use App\Models\patient;
use Illuminate\Support\Facades\Validator;

class Helpercontroller extends Controller
{

    function save(Request $request)
    {
        $temppatientId = IdGenerator::generate(['table' => 'patients', 'length' => 5, 'prefix' => 
        '22']);
        $patientid = $temppatientId   1;
        $query = new patient;
        $query->patientid = $patientid;
        $query->fname = $fname;
        $query->lname = $lname;
        $query->cnic = $cnic;
        $query->contactno = $contactno;
        $query->gender = $gender;
        $query->age = $age;
        $query->dob = $dob;
        $query->city = $city;
        $query->address = $address;
        $query->husbandname = $husbandname;
        $query->fathername = $fathername;
        $query->bloodgroup = $bloodgroup;
        $query->maritalstatus = $maritalstatus;
        

        $query->save();
        return $query;
    }


CodePudding user response:

Quick way to do it is to use Validation from Laravel.

public function save(Request $request)
{
   $validator = \Validator::make($request->all(), [
        // I suppose your table name is 'patients'
        'cnic' => 'required|unique:patients',
    ]);
    
    if ($validator->fails()) {
        // you can return a custom message if needed
        return response()->json(['success' => false, 'errors' => $validator->errors()->all()]);
    }

    // ... your actuel code to save data

    return response()->json(['success' => true, 'patient' => $query]);
}

And in your Ajax call:

$.ajax({
      url: "/save",
      type: "get",
      data: $('#registrationform').serialize(),
      dataType: 'json',
      success: function(data) {
          if (data.success === false) {
             alert('User already exist !');
          } else {
             $("#patientid").val(data.patient.patientid);
             // console.log(data.patient);
          }
      }
})

Respect cases of variables and don't use a GET method to POST a resource.

  • Related