Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Thursday, February 1, 2024

Select and Insert value from dropdown multiple, write and insert multiple values

 Hello. 

Today I want to show you how to select values from dropdown, Write or insert values from dropdown and save to database and manage it.




DB table name : maternal_disease

fields: mdid, cid, shortname, status, display, createdby, createdate, updatedby, updatedate

main php file code : 

<div class="col-sm-4">
                                        <input type="hidden" name="jobskillarray" id="jobskillarray" value="">
                                        <p id="jobskillmsg"></p>
                                        <div id="servicesList2" class="servicesList2"> </div>
                                        <input type="text" name="tag_name2" id="tag_name2" placeholder="Required Skills" list="skilllist2">
                                         
                                        <button type="button" class="btn btn-primary" id="addSkillBtn2">Add This Disease</button>
                                        <datalist id="skilllist2">
                                          <?php foreach ($maternalDiseaseList as $tag) { ?>
                                               <option ><?php echo $tag['shortname'] ?></option>
                                          <?php } ?>
                                        </datalist>
                                        
                                    </div>
<script type="text/javascript">
        $(document).ready(function() {
        var quotations = [];
        var quotations_id = [];
        $('#addSkillBtn2').click(function(e) {
          //debugger;
          var len = quotations_id.length;
          $("#jobskillmsg").html('');
          if (len < 15)
          {
              let tag_name2 = $('#tag_name2').val();
              let tagname2 = tag_name2.slice(0, 100);
              $("#skillMsg").html('');
              console.log(quotations);
              //console.log(quotations_id);
              //debugger
              var data = {};
              if ( tagname2.length >= 2 ){
                //if ($.inArray(tagname2, quotations) == 0) { 
                if ($.inArray(tagname2, quotations) >= 0) { 
                    console.log(quotations);
                } 
                else {
                  //console.log(quotations);
                  //console.log(quotations_id);
                  //debugger;
                  $.ajax({
                        url: 'ajax.php',
                        type: 'POST',
                        dataType: 'json',
                        data: {set_maternal_disease: tagname2},
                        //processData: false,
                        //contentType: false,
                        beforeSend: function(){
                              $('#mydiv').show();
                            },
                        success: function(response) {
                          $('#mydiv').hide();
                          //console.log(quotations);
                          //console.log(quotations_id);
                          //debugger;
                            if (response.message == 'success') {
                               var itemname = response.data.name;
                                var itemid = response.data.id;
                                    //console.log('Value Not exists');
                                    quotations.push(itemname);
                                    quotations_id.push(itemid);
                                    var item = document.createElement("p");
                                    var skillli = '<span class="skillable" data-value="'+response.data.id+'" data-name="'+response.data.name+'" id="js_'+response.data.id+'" ><label for="">'+response.data.name+'</label><i title="delete this skill" id="icon-minus2" class="red right icon-minus-sign"> x </i></span>';
                                    item.innerHTML = skillli;
                                    document.getElementsByClassName("servicesList2")[0].append(item);
                                    $('#tag_name2').val('');
                                  //console.log(quotations);console.log(quotations_id);
                                  $('#jobskillarray').val(quotations_id);
                               
                            } else if (response.message == 'duplicate') {
                              // setTimeout(function() {
                              //     $("#skillMsgDuplicate").hide('blind', {}, 500)
                              // }, 5000);
                               $("#skillMsg").html("<div class='col-md-12'><div class='alert alert-warning'><strong>Sorry! </strong> Duplicate skill cannot be added. </div> </div>");
                            } else if (response.message == 'limit') {
                              // setTimeout(function() {
                              //     $("#skillMsgLimit").hide('blind', {}, 500)
                              // }, 5000);
                              $("#skillMsg").html("<div class='col-md-12'><div class='alert alert-danger'><strong>Sorry! </strong> Maximum 5 skills are allowed. </div> </div>");
                            } else {
                              alert('Error! Try again or refresh page.');
                            }
                        },
                        error: function() {
                          $('#mydiv').hide();
                            alert('Error occurred while adding the skill.');
                        }
                  });
                  return false; 
                  } //end if check value exist
              }
          } 
          else
          { 
            $("#jobskillmsg").html("<div class='col-md-12'><div class='alert alert-danger'><strong>Sorry! </strong> Maximum 15 Disease are allowed. </div> </div>");
          }
          console.log(quotations);
          console.log(quotations_id);
        });
        //end skill to post ajax
        //remove jobpost skill by modal
        $(document).on('click','#icon-minus2',
        function() 
        {
          var y = quotations_id;
          //if (confirm("Are you sure?")) {
            var $list =  $("#servicesList");
            listValue = $(this).parent().data('value');
            listName = $(this).parent().data('name');
            //alert(listValue);
            if (listValue !== '') {
              $("p span#js_"+listValue).remove();
              quotations_id = jQuery.grep(quotations_id, function(value) {
                        return value != listValue;
                      });
              $('#jobskillarray').val(quotations_id);
              quotations = jQuery.grep(quotations, function(value) {
                        return value != listName;
                      });
              //console.log(quotations_id);
              //console.log(quotations);
            }
              
          //}         
        });
        //end
        });
    </script>


