Jquery Set Custom Data Attribute Value Example

Hii guys,

In this artical, we will learn how to get custom attribute value in jquery and how to set custom attribute value in jquery. we will use attr() and data() for getting custom attribute value and set custom attribute value in js.

We can easily set data attribute value in jquery, also you can do it same thing with custom attribute value in jquery.

Example 1:

First Example Using jquery data() function


<!DOCTYPE html>
<html>
<head>
    <title>Jquery Set custom data attribute value</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
  
<div id="example1">Click Here:</div><br>
<button class="set-attr">Set Attribute</button>

<script type="text/javascript">
 
$(".set-attr").click(function(){
    $("#example1").data('my-name', 'nicesnippets');

    var name = $("#example1").data('my-name');
    alert(name);
});
  
</script>
  
</body>
</html>
Example 2:

Second Example Using jquery attr() function

<!DOCTYPE html>
<html>
<head>
    <title>Jquery Set custom data attribute value</title>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
  
<div id="example1">Click Here:</div><br>
<button class="set-attr">Set Attribute</button>

<script type="text/javascript">
 
$(".set-attr").click(function(){
    $("#example1").attr('my-name', 'nicesnippets');

    var name = $("#example1").attr('my-name');
    alert(name);
});
  
</script>
  
</body>
</html>

It will help you...

Laravel 8 Multiple Image Upload Example

Hi Guys,

In this tutorial, I will learn you how to create multiple image upload in laravel 8. We will show example of laravel 8 multiple image upload.Here you will learn laravel 8 multiple images upload. We will look at example of multiple image upload laravel 8. this example will help you laravel 8 multiple image upload with preview. Alright, let’s dive into the steps.

I will create simple multiple image upload in laravel 8. So you basically use this code on your laravel 8 application.I are going from starch so, we will upload multiple file and store on server then after we will store database too. so in this example we will create "files" table using laravel migration and write code for route, controller and view step by step.

Here, I will give you full example for laravel 8 multiple image upload as bellow.

Step-1:Download Laravel 8 Fresh New Setup

First, we need to download the laravel fresh setup. Use the below command and download fresh new laravel setup :

composer create-project --prefer-dist laravel/laravel blog
Step 2: Add Migration and Model

Here, we need create database migration for files table and also we will create model for files table.

php artisan make:migration create_files_table
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateFilesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('files', function (Blueprint $table) {
            $table->id();
            $table->string('files');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('files');
    }
}
php artisan migrate

Next I will create File model by using following command:

php artisan make:model File
app/Models/File.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class File extends Model
{
    use HasFactory;

    protected $fillable = [
        'files'
    ];
}
Step 3: Create Routes

In next step, we will create routes for multiple file upload. so create two route with GET and POST route example.

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\MultipleFileUploadController;
  
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// MultipleFileUploadController
Route::get('/multiple-file-upload', [MultipleFileUploadController::class, 'index'])->name('multiple.file.upload.index');
Route::post('/multiple-file-upload/store', [MultipleFileUploadController::class, 'store'])->name('multiple.file.upload.store');
Step 4: Create Controller

Here I require to add new MultipleFileUploadController controller for manage route So let's create MultipleFileUploadController with create and store method. Make sure you need to create "files" folder in your public directory.

app/Http/Controllers/MultipleFileUploadController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\File;

class MultipleFileUploadController extends Controller
{
    public function index()
    {
      return view('multipleFileUpload');
    }

    public function store(Request $request)
    {
      $this->validate($request, [
            'files' => 'required'
        ]);
  
        $files = [];
        if($request->hasfile('files')){
          foreach($request->file('files') as $file){
              $name = time().rand(1,100).'.'.$file->extension();
              $file->move(public_path('files'), $name);  
              $files[] = $name;  
          }
      }

    File::create(['files' => json_encode($files)]);
  
        return back()->with('success', 'Files uploaded successfully');
    }
}
Store Image in Storage Folder
$request->image->storeAs('images', $imageName);
// storage/app/images/file.png
Store Image in Public Folder
$request->image->move(public_path('images'), $imageName);
// public/images/file.png
Store Image in S3
$request->image->storeAs('images', $imageName, 's3');
Step 5: Create Blade File

in this step we need to create multipleFileUpload.blade.php file in resources folder. So let's multipleFileUpload file:

resources/views/multipleFileUpload.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>Laravel 8 Multiple File Upload</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha256-NuCn4IvuZXdBaFKJOAcsU2Q3ZpwbdFisd5dux4jkQ5w=" crossorigin="anonymous" />
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-6 offset-3 mt-5">
            <div class="card mt-5">
                <div class="card-header text-center bg-primary">
                    <h2 class="text-white"> <strong>Multiple File Upload</strong></h2>
                </div>
                <div class="card-body">
                  @if ($message = Session::get('success'))
                 <div class="alert alert-success alert-block">
                    <button type="button" class="close"   data-dismiss="alert">×</button>
                      <strong>{{ $message }}</strong>
                  </div>
                @endif
                    @if (count($errors) > 0)
                        <ul class="alert alert-danger pl-5">
                          @foreach($errors->all() as $error)
                             <li>{{ $error }}</li> 
                          @endforeach
                        </ul>
                    @endif
                    <form method="post" action="{{ route('multiple.file.upload.store') }}" enctype="multipart/form-data">
              @csrf
              <div class="input-group file-div control-group lst increment" >
                <input type="file" name="files[]" class="myfrm form-control">
                <div class="input-group-btn"> 
                  <button class="btn btn-success add-btn" type="button"><i class="fldemo fa fa-plus"></i></button>
                </div>
              </div>
              <div class="clone hide">
                <div class="file-div control-group lst input-group" style="margin-top:10px">
                  <input type="file" name="files[]" class="myfrm form-control">
                  <div class="input-group-btn"> 
                    <button class="btn btn-danger" type="button"><i class="fldemo fa fa-close"></i></button>
                  </div>
                </div>
              </div>
              <div class="row">
                <div class="col-md-12 text-center mt-4">
                  <button type="submit" class="btn btn-success rounded-0"><i class="fa fa-save"></i> Save</button>
                </div>
              </div>
          </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(document).ready(function() {
      $(".add-btn").click(function(){
          var lsthmtl = $(".clone").html();
          $(".increment").after(lsthmtl);
      });
      $("body").on("click",".btn-danger",function(){
          $(this).parents(".file-div").remove();
      });
    });
</script>
</body>
</html>

Now we are ready to run our custom validation rules example so run bellow command for quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/multiple-file-upload

It Will help you...

PHP Remove Extension From a Filename with Tutorial

Hi guys,

In this blog, i will explain how to remove extension from a filename.If you’ve got a filename that you need to remove the extension from with PHP.We will show remove extension from a filename. i will using pathinfo(), basename(),etc different function to remove file name extension.

Here following the remove extension from a filename exmaple.

Solution 1: Using pathinfo()

Now in this exmaple, The pathinfo() function returns an array containing the directory name, basename, extension and filename.Alternatively, you can pass it one of the PATHINFO_ constants and just return that part of the full filename.

$fileName = 'itwebtutsFileName.html';
$withOutExtension = pathinfo($fileName, PATHINFO_FILENAME);
output
itwebtutsFileName
Solution 2: Using basename()

Here in this exmaple, If the extension is known and is the same for the all the filenames, you can pass the second optional parameter to basename() to tell it to strip that extension from the filename.

$fileName = 'itwebtutsFileName.html';
$withOutExtension = basename($fileName, '.html');
output
itwebtutsFileName
Solution 3: Using substr() and strrpos()

Blow in this exmaple, If the filename contains a full path, then the full path and filename without the extension is returned. You could basename() it as well to get rid of the path if needed (e.g. basename(substr($filename, 0, strrpos($filename, ".")))) although it’s slower than using pathinfo.

$fileName = 'itwebtutsFileName.html';
$withOutExtension = substr($fileName, 0, strrpos($fileName, "."));
output
itwebtutsFileName

It will help you...

PHP Pagination with MySQL and Bootstrap Tutorial

Hi Guys,

In this blog, I will learn you PHP pagination PHP is mostly used to store and display data from a database. Pagination can be done with ajax, but here this is done with non-ajax. In this tutorial, we will learn the pagination in PHP with MySQL. Let's take a brief review about pagination with an example -

It is possible that a SQL SELECT query may returns millions of records back. It is not a good idea to display all records on a single page. A large list of records on a single page may take so much time to load the page and also consume time to find specific data. This may cause (leads to) the confusion in user's mind. Therefore, divide these records over several pages according to the user requirement.

So, what can we do to distribute these large number of records in number of pages? The method of distributing a single list into multiple pages is known as Pagination. Paging refers to showing your query result on multiple pages instead of a single page.

What is Pagination?

Pagination is a way of showing the data on multiple pages rather than putting them to a single page. Pagination avails to divide the records onto several pages, which makes the data more readable and understandable.

Pagination is a prevalent task for PHP developers. MySQL avails the developer to engender pagination by utilizing LIMIT clause, which takes two arguments. The first argument as OFFSET and the second argument is number of records that will return from database.

Let's look at some advantages and disadvantages of using pagination concept in PHP -

Advantages of Pagination
  • Pagination is very useful in astronomically immense scale projects because it makes the webwork more professional. Not only more professional, but it additionally makes the webpage work much more expeditious, precise, and efficient.
  • With the help of pagination, we can save the loading time of a page by dividing the data on various pages. It saves us from loading a lot of information at once. For Example - A webpage with 1000 images will take more time to load images than the 50 images on each webpage. This means that thousands of images need thousands of HTTP requests, which would make the page unresponsive. This problem is resolved by limiting the amount of data with the help of pagination using LIMIT clause.
  • The use of pagination improves the user experience, advertising revenue, and decrease the loading time of the page.
Disadvantages of Pagination

While there are some powerful advantages of pagination, but still many developers avoid to use it. Along with some powerful advantages, there are few disadvantages of pagination as well, which are as follows:

  • Pagination itself is a big overhead in PHP, which is one of the disadvantages of pagination. It is completely an overhead as it is an external feature that can be implemented to the cost of extraneous Markup, Styling, and logic. A small dataset often ignored to use pagination.
  • Pagination may cause of low page rank on search engine because when a page is away from the home page and requires several clicks, it usually does not get a high page rank.
  • It also limits the number links, social shares, total number of results to visible on the webpage, and anchor text that a page receives when the information is split over several pages.
Implementation of Pagination with PHP and MySQL

In order to implement the pagination, we require an astronomically immense dataset to apply pagination to it. Ergo, first we require to engender a database and table. After that, provide the records in the table and commence coding to engender pagination. So that the data fetched from the database can be split over several pages.

Here we will introduce two examples of pagination. First example is a simple and basic example of pagination creation with no CSS, whereas in second example, we will create pagination in attractive way using CSS and bootstrap. You can see the output for both. Below are the steps given for pagination creation;

Simple steps to create pagination -

  1. Create a database and table. Provide a list of records into the table.
  2. Connect with the MySQL database.
  3. Create the pagination link to split the data on multiple pages and add them to bottom of the table.
  4. Fetch data from the database and display it to the multiple pages.

Follow the below step one by one and create simple pagination.

Example

The below example is another example of pagination in which we used CSS along with HTML to make webpage view more attractive. CSS makes the webpage more creative and attractive. On the other hand, MySQL stores the data in database. So, you can learn pagination much better.

We have written whole code in a single file except database connectivity. Therefore, we will create two files, i.e., connection.php and index1.php. Save both the files in .php extension. In the example below, you will learn to create pagination more creative and attractive.

File: connection.php

Database Connectivity

You can write database connectivity code in the same file as well as also keep it separate into another file and include it to your required PHP file. Code for database connection-

<?php  

    $conn = mysqli_connect('localhost', 'root', 'root');  
    if (! $conn) {  
             die("Connection failed" . mysqli_connect_error());  
    }  
    else {  
             mysqli_select_db($conn, 'php_curd');  

    } 

?>

Fetch data and display on webpage

As we have created dataset, now we need to fetch and display it to various webpages. The below code is used to retrieve the data from database and display on the webpages that are divided accordingly.

Fetch data

After establishing the database connection in "connection.php" file, we just need to import it into our code using require_once keyword. We will explicitly define the number of records per page to show.

<?php  

    require_once "connection.php";   
  
    $per_page_record = 4;  // Number of entries to show in a page.   
    // Look for a GET variable page if not found default is 1.        
    if (isset($_GET["page"])) {    
          $page  = $_GET["page"];    
     }    
     else {    
           $page=1;    
     }    
        
    //determine the sql LIMIT starting number for the results on the displaying page  
     $start_from = ($page-1) * $per_page_record;     
        
     $query = "SELECT * FROM product LIMIT $start_from, $per_page_record";     
     $rs_result = mysqli_query ($conn, $query);  

?>

Display data

This section is very simple. In this section, we iterate the loop over the records that we fetched and display each record stored in columns of the table.

<?php  

  while ($row = mysqli_fetch_array($rs_result)) {    
        // Display each field of the records.    
  ?>     
  <tr>     
    <td><?php echo $row["id"]; ?></td>     
    <td><?php echo $row["product_name"]; ?></td>   
    <td><?php echo $row["product_price"]; ?></td>   
    <td><?php echo $row["product_category"]; ?></td>   
    <td><?php echo $row["product_details"]; ?></td>   
    <td><?php echo $row["product_stock"]; ?></td>                                           
</tr>     
  <?php     
  };  

?>

Pagination Link creation

Now the most important code is pagination link creation. So, we will create the Previous, Next, and numeric links for pagination and add them to bottom of the table.

<?php  

    if($page>=2) {   
        echo "<a href='index1.php?page=".($page-1)."'>  Prev </a>";   
    }       
                       
    for ($i=1; $i<=$total_pages; $i++) {   
            if ($i == $page) {   
                  $pagLink .= "<a class = 'active' href='index1.php?page="  
                                                    .$i."'>".$i." </a>";   
              }               
              else  {   
                  $pagLink .= "<a href='index1.php?page=".$i."'>   
                                                    ".$i." </a>";     
              }   
    };     
    echo $pagLink;   
      
    if($page<$total_pages){   
              echo "<a href='index1.php?page=".($page+1)."'>  Next </a>";   
    }   

