1658319001
En esta guía, aprenderemos cómo recortar una imagen antes de subirla a la base de datos en PHP + MySQL + jQuery Croppie + Ajax. Y también cómo usar ajax para enviar un archivo de imagen al servidor sin actualizar toda la página web en PHP + MySQL.
Ahora, debe iniciar su servidor web apache. Y además de iniciar el servidor web Apache y mysql.
En el paso 2, navegue a su directorio xampp/htdocs/. Y dentro del directorio xampp/htdocs/, cree una carpeta. Y puedes nombrar esta carpeta como quieras.
Aquí, haré una "demostración" del nombre de esta carpeta. Luego abra esta carpeta en cualquier editor de texto (usaré el editor de texto sublime).
CREATE DATABASE my_db;
CREATE TABLE `images` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`file` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
Luego cree un archivo php que se llame mydb.php. Que se utiliza para conectar la base de datos phpmyadmin mysql a la carpeta del proyecto (demostración).
Entonces, ahora cree el archivo mydb.php y agregue el siguiente código en su archivo:
<?php
$hName='localhost'; // host name
$uName='root'; // database user name
$password=''; // database password
$dbName = "my_db"; // database name
$conn = mysqli_connect($hName,$uName,$password,"$dbName");
if(!$conn){
die('Could not Connect MySql Server:' .mysql_error());
}
?>
<html>
<head>
<title>Crop and Save Image using jQuery ajax and PHP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
</head>
<body>
<div class="container mt-5">
<div class="card">
<div class="card-header">
Crop and Save Image using jQuery ajax and PHP
</div>
<div class="card-body">
<input type="file" name="before_crop_image" id="before_crop_image" accept="image/*" />
</div>
</div>
</div>
</body>
</html>
Agregue las siguientes líneas jQuery croppie js library en formato html:
Cree un modelo de arranque para recortar y cargar en la base de datos y agregarlo al archivo index.php; Como se muestra abajo:
<div id="imageModel" class="modal fade bd-example-modal-lg" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Crop & Resize Upload Image in PHP with Ajax</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br/>
<button class="btn btn-success crop_image">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width:200,
height:200,
type:'square' //circle
},
boundary:{
width:300,
height:300
}
});
$('#before_crop_image').on('change', function(){
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
$('#imageModel').modal('show');
});
$('.crop_image').click(function(event){
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:'crop-image-store.php',
type:'POST',
data:{"image":response},
success:function(data){
$('#imageModel').modal('hide');
alert('Crop image has been uploaded');
}
})
});
});
});
</script>
Código fuente completo del archivo index.php; como a continuación:
<html>
<head>
<title>Crop and Save Image using jQuery ajax and PHP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
</head>
<body>
<div class="container mt-5">
<div class="card">
<div class="card-header">
Crop and Save Image using jQuery ajax and PHP
</div>
<div class="card-body">
<input type="file" name="before_crop_image" id="before_crop_image" accept="image/*" />
</div>
</div>
</div>
</body>
</html>
<div id="imageModel" class="modal fade bd-example-modal-lg" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Crop & Resize Upload Image in PHP with Ajax</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br/>
<button class="btn btn-success crop_image">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width:200,
height:200,
type:'square' //circle
},
boundary:{
width:300,
height:300
}
});
$('#before_crop_image').on('change', function(){
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
$('#imageModel').modal('show');
});
$('.crop_image').click(function(event){
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:'crop-image-store.php',
type:'POST',
data:{"image":response},
success:function(data){
$('#imageModel').modal('hide');
alert('Crop image has been uploaded');
}
})
});
});
});
</script>
<?php
//save crop image in php
if(isset($_POST["image"]))
{
include('db.php');
$data = $_POST["image"];
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = time() . '.png';
file_put_contents($imageName, $data);
$image_file = addslashes(file_get_contents($imageName));
$query = "INSERT INTO images(file) VALUES ('".$image_file."')";
$statement = $connect->prepare($query);
if($statement->execute())
{
echo 'Image save into database';
unlink($imageName);
}
}
?>
Finalmente, debe abrir su navegador y escribir http://localhost/demo/ este proyecto de ejecución en la máquina local.
Para recortar y cargar imágenes en PHP + base de datos MySQL + jQuery croppie y ajax. A través de este tutorial, aprendió cómo recortar una imagen antes de subirla a la base de datos en PHP + MySQL + jQuery Croppie + Ajax.
1615040237
PHP jquery ajax POST request with MySQL. In this tutorial, you will learn how to create and submit a simple form in PHP using jQuery ajax post request. And how to submit a form data into MySQL database without the whole page refresh or reload. And also you will learn how to show an error message to the user if the user does not fill any form field.
And this tutorial also guide on how to send data to MySQL database using AJAX + jQuery + PHP without reloading the whole page and show a client-side validation error message if it has an error in the form.
Just follow the few below steps and easily create and submit ajax form in PHP and MySQL with client-side validation.
https://www.tutsmake.com/php-jquery-ajax-post-tutorial-example/
#jquery ajax serialize form data example #submit form using ajax in php example #save form data using ajax in php #how to insert form data using ajax in php #php jquery ajax form submit example #jquery ajax and jquery post form submit example with php
1658319001
En esta guía, aprenderemos cómo recortar una imagen antes de subirla a la base de datos en PHP + MySQL + jQuery Croppie + Ajax. Y también cómo usar ajax para enviar un archivo de imagen al servidor sin actualizar toda la página web en PHP + MySQL.
Ahora, debe iniciar su servidor web apache. Y además de iniciar el servidor web Apache y mysql.
En el paso 2, navegue a su directorio xampp/htdocs/. Y dentro del directorio xampp/htdocs/, cree una carpeta. Y puedes nombrar esta carpeta como quieras.
Aquí, haré una "demostración" del nombre de esta carpeta. Luego abra esta carpeta en cualquier editor de texto (usaré el editor de texto sublime).
CREATE DATABASE my_db;
CREATE TABLE `images` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`file` VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=1;
Luego cree un archivo php que se llame mydb.php. Que se utiliza para conectar la base de datos phpmyadmin mysql a la carpeta del proyecto (demostración).
Entonces, ahora cree el archivo mydb.php y agregue el siguiente código en su archivo:
<?php
$hName='localhost'; // host name
$uName='root'; // database user name
$password=''; // database password
$dbName = "my_db"; // database name
$conn = mysqli_connect($hName,$uName,$password,"$dbName");
if(!$conn){
die('Could not Connect MySql Server:' .mysql_error());
}
?>
<html>
<head>
<title>Crop and Save Image using jQuery ajax and PHP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
</head>
<body>
<div class="container mt-5">
<div class="card">
<div class="card-header">
Crop and Save Image using jQuery ajax and PHP
</div>
<div class="card-body">
<input type="file" name="before_crop_image" id="before_crop_image" accept="image/*" />
</div>
</div>
</div>
</body>
</html>
Agregue las siguientes líneas jQuery croppie js library en formato html:
Cree un modelo de arranque para recortar y cargar en la base de datos y agregarlo al archivo index.php; Como se muestra abajo:
<div id="imageModel" class="modal fade bd-example-modal-lg" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Crop & Resize Upload Image in PHP with Ajax</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br/>
<button class="btn btn-success crop_image">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width:200,
height:200,
type:'square' //circle
},
boundary:{
width:300,
height:300
}
});
$('#before_crop_image').on('change', function(){
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
$('#imageModel').modal('show');
});
$('.crop_image').click(function(event){
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:'crop-image-store.php',
type:'POST',
data:{"image":response},
success:function(data){
$('#imageModel').modal('hide');
alert('Crop image has been uploaded');
}
})
});
});
});
</script>
Código fuente completo del archivo index.php; como a continuación:
<html>
<head>
<title>Crop and Save Image using jQuery ajax and PHP</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.6.5/croppie.css" />
</head>
<body>
<div class="container mt-5">
<div class="card">
<div class="card-header">
Crop and Save Image using jQuery ajax and PHP
</div>
<div class="card-body">
<input type="file" name="before_crop_image" id="before_crop_image" accept="image/*" />
</div>
</div>
</div>
</body>
</html>
<div id="imageModel" class="modal fade bd-example-modal-lg" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Crop & Resize Upload Image in PHP with Ajax</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br/>
<button class="btn btn-success crop_image">Save</button>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width:200,
height:200,
type:'square' //circle
},
boundary:{
width:300,
height:300
}
});
$('#before_crop_image').on('change', function(){
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function(){
console.log('jQuery bind complete');
});
}
reader.readAsDataURL(this.files[0]);
$('#imageModel').modal('show');
});
$('.crop_image').click(function(event){
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:'crop-image-store.php',
type:'POST',
data:{"image":response},
success:function(data){
$('#imageModel').modal('hide');
alert('Crop image has been uploaded');
}
})
});
});
});
</script>
<?php
//save crop image in php
if(isset($_POST["image"]))
{
include('db.php');
$data = $_POST["image"];
$image_array_1 = explode(";", $data);
$image_array_2 = explode(",", $image_array_1[1]);
$data = base64_decode($image_array_2[1]);
$imageName = time() . '.png';
file_put_contents($imageName, $data);
$image_file = addslashes(file_get_contents($imageName));
$query = "INSERT INTO images(file) VALUES ('".$image_file."')";
$statement = $connect->prepare($query);
if($statement->execute())
{
echo 'Image save into database';
unlink($imageName);
}
}
?>
Finalmente, debe abrir su navegador y escribir http://localhost/demo/ este proyecto de ejecución en la máquina local.
Para recortar y cargar imágenes en PHP + base de datos MySQL + jQuery croppie y ajax. A través de este tutorial, aprendió cómo recortar una imagen antes de subirla a la base de datos en PHP + MySQL + jQuery Croppie + Ajax.
1602560783
In this article, we’ll discuss how to use jQuery Ajax for ASP.NET Core MVC CRUD Operations using Bootstrap Modal. With jQuery Ajax, we can make HTTP request to controller action methods without reloading the entire page, like a single page application.
To demonstrate CRUD operations – insert, update, delete and retrieve, the project will be dealing with details of a normal bank transaction. GitHub repository for this demo project : https://bit.ly/33KTJAu.
Sub-topics discussed :
In Visual Studio 2019, Go to File > New > Project (Ctrl + Shift + N).
From new project window, Select Asp.Net Core Web Application_._
Once you provide the project name and location. Select Web Application(Model-View-Controller) and uncheck HTTPS Configuration. Above steps will create a brand new ASP.NET Core MVC project.
Let’s create a database for this application using Entity Framework Core. For that we’ve to install corresponding NuGet Packages. Right click on project from solution explorer, select Manage NuGet Packages_,_ From browse tab, install following 3 packages.
Now let’s define DB model class file – /Models/TransactionModel.cs.
public class TransactionModel
{
[Key]
public int TransactionId { get; set; }
[Column(TypeName ="nvarchar(12)")]
[DisplayName("Account Number")]
[Required(ErrorMessage ="This Field is required.")]
[MaxLength(12,ErrorMessage ="Maximum 12 characters only")]
public string AccountNumber { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Beneficiary Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BeneficiaryName { get; set; }
[Column(TypeName ="nvarchar(100)")]
[DisplayName("Bank Name")]
[Required(ErrorMessage = "This Field is required.")]
public string BankName { get; set; }
[Column(TypeName ="nvarchar(11)")]
[DisplayName("SWIFT Code")]
[Required(ErrorMessage = "This Field is required.")]
[MaxLength(11)]
public string SWIFTCode { get; set; }
[DisplayName("Amount")]
[Required(ErrorMessage = "This Field is required.")]
public int Amount { get; set; }
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime Date { get; set; }
}
C#Copy
Here we’ve defined model properties for the transaction with proper validation. Now let’s define DbContextclass for EF Core.
#asp.net core article #asp.net core #add loading spinner in asp.net core #asp.net core crud without reloading #asp.net core jquery ajax form #asp.net core modal dialog #asp.net core mvc crud using jquery ajax #asp.net core mvc with jquery and ajax #asp.net core popup window #bootstrap modal popup in asp.net core mvc. bootstrap modal popup in asp.net core #delete and viewall in asp.net core #jquery ajax - insert #jquery ajax form post #modal popup dialog in asp.net core #no direct access action method #update #validation in modal popup
1659323040
DataTable viene con un solo cuadro de búsqueda que puede usar para buscar en todos los campos o en campos específicos y mostrar registros filtrados.
Puede agregar elementos personalizados según sus requisitos y usarlos con DataTable.
En este tutorial, muestro cómo puede implementar una búsqueda de rango de fechas en DataTable con jQuery AJAX y PHP. Estoy usando jQuery UI para agregar un selector de fechas.
Cree employee
una tabla y agregué algunos registros.
CREATE TABLE `employee` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`emp_name` varchar(80) NOT NULL,
`salary` varchar(20) NOT NULL,
`gender` varchar(10) NOT NULL,
`city` varchar(80) NOT NULL,
`email` varchar(80) NOT NULL,
`date_of_joining` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Para la búsqueda de fechas, creó un 'date_of_joining'
campo de date
tipo.
Cree una config.php
para la conexión de la base de datos.
Código completado
<?php
$host = "localhost"; /* Host name */$user = "root"; /* User */$password = ""; /* Password */$dbname = "tutorial"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
datatables.min.css
, jquery-ui.min.css
, la biblioteca jQuery jquery-ui.min.js
, y datatables.min.js
en la <head>
sección.<!-- Datatable CSS -->
<link href='//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css' rel='stylesheet' type='text/css'>
<!-- jQuery UI CSS -->
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<!-- jQuery Library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- jQuery UI JS -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Datatable JS -->
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
Para el filtro de fecha, cree dos elementos de texto. Agregado class='datepicker'
para inicializar el selector de fechas. Además, cree un elemento de botón.
Crear <table id='empTable'>
_
Código completado
<div >
<!-- Date Filter -->
<table>
<tr>
<td>
<input type='text' readonly id='search_fromdate' class="datepicker" placeholder='From date'>
</td>
<td>
<input type='text' readonly id='search_todate' class="datepicker" placeholder='To date'>
</td>
<td>
<input type='button' id="btn_search" value="Search">
</td>
</tr>
</table>
<!-- Table -->
<table id='empTable' class='display dataTable'>
<thead>
<tr>
<th>Employee name</th>
<th>Email</th>
<th>Date of Joining</th>
<th>Salary</th>
<th>City</th>
</tr>
</thead>
</table>
</div>
Inicializar datepicker
en class='datepicker'
.
Inicialice DataTable en #empTable
. Establecer opciones – 'processing': true, 'serverSide': true, 'serverMethod': 'post'
. Establezca la URL de AJAX en 'ajaxfile.php'
.
Con 'ajax'
data
la opción pase el filtro de fecha desde y hasta la fecha agregando en data
el objeto. Asigne from_date
valor en data.searchByFromdate
y to_date
valor en data.searchByTodate
.
Con 'columns'
la opción especifica los nombres de clave que deben leerse de la respuesta AJAX.
En el botón de búsqueda, haga clic en llamar dataTable.draw()
para volver a dibujar el DataTable y pasar los valores del filtro.
Código completado
$(document).ready(function(){
// Datapicker
$( ".datepicker" ).datepicker({
"dateFormat": "yy-mm-dd",
changeYear: true
});
// DataTable
var dataTable = $('#empTable').DataTable({
'processing': true,
'serverSide': true,
'serverMethod': 'post',
'searching': true, // Set false to Remove default Search Control
'ajax': {
'url':'ajaxfile.php',
'data': function(data){
// Read values
var from_date = $('#search_fromdate').val();
var to_date = $('#search_todate').val();
// Append to data
data.searchByFromdate = from_date;
data.searchByTodate = to_date;
}
},
'columns': [
{ data: 'emp_name' },
{ data: 'email' },
{ data: 'date_of_joining' },
{ data: 'salary' },
{ data: 'city' },
]
});
// Search button
$('#btn_search').click(function(){
dataTable.draw();
});
});
Crear ajaxfile.php
archivo para el manejo de solicitudes AJAX.
Lea los valores POST de DataTable y asígnelos a las variables.
Además, lea los valores de filtro de fecha pasada y asígnelos en $searchByFromdate
y $searchByTodate
.
Si $searchValue
no está vacío, prepara la consulta del filtro de búsqueda. Úselo $searchValue
para buscar en los campos emp_name, email y city.
Si $searchByFromdate
y $searchByTodate
no está vacío, prepare y concatene la consulta del filtro de búsqueda en $searchQuery
. Utilice entre para seleccionar registros cuyo date_of_joining
valor de campo esté entre $searchByFromdate
y $searchByTodate
.
Cuente el número de registros con y sin el filtro de la employee
tabla. Asigne registros totales sin filtro en $totalRecords
y con filtro en $totalRecordwithFilter
.
Obtener registros de employee
la tabla donde se pasa $searchQuery
la WHERE
cláusula y especificar ORDER BY
y LIMIT
.
Inicialice $response
Array con los valores requeridos y regrese en formato JSON.
Código completado
<?php
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Date search value
$searchByFromdate = mysqli_real_escape_string($con,$_POST['searchByFromdate']);
$searchByTodate = mysqli_real_escape_string($con,$_POST['searchByTodate']);
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (emp_name like '%".$searchValue."%' or email like '%".$searchValue."%' or city like'%".$searchValue."%' ) ";
}
// Date filter
if($searchByFromdate != '' && $searchByTodate != ''){
$searchQuery .= " and (date_of_joining between '".$searchByFromdate."' and '".$searchByTodate."' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of records with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"date_of_joining"=>$row['date_of_joining'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
die;
Pase los valores de filtro de fecha usando ajax
data
la opción. Llame draw()
al método en la instancia de dataTable para recargar los datos después de la selección de fecha desde y hasta.
Si el campo de su tabla almacenó la marca de tiempo UNIX en lugar de una fecha o un formato de fecha y hora, entonces necesita convertir los valores de filtro de fecha pasados de dataTable al formato de marca de tiempo UNIX usando strtotime()
la función y el uso en la consulta de búsqueda.
Fuente: https://makitweb.com
1597487472
Here, i will show you how to populate country state city in dropdown list in php mysql using ajax.
You can use the below given steps to retrieve and display country, state and city in dropdown list in PHP MySQL database using jQuery ajax onchange:
https://www.tutsmake.com/country-state-city-database-in-mysql-php-ajax/
#country state city drop down list in php mysql #country state city database in mysql php #country state city drop down list using ajax in php #country state city drop down list using ajax in php demo #country state city drop down list using ajax php example #country state city drop down list in php mysql ajax