ajax.php

//display maternal disease
if(isset($_POST['set_maternal_disease'])){
    $id_edit = string_sanitize(trim($_POST['set_maternal_disease']));
    
    $userid = $_SESSION['userid'];
    $cid = $_SESSION['cid'];
    $createddate = date("Y-m-d H:i:s");
    $disease = mb_substr($id_edit, 0, 100);
    $sql = "SELECT shortname, mdid FROM `maternal_disease` WHERE `shortname` = '".$disease."' AND `cid` = '".$cid."' AND `status` = '1' AND `display` = '1' ";
    $myquery = mysqli_query($db_conx, $sql);
    if(mysqli_num_rows($myquery) == 1)
    {
        $row = mysqli_fetch_assoc($myquery);
        $mdid = $row['mdid'];
        $shortname = $row['shortname'];
    } elseif (mysqli_num_rows($myquery) == 0) {
        //insert data
        $sql = "INSERT INTO `maternal_disease` (`cid`, `shortname`, `createdby`, `createddate`) VALUES ('".$cid."', '".$disease."', '".$userid."', '".$createddate."')";
        $insertDisease = mysqli_query($db_conx, $sql);
        if ($insertDisease === TRUE){
            $mdid = mysqli_insert_id($db_conx);
            $shortname = $disease;
        }
    } else {
    }
    $responseData = [
                    'message' => 'success',
                    'data' => ['name'=> $shortname, 
                                'id' => $mdid
                                ],
                ];
    echo json_encode($responseData);
}

Wednesday, January 11, 2023

WordPress REST API Tutorial (Real Example)

 WordPress comes with a built-in (as in no plugins required) REST API. In this lesson we learn how to load and save content to/from the WordPress database on the fly using AJAX and the brand new REST API.

This is work only for admin login users.



1 : Open theme's functions.php file and paste these code.

//new code

    wp_enqueue_script( 'main_js', get_template_directory_uri() . '/rest/js/newcustom.js', NULL, '1.1', true );

    wp_localize_script('main_js', 'magicalData', array( 'nonce' => wp_create_nonce('wp_rest') )); 


2 : Create page-restapi.php in theme template path. put this code.

get_header(); ?>


    <div id="primary-mono" class="content-area col-md-12 page">

        <main id="main" class="site-main" role="main">


            <?php //if (current_user_can('administrator')) : ?>

            <div class="admin-quick-add">

                <h3>Quick Add Post</h3>

                <input type="text" name="title" placeholder="Title">

                <textarea name="content" placeholder="Content"></textarea>

                <button id="quick-add-button">Create Post</button>

            </div>

            <?php //endif; ?>



            <?php while ( have_posts() ) : the_post();?>

                <?php get_template_part( 'modules/content/content', 'page' ); ?>


                <?php

                // If comments are open or we have at least one comment, load up the comment template

                if ( comments_open() || get_comments_number() ) :

                    comments_template();

                endif;

                ?>


            <?php endwhile; // end of the loop. ?>

            <button  id="load-post-btn">Load Post</button>

            <div id="load_post_container"> </div>


        </main><!-- #main -->

    </div><!-- #primary -->


<?php get_footer(); ?>


3 : Create new js file in this theme path:/rest/js/newcustom.js

let load_post_btn = document.getElementById('load-post-btn');

var postcontainer = document.getElementById('load_post_container');


if (load_post_btn) {

load_post_btn.addEventListener("click", function(){

//console.log("clicked");

var ourRequest = new XMLHttpRequest();

// http://localhost/wordpress611/?rest_route=/wp/v2/posts

// http://localhost/wordpress611/wp-json/wp/v2/posts?categories=6&order=asc

ourRequest.open('GET', 'http://localhost/wordpress611/?rest_route=/wp/v2/posts');

ourRequest.onload = function() {

  if (ourRequest.status >= 200 && ourRequest.status < 400) {

    var data = JSON.parse(ourRequest.responseText);

    //console.log(data);

    createHTML(data)

  } else {

    console.log("We connected to the server, but it returned an error.");

  }

};


ourRequest.onerror = function() {

  console.log("Connection error");

};


ourRequest.send();


});

}


function createHTML(postsData) {

  var ourHTMLString = '';

  for (i = 0; i < postsData.length; i++) {

    ourHTMLString += '<h2>' + postsData[i].title.rendered + '</h2>';

    ourHTMLString += postsData[i].content.rendered;

  }

  postcontainer.innerHTML = ourHTMLString;

}


// Quick Add Post AJAX

var quickAddButton = document.querySelector("#quick-add-button");


if (quickAddButton) {

  quickAddButton.addEventListener("click", function() {

    var ourPostData = {

      "title": document.querySelector('.admin-quick-add [name="title"]').value,

      "content": document.querySelector('.admin-quick-add [name="content"]').value,

      "status": "publish"

    }


    var createPost = new XMLHttpRequest();

    var posturl = 'http://localhost/wordpress611/?rest_route=/wp/v2/posts';

    //createPost.open("POST", magicalData.siteURL + "/wp-json/wp/v2/posts");

    createPost.open("POST", posturl);

    createPost.setRequestHeader("X-WP-Nonce", magicalData.nonce);

    createPost.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

    createPost.send(JSON.stringify(ourPostData));

    createPost.onreadystatechange = function() {

      if (createPost.readyState == 4) {

        if (createPost.status == 201) {

          document.querySelector('.admin-quick-add [name="title"]').value = '';

          document.querySelector('.admin-quick-add [name="content"]').value = '';

        } else {

          alert("Error - try again.");

        }

      }

    }

  });

}

4: add css:-

/* Quick Add Form Styles */

.admin-quick-add {

background-color: #DDD;

padding: 15px;

margin-bottom: 15px;

}


.admin-quick-add input,

.admin-quick-add textarea {

width: 100%;

border: none;

padding: 10px;

margin: 0 0 10px 0;

box-sizing: border-box;

}





Tuesday, December 27, 2022

wordpress crud with file upload ajax frontend

Hello

Today I saw you crud  ajax operation with file upload in front side of wordpress website. Create a plugin for it, make shortcode and use it in wordpress page/post. 

Make file structure like this.




FILE : ajax-front.php

<?php

/*

Plugin Name: AJAX FRONT CRUD with media upload

Plugin URI: #

Description: A simple plugin that allows you to perform Create (INSERT), Read (SELECT), Update, Delete, File upload operations with ajax in FRONT SIDE.

Version: 1.0.0

Author: Chirag

Author URI: #

License: GPL2

*/

defined( 'ABSPATH' ) || exit;


/**

 * DEFINE PATHS

 */

global $wpdb;

define( 'MY_FRONT_CRUDURL', plugin_dir_url( __FILE__ ) );

define( 'MY_FRONT_CRUDPATH', plugin_dir_path( __FILE__ ));


//load css and js

function frontend_cssjs() {

  wp_register_style( 'customcss', MY_FRONT_CRUDURL.'/css/style.css', false, '1.0.0' );

  wp_enqueue_style( 'customcss' );


  wp_register_style('prefix_bootstrapcss', 'https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css');

  wp_enqueue_style('prefix_bootstrapcss');

  wp_register_script('prefix_bootstrapjs', 'https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js');

  wp_enqueue_script('prefix_bootstrapjs');


  wp_enqueue_script( 'my_jquery', MY_FRONT_CRUDURL. 'js/jQuery.min.js' );

  wp_enqueue_script( 'myjs', MY_FRONT_CRUDURL. 'js/crud.js' );

  wp_localize_script( 'myjs', 'ajax_var', array( 'ajaxurl' => admin_url('admin-ajax.php') ));


// Enqueue WordPress media scripts

    //wp_enqueue_media();

    // Enqueue custom script that will interact with wp.media

    //wp_enqueue_script( 'myprefix_script', plugins_url( '/js/myscript.js' , __FILE__ ), array('jquery'), '0.1' );

}

add_action('wp_enqueue_scripts','frontend_cssjs');




function pwwp_enqueue_my_scripts() {

    // jQuery is stated as a dependancy of bootstrap-js - it will be loaded by WordPress before the BS scripts 

    wp_enqueue_script( 'bootstrap-js', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js', array('jquery'), true); // all the bootstrap javascript goodness

}

add_action('wp_enqueue_scripts', 'pwwp_enqueue_my_scripts');


function pwwp_enqueue_my_styles() {

    wp_enqueue_style( 'bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' );


    // this will add the stylesheet from it's default theme location if your theme doesn't already

    //wp_enqueue_style( 'my-style', get_template_directory_uri() . '/style.css');

}

add_action('wp_enqueue_scripts', 'pwwp_enqueue_my_styles');





//activation hook

register_activation_hook( __FILE__, 'createfrontcrud');

function createfrontcrud() {

  global $wpdb;

  $charset_collate = $wpdb->get_charset_collate();

  $table_name = $wpdb->prefix . 'crudfront';

  $sql = "CREATE TABLE `$table_name` (

    `user_id` int(11) NOT NULL AUTO_INCREMENT,

    `name` varchar(220) DEFAULT NULL,

    `email` varchar(220) DEFAULT NULL,

    `filepath` varchar(256) DEFAULT NULL,

    PRIMARY KEY(user_id)

    ) ENGINE=MyISAM DEFAULT CHARSET=latin1;

    ";

  if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {

    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');

    dbDelta($sql);

  }

}


require_once(MY_FRONT_CRUDPATH.'/ajax_action.php');



//[frontend_crud]

//add_shortcode('frontendcrudnew','front_crud_file');

function register_shortcodes(){

   add_shortcode('frontendcrudnew', 'front_crud_file');

}

add_action( 'init', 'register_shortcodes');


//display data

function front_crud_file(){ 

html_addbuton();

html_display_data();

edit_data();

}



function html_addbuton(){ ?>

<!-- Button trigger modal -->

<div class="">

  <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">

    Insert Data

  </button>

  <div id="msg"></div>

</div>

<!-- Modal -->

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">

  <div class="modal-dialog" role="document">

    <div class="modal-content">

      <div class="modal-header">

        <h4 class="modal-title" id="myModalLabel">Add page for under construction</h4>

        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

      </div>

      <div class="modal-body">

          <div class="wqsubmit_message"></div>


          <form name="insertform" id="insertform" enctype="multipart/form-data">

            <table>

              <tbody>

                <tr>

                  <td><input type="text" value="AUTO_GENERATED" disabled></td>

                </tr>

                <tr>

                  <td><input type="text" id="newname" name="newname" placeholder="Name Here"></td>

                </tr>

                <tr>

                  <td><input type="text" id="newemail" name="newemail" placeholder="Email ID Here"></td>

                </tr>

                <tr>

<td>

<input type="file" name="file1" id="file1">

</td>

                </tr>

              </tbody>

            </table>

          

        </form>


      </div>

      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="btn btn-primary" id="savedata" name="savedata" >Insert Data</button>

        <!-- <div><input type="submit" class="btn btn-primary wqsubmit_button" id="wqadd" value="Add" /></div> -->

        

        <!-- <input type="submit" id="savedata" name="savedata" class="button button-primary" value="Save Data"> -->

      </div>

    </div>

  </div>

</div>

<!-- END Modal -->

<?php

}


function html_display_data(){

?>

<div class="wrap">

    <h2>DATA FRONTEND ALL</h2>

    <table class="wp-list-table widefat striped">

      <thead>

        <tr>

          <th width="5%">User ID</th>

          <th width="20%">Name</th>

          <th width="20%">Email Address</th>

          <th width="45%">Image</th>

          <th width="10%">Actions</th>

        </tr>

      </thead>

      <tbody>

        

        <?php

        global $wpdb;

        $table_name = $wpdb->prefix . 'crudfront';

          $result = $wpdb->get_results("SELECT * FROM $table_name");

          //print_r($result);

          $rowcount = count((array)$result);

          //echo "c:".$rowcount;

          //echo $last_query = $wpdb->last_query;

          if ($rowcount == 0) {

            echo "<tr> <td colspan='5'>No data found! </td></tr>";

          } else { 

            foreach ($result as $print) {

              ?>

                <tr id="user_<?php echo $print->user_id; ?>">

                  <td width='5%' id=""><?php echo $print->user_id; ?></td>

                  <td width='20%' id="inputUsername_<?php echo $print->user_id; ?>"><?php echo $print->name; ?></td>

                  <td width='20%' id="inputUserEmail_<?php echo $print->user_id; ?>"><?php echo $print->email; ?></td>

                  <td width='45%'> <img id="inputUserFile_<?php echo $print->user_id; ?>" height="250px" width="250px" src="<?php echo $print->filepath; ?>" alt=""> </td>

                  <td width='10%'>

                    <form name="formaction_<?php echo $print->user_id; ?>" id="formaction_<?php echo $print->user_id; ?>">

                      <input type="hidden" name="userid_delete" id="userid_delete" value="<?php echo $print->user_id; ?>">

                    <!-- <a href='admin.php?page=crud%2Fcrud.php&upt=$print->user_id'>

                      <button type='button'>UPDATE</button>

                    </a>  -->

                    <a href="#edit_user" class="open-edit_user" data-toggle="modal" data-user_id="<?php echo $print->user_id; ?>" onclick="goDoSomething(this);"> 

                      <span class="glyphicon glyphicon-edit">EDIT</span> 

                    </a>

                    <!-- <a href='admin.php?page=crud%2Fcrud.php&del=$print->user_id'> -->

                      <button type='button' data-user_id="<?php echo $print->user_id; ?>" onclick="DeleteData(this);">DELETE</button>

                    <!-- </a> -->

                  </form>

                  </td>

                </tr>

              

           <?php }

          }

        ?>

      </tbody>  

    </table>

    <br>

    <br>

    

  </div>

<?php

}


function edit_data(){

?>

<div class="modal fade" id="edit_user" role="dialog"> 

  <div class="modal-dialog">   

    <div class="modal-content"> 

      <div class="modal-header">   

        <h4 class="modal-title">

          <b>User Registration EDIT Form</b>

          <span id="uid"> </span>

        </h4> 

        <button type="button" class="close" data-dismiss="modal">&times;</button>   

      </div> 

      <div class="modal-body">   

        <div class="fetched_user"></div> 

        <div class="wqsubmit_message1"></div>


          <form name="editform" id="editform">

            <table>

              <tbody>

                <tr>

                  <td><input id="userid_input" type="text" value="" disabled>

                      <input type="hidden" name="userid" id="userid" value="">

                  </td>

                </tr>

                <tr>

                  <td><input type="text" id="editnewname" name="editnewname" placeholder="Name Here"></td>

                </tr>

                <tr>

                  <td><input type="text" id="editnewemail" name="editnewemail" placeholder="Email ID Here"></td>

                </tr>

                <tr>

<td>

<img src="" id="editfile" name="editfile" width="250px" height="250px">

<input type="hidden" id="editfile_hidden" name="editfile_hidden" value="">

<input type="file" name="fileedit" id="fileedit" value="">

</td>

                </tr>

              </tbody>

            </table>

          

          </form>

      </div> 

      <div class="modal-footer">

        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

        <button type="button" class="btn btn-primary" id="updatedata" name="updatedata" >Update Data</button>

      </div> 

    </div>

  </div>

</div> <!--Edit Modal close-->

<?php

}


//deactive plugin

register_deactivation_hook( __FILE__, 'deactivate_crudfunction' );

function deactivate_crudfunction(){

global $wpdb;

  $table_name = $wpdb->prefix . 'crudfront';

  $sql = "DROP TABLE IF EXISTS $table_name";

  $wpdb->query($sql);

}


FILE : ajax_action.php

<?php
add_action('wp_ajax_ajaxfrontend','ajax_front_insert');
add_action('wp_ajax_nopriv_ajaxfrontend','ajax_front_insert');

function ajax_front_insert() {
  global $wpdb;
  //print_r($_POST); print_r($_FILES['file']); exit;
  $table_name = $wpdb->prefix . 'crudfront';
  //echo $filename=$_FILES['file1']['name']; exit();

  //file upload

  if (isset($_FILES['file1'] ) && !empty($_FILES['file1']['name']) ){
    $allowedExts = array("jpeg", "jpg", "png", "bmp", "gif");
    $temp = explode(".", $_FILES["file1"]["name"]);
    $extension = end($temp);
    if ( in_array($extension, $allowedExts)){
       if ( ($_FILES["file1"]["error"] > 0) && ($_FILES['file1']['size'] <= 3145728 ))
        {
            $response = array(
                "status" => 'error',
                "message" => 'ERROR Return Code: '. $_FILES["file1"]["error"],
                );
        }
        else{
          $uploadedfile = $_FILES['file1'];
          $upload_name = $_FILES['file1']['name'];
          $tempname = $_FILES["file1"]["tmp_name"];
          //$uploads = wp_upload_dir();
          //$filepath = $uploads['path']."/$upload_name";
          $filepath = MY_FRONT_CRUDPATH."imgs/$upload_name";
          if ( ! function_exists( 'wp_handle_upload' ) )
          {
              require_once( ABSPATH . 'wp-admin/includes/file.php' );
          }
          require_once( ABSPATH . 'wp-admin/includes/image.php' );
          $upload_overrides = array( 'test_form' => false );
          $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); // default wordpress file upload
          //$movefile = wp_upload_bits($uploadedfile, null, file_get_contents($_FILES["file1"]["tmp_name"]));
          //$movefile = move_uploaded_file($tempname,$filepath);
          if ( $movefile && !isset( $movefile['error'] )  ) {
              $file = $movefile['file'];
              $url = $movefile['url'];
              $type = $movefile['type'];

              $attachment = array(
                  'post_mime_type' => $type ,
                  'post_title' => $upload_name,
                  'post_content' => 'File '.$upload_name,
                  'post_status' => 'inherit'
                  );

              $attach_id=wp_insert_attachment( $attachment, $file, 0);
              $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
              wp_update_attachment_metadata( $attach_id, $attach_data );
          }
          $response = array(
            "status" => 'success',
            "url" => $url
          );


        }

    }
    else
    {
        $response = array(
            "status" => 'error',
            "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
            );
    }
  } else {
    // no file uploaded {"status":"success","url":"http:\/\/localhost\/wordpress63\/wp-content\/uploads\/2022\/12\/blue-smart-watch-1.jpg"} Data Has Inserted Successfully

    $upload_name = '';
    
  }
  //print json_encode($response);
  //exit;
  //end file upload
  $sql = "SELECT * FROM `$table_name` WHERE `name` = '".$_POST['newname']."' AND `email` = '".$_POST['newemail']."' ORDER BY `user_id` DESC" ;
  //echo $sql;
  $wpdb->get_row($sql);
  if($wpdb->num_rows < 1) {
    $query = $wpdb->insert($table_name , array(
      "name" => $_POST['newname'],
      "email" => $_POST['newemail'],
      "filepath" => $url
    ));

    $last_query = $wpdb->last_query;
    if ($query == true) {
      //$response = array('message'=>'Data Has Inserted Successfully', 'rescode'=>200);
      $response = '<span class="alert alert-success"> Data Has Inserted Successfully </span>';
    } else {
       $response = '<span class="alert alert-danger"> Data Not Saved </span>';
    }
    
  } else {
    $response = '<span class="alert alert-info"> Data Has Already Exist </span>';
  }
  echo $response;
  exit();
  wp_die();
}



add_action('wp_ajax_edituserdata','ajaxEditData');
add_action('wp_ajax_nopriv_edituserdata','ajaxEditData');

function ajaxEditData() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'crudfront';
  $wpdb->get_row( "SELECT * FROM `$table_name` WHERE `name` = '".$_POST['editnewname']."' AND `email` = '".$_POST['editnewemail']."' AND `user_id`!='".$_POST['userid']."' " );
  if($wpdb->num_rows < 1) {

    //file upload
    if (isset($_FILES['fileedit'] ) && !empty($_FILES['fileedit']['name']) ){
      $allowedExts = array("jpeg", "jpg", "png", "bmp", "gif");
      $temp = explode(".", $_FILES["fileedit"]["name"]);
      $extension = end($temp);
      if ( in_array($extension, $allowedExts)){
         if ( ($_FILES["fileedit"]["error"] > 0) && ($_FILES['fileedit']['size'] <= 3145728 ))
          {
              $response = array(
                  "status" => 'error',
                  "message" => 'ERROR Return Code: '. $_FILES["fileedit"]["error"],
                  );
          }
          else{
            $uploadedfile = $_FILES['fileedit'];
            $upload_name = $_FILES['fileedit']['name'];
            $tempname = $_FILES["fileedit"]["tmp_name"];
            //$uploads = wp_upload_dir();
            //$filepath = $uploads['path']."/$upload_name";
            $filepath = MY_FRONT_CRUDPATH."imgs/$upload_name";
            if ( ! function_exists( 'wp_handle_upload' ) )
            {
                require_once( ABSPATH . 'wp-admin/includes/file.php' );
            }
            require_once( ABSPATH . 'wp-admin/includes/image.php' );
            $upload_overrides = array( 'test_form' => false );
            $movefile = wp_handle_upload( $uploadedfile, $upload_overrides ); // default wordpress file upload
            //$movefile = wp_upload_bits($uploadedfile, null, file_get_contents($_FILES["file1"]["tmp_name"]));
            //$movefile = move_uploaded_file($tempname,$filepath);
            if ( $movefile && !isset( $movefile['error'] )  ) {
                $file = $movefile['file'];
                $url = $movefile['url'];
                $type = $movefile['type'];

                $attachment = array(
                    'post_mime_type' => $type ,
                    'post_title' => $upload_name,
                    'post_content' => 'File '.$upload_name,
                    'post_status' => 'inherit'
                    );

                $attach_id=wp_insert_attachment( $attachment, $file, 0);
                $attach_data = wp_generate_attachment_metadata( $attach_id, $file );
                wp_update_attachment_metadata( $attach_id, $attach_data );
            }
            $response = array(
              "status" => 'success',
              "url" => $url
            );


          }

      }
      else
      {
          $response = array(
              "status" => 'error',
              "message" => 'something went wrong, most likely file is to large for upload. check upload_max_filesize, post_max_size and memory_limit in you php.ini',
              );
      }
    } else {
      // no file uploaded {"status":"success","url":"http:\/\/localhost\/wordpress63\/wp-content\/uploads\/2022\/12\/blue-smart-watch-1.jpg"} Data Has Inserted Successfully
      //$upload_name = $_POST['editfile_hidden'];
      $url = $_POST['editfile_hidden'];
    }

    $updatedata = $wpdb->update( $table_name, array(
      "name" => $_POST['editnewname'],
      "email" => $_POST['editnewemail'],
      "filepath" => $url
      //"updated_at" => time()
    ), array('user_id' => $_POST['userid']) );

    //echo $last_query = $wpdb->last_query;

    if ($updatedata == true) {
      //$response = array('message'=>'Data Has Updated Successfully', 'rescode'=>200);
      $response = '<span class="alert alert-success"> Data Has Updated Successfully </span>';
    } else {
      $response = '<span class="alert alert-danger"> Data Not Saved </span>';
    }


    
  } else {
    //$response = array('message'=>'Data Has Already Exist', 'rescode'=>404);
    $response = '<span class="alert alert-warning"> Data Has Already Same! </span>';
  }
  //echo json_encode($response);
  echo $response;
  exit();
  wp_die();
}


add_action('wp_ajax_delete_data','wqedit_entry_delete_data');
add_action('wp_ajax_nopriv_delete_data','wqedit_entry_delete_data');
function wqedit_entry_delete_data() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'crudfront'; 
  //$_POST['editnewname'];
  //print_r($_POST); exit(); 
  $userid_delete = $_POST['userid_delete'];
  $query = $wpdb->delete( $table_name, array( 'user_id' => $userid_delete ) );
  //echo $last_query = $wpdb->last_query;
  if ($query == true) {
    $response = "1";
  } else {
    $response = "2";
  }
  echo $response;
  exit();
  wp_die();
}

FILE : css/style.css


.wqmessage {
  color: red;
  font-size: 16px;
}
.wqsubmit_message {
  font-size: 16px;
}
.wqtextfield {
  width: 100%;
  padding: 15px;
  border: 1px solid #ccc;
  border-radius: 8px;
}
.wqsubmit_button {
  background-color: lightseagreen;
  border: none;
  color: white;
  padding: 10px;
  cursor: pointer;
  border-radius: 8px;
  width: 100%;
}
.wqlabel {
  font-size: 20px;
  margin-bottom: 10px;
}
.wqpage_heading {
  font-size: 25px;
  text-align: center;
}

#insertform {
    float: left;
    padding-top: 20px;
}
.wqsubmit_message{padding: 10px;}


FILE: js/crud.js

jQuery(document).ready(function(){
   //$(document).on('submit','#insertform', function(e) {
   jQuery("#savedata").click( function(e) {
    e.preventDefault();
    //alert('aaya');
    $('.wqmessage').html('');
    $('.wqsubmit_message').html('');

      var newname = $('#newname').val();
      var newemail = $('#newemail').val();

      var regex = /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
      if(regex.test(newemail)){
       var emailcheck = true;
      }
      else{
       var emailcheck = false;
      }


    if(newname != '' && emailcheck == true) {
      var fd = new FormData(document.getElementById("insertform"));
      //var fd = new FormData(this);
      var action = 'ajaxfrontend';
      fd.append("action", action);

      //var form_data =jQuery('#insertform').serializeArray();
      //console.log(form_data);


      $.ajax({
        data: fd,
        //data: {action: "wqnew_entry", newname : newname, newemail: newemail},
        type: 'POST',
        url: ajax_var.ajaxurl,
        contentType: false,
           cache: false,
           processData:false,
        success: function(response) {
         //var res = JSON.stringify(response);
          //var res = JSON.parse(res);
          $('.wqsubmit_message').html(response);
          // if(res.rescode!='404') {
          //   $('#insertform')[0].reset();
          //   $('.wqsubmit_message').css('color','green');
          // } else {
          //   $('.wqsubmit_message').css('color','red');
          // }
          setTimeout(function() { location.reload(); }, 3500);
          //$(".entry-content").load("../showdata.php");
        }
      });
    } else {
      return false;
    }
  });



   //update data
   jQuery("#updatedata").click( function(e) {
      e.preventDefault();
      $('.wqmessage').html('');
      $('.wqsubmit_message1').html('');
      var userid = $('#userid').val();
      var editnewname = $('#editnewname').val();
      var editnewemail = $('#editnewemail').val();

      var regex = /^([_\-\.0-9a-zA-Z]+)@([_\-\.0-9a-zA-Z]+)\.([a-zA-Z]){2,7}$/;
      if(regex.test(editnewemail)){
       var emailcheck = true;
      }
      else{
       var emailcheck = false;
      }

      if(newname != '' && emailcheck == true) { 
        var fd = new FormData(document.getElementById("editform"));
        var action = 'edituserdata';
        fd.append("action", action);
//debugger;
        $.ajax({
          data: fd,
          type: 'POST',
          url: ajax_var.ajaxurl,
          contentType: false,
             cache: false,
             processData:false,
          success: function(response) {
            $('.wqsubmit_message1').html(response);
            setTimeout(function() { location.reload(); }, 3500);
          }
        });        
      }
      else {
        return false;
      }
   });

  });

function goDoSomething(d){     
    var uid = d.getAttribute("data-user_id");
    var username = $("#inputUsername_"+uid).text();
    var emailid = $("#inputUserEmail_"+uid).text();
    var filesrc = $("#inputUserFile_"+uid).attr('src');
    $("#userid_input").val(uid); 
    $("#userid").val(uid); 
    $("#editnewname").val(username);
    $("#editnewemail").val(emailid);
    //$('#editfile').attr('src','');
    $('#editfile').attr('src',filesrc);
    $('#editfile_hidden').val(filesrc);
}

//delete data
function DeleteData(d){ 
  var uid = d.getAttribute("data-user_id");
  //alert(uid);
  if (confirm('Are you sure ?')) {
        //$(this).prev('span.text').remove();
      //alert(uid);
    $('#msg').html('');
    var fd = new FormData(document.getElementById("formaction_"+uid));
    var action = 'delete_data';
    fd.append("action", action);
    $.ajax({
          data: fd,
          type: 'POST',
          url: ajax_var.ajaxurl,
          contentType: false,
             cache: false,
             processData:false,
          success: function(res) {
            $('#msg').html('<span class="alert alert-success"> Data Has DELETED Successfully </span>');
            $('#user_'+uid).remove();
            //setTimeout(function() { location.reload(); }, 4000);
          }
    });
  }
}

Now go to wp-admin area. open any page/post. Paste this shortcode to this : 
[frontendcrudnew]


These are some screenshots.