?>

Code for Random Moment

In case when the number of pages is too much, this code helps us for random moment. By entering the page number in the input field, a user can directly move to that page. This code is written in JavaScript.

<?php  

    function go2Page()   
    {   
            var page = document.getElementById("page").value;   
            page = ((page><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((page<1)?1:page));   
            window.location.href = 'index1.php?page='+page;   
    }    

?>

Final Code

File: Index1.php
<?php  

  <html>   
  <head>   
    <title>How To Create Pagination In PHP and Mysql - itwebtuts</title>   
    <link rel="stylesheet"  
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">   
    <style>   
    table {  
        border-collapse: collapse;  
    }  
        .inline{   
            display: inline-block;   
            float: right;   
            margin: 20px 0px;   
        }   
         
        input, button{   
            height: 34px;   
        }   
  
    .pagination {   
        display: inline-block;   
    }   
    .pagination a {   
        font-weight:bold;   
        font-size:18px;   
        color: black;   
        float: left;   
        padding: 8px 16px;   
        text-decoration: none;   
        border:1px solid black;   
    }   
    .pagination a.active {   
            background-color: skyblue ;   
    }   
    .pagination a:hover:not(.active) {   
        background-color: pink;   
    }   
        </style>   
  </head>   
  <body>   
  <center>  
    <?php  
      
    // Import the file where we defined the connection to Database.     
        require_once "connection.php";   
    
        $per_page_record = 4;  // Number of entries to show in a page.   
        // Look for a GET variable page if not found default is 1.        
        if (isset($_GET["page"])) {    
            $page  = $_GET["page"];    
        }    
        else {    
          $page=1;    
        }    
    
        $start_from = ($page-1) * $per_page_record;     
    
        $query = "SELECT * FROM product LIMIT $start_from, $per_page_record";     
        $rs_result = mysqli_query ($conn, $query);    
    ?>    
  
    <div class="container">   
      <br>   
      <div>   
        <h1>Pagination Simple Example - itwebtuts</h1>   
          
        <table class="table table-striped table-condensed    
                                          table-bordered">   
          <thead>   
            <tr>   
              <th width="10%">ID</th>   
              <th>Name</th>   
              <th>price</th>   
              <th>category</th>   
              <th>details</th>   
              <th>stock</th>   
            </tr>   
          </thead>   
          <tbody>   
    <?php     
            while ($row = mysqli_fetch_array($rs_result)) {    
                  // Display each field of the records.    
            ?>     
            <tr>     
                <td><?php echo $row["id"]; ?></td>     
                <td><?php echo $row["product_name"]; ?></td>   
                <td><?php echo $row["product_price"]; ?></td>   
                <td><?php echo $row["product_category"]; ?></td>   
                <td><?php echo $row["product_details"]; ?></td>   
                <td><?php echo $row["product_stock"]; ?></td>                                           
            </tr>     
            <?php     
                };    
            ?>     
          </tbody>   
        </table>   
  
     <div class="pagination">    
      <?php  
        $query = "SELECT COUNT(*) FROM product";     
        $rs_result = mysqli_query($conn, $query);     
        $row = mysqli_fetch_row($rs_result);     
        $total_records = $row[0];     
          
    echo "</br>";     
        // Number of pages required.   
        $total_pages = ceil($total_records / $per_page_record);     
        $pagLink = "";       
      
        if($page>=2){   
            echo "<a href='index1.php?page=".($page-1)."'>  Prev </a>";   
        }       
                   
        for ($i=1; $i<=$total_pages; $i++) {   
          if ($i == $page) {   
              $pagLink .= "<a class = 'active' href='index1.php?page="  
                                                .$i."'>".$i." </a>";   
          }               
          else  {   
              $pagLink .= "<a href='index1.php?page=".$i."'>   
                                                ".$i." </a>";     
          }   
        };     
        echo $pagLink;   
  
        if($page<$total_pages){   
            echo "<a href='index1.php?page=".($page+1)."'>  Next </a>";   
        }   
  
      ?>    
      </div>  
  
  
      <div class="inline">   
      <input id="page" type="number" min="1" max="<?php echo $total_pages?>"   
      placeholder="<?php echo $page."/".$total_pages; ?>" required>   
      <button class="btn btn-success" onClick="go2Page();">Go</button>   
     </div>    
    </div>   
  </div>  
</center>   
  <script>   
    function go2Page()   
    {   
        var page = document.getElementById("page").value;   
        page = ((page><?php echo $total_pages; ?>)?<?php echo $total_pages; ?>:((page<1)?1:page));   
        window.location.href = 'index1.php?page='+page;   
    }   
  </script>  
  </body>   
</html>

?>

I Will help you.