How to check if a record already exists in a database before submitting the form using jQuery Laravel

user19704437

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;
    }


Vincent Decaux

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to check if a record with composite key already exists in mysql database before inserting it using Dapper in C#

Check if the value already exists in the database using Laravel

Check if record exists before submitting new

How do I check if the record already exists in SQL database?

How to check if my data already exists in my database before creating?

Properly check if a record already exists in a database

How to check if database already exists

Check if record exists before adding it to the database

How to check if a particular database in mysql already exists using java

How to check if a key already exists in the database using Firebase and Python?

How to check if mail already exists in database when using updateProfile () function

Laravel: Check if record exists Before Insertion

How do I check users email isn't already in my database when submitting a form?

How to check if object value in array already exists using jquery

Confirmation before submitting form using jQuery

Check if database already exists

How to check if .realm database already exists?

How to check if the email already exists in database

How to check if token already exists in database table

laravel updating editing database record - getting error when submitting the form

How to check the data already exists or not laravel

Check if a record exists in the database

How in Sinatra would I check that the term the user has input into a form already exists in your database?

How to check if record with given ID already exists using EF5 and repository

How do I avoid "record already exists" form validation error using ModelForms in Django 1.6?

How to check if a database exists before creating a table?

Check if hasMany Relationship Exists in Laravel 8 Before Deleting Record

How to check calculation answer of 2 input fields before submitting form

How to check if a folder exists before creating it in laravel?

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive