Monday, April 29, 2019

Ajax : 5 best libraries for making AJAX calls in React

jQuery $.ajax

This is a quick & dirty way to make AJAX calls. In the former, official React tutorial, they use jQuery to fetch data from the server. If you are just starting out and are playing around with React, this can save you a lot of time. Many of us are already familiar with jQuery. So, it won't take a lot of time to understand and use it in React. Here is how a simple API call is made, with jQuery:
loadCommentsFromServer: function() {
      $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data}); // Notice this
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  }
P.S. Snippet is from React's former official tutorial.
It's the same old jQuery's $.ajax used inside a React component. Notice how this.setState() is called inside the success callback. This is how you update the state with data obtained from the API call.
However, jQuery is a big library with many functionalities - So, it doesn't make sense to use it just for making API calls (Unless you are already using it for a bunch of other tasks). So, what's the alternative? What should we use? The answer is fetch API.

Fetch API

Fetch is a new, simple and standardised API that aims to unify fetching across the web and replace XMLHttpRequest. It has a polyfill for older browsers and should be used in modern web apps. If you are making API calls in Node.js you should also check out node-fetch which brings fetch to Node.js.
Here is what the modified API call looks like :
loadCommentsFromServer: function() {
    fetch(this.props.url).then(function(response){
        // perform setState here
    });
}
In most modern React tutorials you will find fetch being used. To know more about fetch, check out the following links :

Superagent

Superagent is a light weight AJAX API library created for better readability and flexibility. If due to some reason, you don't want to use fetch, you should definitely check this out. Here is a snippet to demonstrate its usage :
loadCommentsFromServer: function() {
    request.get(this.props.url).end(function(err,res){
        // perform setState here
    });
}
Superagent also has a Node.js module with the same API. If you are building isomorphic apps using Node.js and React, you can bundle superagent using something like webpack and make it available on the client side. As the APIs for client and server are the same, no code change is required in order to make it work in the browser.

Axios

Axios is a promise based HTTP client for Node.js and browser. Like fetch and superagent, it can work on both client and server. It has many other useful features which you can find on their GitHub page.
Here is how you make an API call using Axios :
loadCommentsFromServer: function() {
    axios.get(this.props.url).then(function(response){
      // perform setState here
    }).catch(function(error){
      //Some error occurred
    });
}

Request

This list will be incomplete without request library which was designed with simplicity in mind. With more that 12k GitHub stars, it's also one of the most popular Node.js modules. You can find more about request module on their GitHub page.
Sample usage :
loadCommentsFromServer: function() {
    request(this.props.url, function(err, response, body){
          // perform setState here
    });
}



Sunday, April 21, 2019

Laravel : Laravel 5.6 - User Roles and Permissions (ACL) using Spatie Tutorial

ACL stands for Access Control List. ACL roles and permissions are very important if you are making big application in laravel 5.6. this tutorial will explain how to implement User Roles and Permissions(ACL) using spatie/laravel-permission composer package. So basically i will do it from scratch how to create permissions, roles, and users with assign roles etc.
I also posted on tutorial for ACL User Roles and Permissions using entrust package, you can see here : Laravel 5 - User Roles and Permissions (ACL) using entrust package.
If you are work on big ERP or Project then you need to control access to certain sections of the website. I mean you require to role permissions based access control database design that way you can specify the level of the user.
Roles and Permissions through you can create several types of users with different role and permission, i mean some user have only see a listing of items module, some user can also edit items modules, for delete and etc.
In this examples I created three modules as listed below:
User Management
Role Management
Product Management
After register user, you don't have any roles, so you can edit your details and assign admin role to you from User Management. After that you can create your own role with permission like role-list, role-create, role-edit, role-delete, product-list, product-create, product-edit, product-delete. you can check with assign new user and check that.
You need to just follow few step and you will get full example of ACL:



Creative code : PHP - Dynamically Add Remove input fields using JQuery Ajax Example with Demo

In this post, we will learn how to add and remove form input fields dynamically using jQuery and store in database using PHP. Here you will see how to handle dynamically added fields value save in mysql database using PHP Bootstrap. I will show you full example of dynamically add/remove input fields and submit to database with jquery ajax and php. you can also see add more fields jquery demo.
Few days ago i posted add/remove multiple input fields dynamically with jquery ajax in Laravel Framework, You can see here : Laravel - Dynamically Add or Remove input fields using JQuery.
We almost need to require add more functionality when client want to at time multiple value insert into database. It will great if you are use something interesting like give them input box with "+" button that way they can add multiple values at time.
So here you have to just follow few step to proceed.
1) Create Database Table
2) index.php File
3) addmore.php File
After Completed full example, you will get layout like as bellow:
Step 1: Create Database Table

