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.





No comments:

Post a Comment