In fist step, we need to create database and table, so here i created "test" database and "tagslist" table with id and name column. You can simply create "tagslist" table as following sql query.
SQL Query:
CREATE TABLE IF NOT EXISTS `tagslist` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=24 ;
Step 2: Create index.php File
Here, we need to create index.php file and i created form with one input text box and button. I also write code for add more fields in jquery. So let's create index.php file and put bellow code.
index.php

<!DOCTYPE html>
<html>
<head>
<title>PHP - Dynamically Add or Remove input fields using JQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2 align="center">PHP - Dynamically Add or Remove input fields using JQuery</h2>
<div class="form-group">
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" required="" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var postURL = "/addmore.php";
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" required /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
alert('Record Inserted Successfully.');
}
});
});
});
</script>
</body>
</html>
Step 3: Create addmore.php File
In this step, we will write code of insert data into database using mysql query. So you have to create addmore.php and put bellow code:
addmore.php
<?php
define (DB_USER, "root");
define (DB_PASSWORD, "root");
define (DB_DATABASE, "test");
define (DB_HOST, "localhost");
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if(!empty($_POST["name"])){
foreach ($_POST["name"] as $key => $value) {
$sql = "INSERT INTO tagslist(name) VALUES ('".$value."')";
$mysqli->query($sql);
}
echo json_encode(['success'=>'Names Inserted successfully.']);
}
?>


Creative code : Jquery Ajax CRUD Operations in PHP

Hi Guys,
In this tutorial, i would like to show you how to create add edit delete and pagination operations using jquery ajax in php. You have to just follow 4 step to create php crud operation using ajax/jquery with bootstrap. I also added jquery validation using validatorjs plugin.
In this post, i crud with i also created pagination, notification and also validation in crud operation. When you will add new item then show you "item created successfully" notification. So just follow listed few step and you will get crud app like as below screen shot:

Content Overview
you can implement crud application from scratch, so no worry if you can implement through bellow simple step. After create successful example, you will find layout as bellow:

Step 1: Create Database and Table Configuration

first of all, we should create database and items table. so let's create database i did create "h_blog" database and "items" table inside that database. so you can create database as you want but you have to create "items" table if you are doing from scratch. so create "items" table using following mysql query:
Items Table Query:

CREATE TABLE IF NOT EXISTS `items` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`description` text COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=63 ;
Ok, let's proceed this way, we are doing from scratch so we require to create database configuration file that way we can use that file in many other file. so let's create api directory and create db_config.php file in api directory and put bellow code:
api/db_config.php
<?php
$hostName = "localhost";
$username = "root";
$password = "root";
$dbname = "blog2";
$mysqli = new mysqli($hostName, $username, $password, $dbname);
?>

In Above file please make sure to check your database configuration because could problem you find somewhere. that's way i tell you check it two times. It was just for your kind information.
Step 2: Create Index Page
Ok, now we also require to create index.php file in our root directory. In this file i added "url" variable in js for site root URL. You can update also with your site URL. so let's create index.php file and put bellow content in that file.
index.php
<!DOCTYPE html>
<html>
<head>
<title>PHP Jquery Ajax CRUD Example</title>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.3.1/jquery.twbsPagination.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
<link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">
<script type="text/javascript">
var url = "http://localhost:8000/";
</script>
<script src="/js/item-ajax.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>PHP Jquery Ajax CRUD Example</h2>
</div>
<div class="pull-right">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-item">
Create Item
</button>
</div>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>Title</th>
<th>Description</th>
<th width="200px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<ul id="pagination" class="pagination-sm"></ul>
<!-- Create Item Modal -->
<div class="modal fade" id="create-item" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Create Item</h4>
</div>
<div class="modal-body">
<form data-toggle="validator" action="api/create.php" method="POST">
<div class="form-group">
<label class="control-label" for="title">Title:</label>
<input type="text" name="title" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Description:</label>
<textarea name="description" class="form-control" data-error="Please enter description." required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="btn crud-submit btn-success">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Edit Item Modal -->
<div class="modal fade" id="edit-item" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Edit Item</h4>
</div>
<div class="modal-body">
<form data-toggle="validator" action="api/update.php" method="put">
<input type="hidden" name="id" class="edit-id">
<div class="form-group">
<label class="control-label" for="title">Title:</label>
<input type="text" name="title" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Description:</label>
<textarea name="description" class="form-control" data-error="Please enter description." required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success crud-submit-edit">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Step 3: Create CRUD JS File
In this step we will create jquery file and write ajax request code on it. So first create js folder on your root directory and then create item-ajax.js file on it.
js/item-ajax.js

$( document ).ready(function() {
var page = 1;
var current_page = 1;
var total_page = 0;
var is_ajax_fire = 0;
manageData();
/* manage data list */
function manageData() {
$.ajax({
dataType: 'json',
url: url+'api/getData.php',
data: {page:page}
}).done(function(data){
total_page = Math.ceil(data.total/10);
current_page = page;
$('#pagination').twbsPagination({
totalPages: total_page,
visiblePages: current_page,
onPageClick: function (event, pageL) {
page = pageL;
if(is_ajax_fire != 0){
getPageData();
}
}
});
manageRow(data.data);
is_ajax_fire = 1;
});
}
/* Get Page Data*/
function getPageData() {
$.ajax({
dataType: 'json',
url: url+'api/getData.php',
data: {page:page}
}).done(function(data){
manageRow(data.data);
});
}
/* Add new Item table row */
function manageRow(data) {
var rows = '';
$.each( data, function( key, value ) {
rows = rows + '<tr>';
rows = rows + '<td>'+value.title+'</td>';
rows = rows + '<td>'+value.description+'</td>';
rows = rows + '<td data-id="'+value.id+'">';
rows = rows + '<button data-toggle="modal" data-target="#edit-item" class="btn btn-primary edit-item">Edit</button> ';
rows = rows + '<button class="btn btn-danger remove-item">Delete</button>';
rows = rows + '</td>';
rows = rows + '</tr>';
});
$("tbody").html(rows);
}
/* Create new Item */
$(".crud-submit").click(function(e){
e.preventDefault();
var form_action = $("#create-item").find("form").attr("action");
var title = $("#create-item").find("input[name='title']").val();
var description = $("#create-item").find("textarea[name='description']").val();
if(title != '' && description != ''){
$.ajax({
dataType: 'json',
type:'POST',
url: url + form_action,
data:{title:title, description:description}
}).done(function(data){
$("#create-item").find("input[name='title']").val('');
$("#create-item").find("textarea[name='description']").val('');
getPageData();
$(".modal").modal('hide');
toastr.success('Item Created Successfully.', 'Success Alert', {timeOut: 5000});
});
}else{
alert('You are missing title or description.')
}
});
/* Remove Item */
$("body").on("click",".remove-item",function(){
var id = $(this).parent("td").data('id');
var c_obj = $(this).parents("tr");
$.ajax({
dataType: 'json',
type:'POST',
url: url + 'api/delete.php',
data:{id:id}
}).done(function(data){
c_obj.remove();
toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});
getPageData();
});
});
/* Edit Item */
$("body").on("click",".edit-item",function(){
var id = $(this).parent("td").data('id');
var title = $(this).parent("td").prev("td").prev("td").text();
var description = $(this).parent("td").prev("td").text();
$("#edit-item").find("input[name='title']").val(title);
$("#edit-item").find("textarea[name='description']").val(description);
$("#edit-item").find(".edit-id").val(id);
});
/* Updated new Item */
$(".crud-submit-edit").click(function(e){
e.preventDefault();
var form_action = $("#edit-item").find("form").attr("action");
var title = $("#edit-item").find("input[name='title']").val();
var description = $("#edit-item").find("textarea[name='description']").val();
var id = $("#edit-item").find(".edit-id").val();
if(title != '' && description != ''){
$.ajax({
dataType: 'json',
type:'POST',
url: url + form_action,
data:{title:title, description:description,id:id}
}).done(function(data){
getPageData();
$(".modal").modal('hide');
toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});
});
}else{
alert('You are missing title or description.')
}
});
});
Step 4: Create AJAX File
In this step we require to create api file for getting item Data, Add item Data, update item Data and delete item Data. So let's create api file one by one.
api/getData.php
<?php
require 'db_config.php';
$num_rec_per_page = 5;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sqlTotal = "SELECT * FROM items";
$sql = "SELECT * FROM items Order By id desc LIMIT $start_from, $num_rec_per_page";
$result = $mysqli->query($sql);
while($row = $result->fetch_assoc()){
$json[] = $row;
}
$data['data'] = $json;
$result = mysqli_query($mysqli,$sqlTotal);
$data['total'] = mysqli_num_rows($result);
echo json_encode($data);
?>
api/create.php
<?php
require 'db_config.php';
$post = $_POST;
$sql = "INSERT INTO items (title,description)
VALUES ('".$post['title']."','".$post['description']."')";
$result = $mysqli->query($sql);
$sql = "SELECT * FROM items Order by id desc LIMIT 1";
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
?>
api/update.php
<?php
require 'db_config.php';
$id = $_POST["id"];
$post = $_POST;
$sql = "UPDATE items SET title = '".$post['title']."'
,description = '".$post['description']."'
WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$sql = "SELECT * FROM items WHERE id = '".$id."'";
$result = $mysqli->query($sql);
$data = $result->fetch_assoc();
echo json_encode($data);
?>

api/delete.php
<?php
require 'db_config.php';
$id = $_POST["id"];
$sql = "DELETE FROM items WHERE id = '".$id."'";
$result = $mysqli->query($sql);
echo json_encode([$id]);
?>