1659386880
文件上傳是網站的基本要求。它是使用服務器端腳本完成的。
提交表單後需要重新加載頁面才能執行腳本。
使用 AJAX 客戶端腳本與服務器端腳本交互並執行操作而無需重新加載頁面。
在本教程中,我將展示如何使用 JavaScript AJAX 和 PHP 上傳文件。
創建文件和按鈕元素。在調用函數的按鈕上添加onclick
了事件。uploadFile()
完成的代碼
<div >
<input type="file" name="file" id="file">
<input type="button" id="btn_uploadfile"
value="Upload"
onclick="uploadFile();" >
</div>
創建一個ajaxfile.php
文件和一個upload
文件夾來存儲文件。
檢查是否$_FILES
設置了數組。如果設置然後分配$_FILES['file']['name']
給$filename
,文件名,上傳位置在$location
變量中。
獲取文件擴展名並在$valid_ext
數組中分配有效的文件擴展名。
$valid_ext
檢查Array中是否存在文件擴展名。$response
如果存在,則上傳文件,如果成功上傳,則分配 1 。
返回$response
。
完成的代碼
<?php
if(isset($_FILES['file']['name'])){
// file name
$filename = $_FILES['file']['name'];
// Location
$location = 'upload/'.$filename;
// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
// Valid extensions
$valid_ext = array("pdf","doc","docx","jpg","png","jpeg");
$response = 0;
if(in_array($file_extension,$valid_ext)){
// Upload file
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = 1;
}
}
echo $response;
exit;
}
創建uploadFile()
調用上傳按鈕單擊的函數。
讀取files
一個file
元素。如果選擇了文件,則創建一個對象,FormData
否則為警報"Please select a file"
消息。
追加files[0]
到'file'
鍵入formData
。
要發送 AJAX 請求,請創建一個XMLHttpRequest
. 使用open()
方法設置請求方法"POST"
和 AJAX 文件路徑。
用方法處理 AJAX 成功回調onreadystatechange()
。this.responseText
在response
變量中賦值。如果response == 1
則警告"Upload successfully."
消息,否則,警告"File not uploaded."
消息。
用方法傳遞formData
對象。send()
完成的代碼
// Upload file
function uploadFile() {
var files = document.getElementById("file").files;
if(files.length > 0 ){
var formData = new FormData();
formData.append("file", files[0]);
var xhttp = new XMLHttpRequest();
// Set POST method and ajax file path
xhttp.open("POST", "ajaxfile.php", true);
// call on request changes state
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
if(response == 1){
alert("Upload successfully.");
}else{
alert("File not uploaded.");
}
}
};
// Send request with data
xhttp.send(formData);
}else{
alert("Please select a file");
}
}
使用 FormData 對象發送文件實例,並在 AJAX 文件中使用 $_FILES 數組訪問它。
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
1659386880
文件上傳是網站的基本要求。它是使用服務器端腳本完成的。
提交表單後需要重新加載頁面才能執行腳本。
使用 AJAX 客戶端腳本與服務器端腳本交互並執行操作而無需重新加載頁面。
在本教程中,我將展示如何使用 JavaScript AJAX 和 PHP 上傳文件。
創建文件和按鈕元素。在調用函數的按鈕上添加onclick
了事件。uploadFile()
完成的代碼
<div >
<input type="file" name="file" id="file">
<input type="button" id="btn_uploadfile"
value="Upload"
onclick="uploadFile();" >
</div>
創建一個ajaxfile.php
文件和一個upload
文件夾來存儲文件。
檢查是否$_FILES
設置了數組。如果設置然後分配$_FILES['file']['name']
給$filename
,文件名,上傳位置在$location
變量中。
獲取文件擴展名並在$valid_ext
數組中分配有效的文件擴展名。
$valid_ext
檢查Array中是否存在文件擴展名。$response
如果存在,則上傳文件,如果成功上傳,則分配 1 。
返回$response
。
完成的代碼
<?php
if(isset($_FILES['file']['name'])){
// file name
$filename = $_FILES['file']['name'];
// Location
$location = 'upload/'.$filename;
// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
// Valid extensions
$valid_ext = array("pdf","doc","docx","jpg","png","jpeg");
$response = 0;
if(in_array($file_extension,$valid_ext)){
// Upload file
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = 1;
}
}
echo $response;
exit;
}
創建uploadFile()
調用上傳按鈕單擊的函數。
讀取files
一個file
元素。如果選擇了文件,則創建一個對象,FormData
否則為警報"Please select a file"
消息。
追加files[0]
到'file'
鍵入formData
。
要發送 AJAX 請求,請創建一個XMLHttpRequest
. 使用open()
方法設置請求方法"POST"
和 AJAX 文件路徑。
用方法處理 AJAX 成功回調onreadystatechange()
。this.responseText
在response
變量中賦值。如果response == 1
則警告"Upload successfully."
消息,否則,警告"File not uploaded."
消息。
用方法傳遞formData
對象。send()
完成的代碼
// Upload file
function uploadFile() {
var files = document.getElementById("file").files;
if(files.length > 0 ){
var formData = new FormData();
formData.append("file", files[0]);
var xhttp = new XMLHttpRequest();
// Set POST method and ajax file path
xhttp.open("POST", "ajaxfile.php", true);
// call on request changes state
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
if(response == 1){
alert("Upload successfully.");
}else{
alert("File not uploaded.");
}
}
};
// Send request with data
xhttp.send(formData);
}else{
alert("Please select a file");
}
}
使用 FormData 對象發送文件實例,並在 AJAX 文件中使用 $_FILES 數組訪問它。
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
1659432660
AJAX 是允許客戶端與服務器端通信的唯一方式。
使用 JavaScript 庫或框架更容易發送 AJAX 請求。但是了解如何使用純 Javascript 發送 AJAX 請求也很好。
使用 XMLHttpRequest 對象與服務器通信。
在本教程中,我將展示如何使用 JavaScript 發送 GET 和 POST AJAX 請求並使用 PHP 處理請求。
創建employee
表並添加一些記錄。
CREATE TABLE `employee` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`emp_name` varchar(80) NOT NULL,
`salary` varchar(20) NOT NULL,
`email` varchar(80) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
為數據庫連接創建一個config.php
。
完成的代碼
<?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());
}
創建 3 個輸入文本元素,用於輸入姓名、薪水和電子郵件。和一個按鈕元素。
在調用函數的按鈕上添加onclick
了事件。insertNewEmployee()
列出<table id='emptTable'>
使用 JavaScript 和 AJAX 中的記錄。
完成的代碼
<div>
Name: <input type="text" id='txt_name'> <br>
Salary: <input type="text" id='txt_salary'> <br>
Email: <input type="text" id='txt_email'> <br>
<input type="button" id="btn_submit" value="Submit" onclick="insertNewEmployee();">
</div>
<table id='empTable' border='1'>
<thead>
<tr>
<th>Name</th>
<th>Salary</th>
<th>Email</th>
</tr>
</thead>
<tbody></tbody>
</table>
創建'ajaxfile.php'
文件來處理 AJAX 請求。
例如,我在一個文件中同時處理 GET 和 POST 請求。
將 2 分配給$request
.
GET 請求(獲取記錄)
檢查是否$_GET['request']
已設置,如果已設置,則分配$_GET['request']
給$request
。
如果$request == 1
然後從表中獲取所有記錄employee
並分配給$employeeData
. 循環獲取的記錄。
$response
使用 id、emp_name、salary 和 email 鍵進行初始化。
以 JSON 格式返回$response
數組。
POST 請求(插入記錄)
如果$request == 2
然後使用json_decode(file_get_contents("php://input"))
.
為變量賦值並準備 INSERT 查詢。
如果 INSERT 查詢執行成功,則返回1
else 0
。
完成的代碼
<?php
include "config.php";
$request = 2;
// Read $_GET value
if(isset($_GET['request'])){
$request = $_GET['request'];
}
// Fetch records
if($request == 1){
// Select record
$sql = "SELECT * FROM employee";
$employeeData = mysqli_query($con,$sql);
$response = array();
while($row = mysqli_fetch_assoc($employeeData)){
$response[] = array(
"id" => $row['id'],
"emp_name" => $row['emp_name'],
"salary" => $row['salary'],
"email" => $row['email'],
);
}
echo json_encode($response);
exit;
}
// Insert record
if($request == 2){
// Read POST data
$data = json_decode(file_get_contents("php://input"));
$name = $data->name;
$salary = $data->salary;
$email = $data->email;
// Insert record
$sql = "insert into employee(emp_name,salary,email) values('".$name."',".$salary.",'".$email."')";
if(mysqli_query($con,$sql)){
echo 1;
}else{
echo 0;
}
exit;
}
使用XMLHttpRequest
對象發送 AJAX 請求。
.open() –方法接受 3 個參數 –
ajaxfile.php?name=yogesh&city=bhopal
。true
或false
. 默認值為true
。通過true
異步和false
同步請求。.setRequestHeader() -此方法用於設置Content-Type
. 默認情況下,'application/x-www-form-urlencoded'
設置內容類型。您可以更改其值,例如 – application/json
、 multipart/form-data
等。
.onreadystatechange –此屬性調用請求狀態更改。分配一個匿名函數來處理響應。如果this.readyState == 4 && this.status == 200
表示服務器響應已準備好進行處理。
.send() -此方法發送 AJAX 請求。它也用於發送數據。
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "ajaxfile.php?request=1", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
}
};
xhttp.send();
以上語法與 jQuery
$.ajax({ url: 'ajaxfile.php?request=1', type: 'get', 成功: function(response){ } });
application/x-www-form-urlencoded; charset=UTF-8
是默認的 Content-Type 但您可以使用任何其他類型,例如 – application/json
、 multipart/form-data
等。
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = this.responseText;
}
};
var data = {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'};
xhttp.send(JSON.stringify(data));
以上語法與 jQuery
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {name:'yogesh',salary: 35000,email: 'yogesh@makitweb.com'},
success: function(response){
}
});
創建 2 個函數 –
創建 的對象XMLHttpRequest
。在方法中使用參數 ( 'ajaxfile.php?request=1'
)指定 GET 請求和 AJAX 文件路徑。.open()
使用屬性設置Content-type
和處理服務器響應onreadystatechange
。
解析this.responseText
to JSON 對象並選擇<table id='empTable'> <tbody>
並清空它。
循環response
讀取值。創建一個新的表格行元素並在單元格中分配一個響應值。
通過調用send()
方法發送請求。
從文本框中讀取值並將它們分配到變量中。如果變量不為空,則創建一個data
JSON 對象。使用文本框值初始化data
對象。
創建XMLHttpRequest
對象並在方法中指定 POST 請求和 AJAX 文件路徑 ( 'ajaxfile.php'
) .open()
。使用屬性設置Content-type
並'application/json'
處理服務器響應onreadystatechange
。
分配this.responseText
在response
. 如果response == 1
然後警告消息並調用loadEmployees()
函數以獲取記錄。
完成的代碼
loadEmployees();
// Load records with GET request
function loadEmployees() {
var xhttp = new XMLHttpRequest();
// Set GET method and ajax file path with parameter
xhttp.open("GET", "ajaxfile.php?request=1", true);
// Content-type
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// call on request changes state
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Parse this.responseText to JSON object
var response = JSON.parse(this.responseText);
// Select <table id='empTable'> <tbody>
var empTable =
document.getElementById("empTable").getElementsByTagName("tbody")[0];
// Empty the table <tbody>
empTable.innerHTML = "";
// Loop on response object
for (var key in response) {
if (response.hasOwnProperty(key)) {
var val = response[key];
// insert new row
var NewRow = empTable.insertRow(0);
var name_cell = NewRow.insertCell(0);
var username_cell = NewRow.insertCell(1);
var email_cell = NewRow.insertCell(2);
name_cell.innerHTML = val['emp_name'];
username_cell.innerHTML = val['salary'];
email_cell.innerHTML = val['email'];
}
}
}
};
// Send request
xhttp.send();
}
// Insert new record with POST request
function insertNewEmployee() {
var name = document.getElementById('txt_name').value;
var salary = document.getElementById('txt_salary').value;
var email = document.getElementById('txt_email').value;
if(name != '' && salary !='' && email != ''){
var data = {name: name,salary: salary,email: email};
var xhttp = new XMLHttpRequest();
// Set POST method and ajax file path
xhttp.open("POST", "ajaxfile.php", true);
// call on request changes state
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
if(response == 1){
alert("Insert successfully.");
loadEmployees();
}
}
};
// Content-type
xhttp.setRequestHeader("Content-Type", "application/json");
// Send request with data
xhttp.send(JSON.stringify(data));
}
}
使用 XMLHttpRequest 對象發送 AJAX 請求。
在 GET 請求中直接傳遞帶有類似文件名的數據 -ajaxfile.php?name=yogesh&city=bhopal
並在 POST 請求中通過send()
方法傳遞您的數據。
1658018100
動態相關下拉列表根據之前的下拉選擇限制用戶選擇。
在本教程中,我將展示如何使用 JavaScript 和 PHP 使用 MySQL 數據庫數據自動填充下拉列表。
我在示例中使用了 3 個表 –
國家表(存儲國家記錄)-
CREATE TABLE countries (
id serial PRIMARY KEY,
name varchar(80) NOT NULL
)
狀態表(存儲國家/地區的狀態)-
CREATE TABLE states (
id serial PRIMARY KEY,
name varchar(80) NOT NULL,
country_id bigint NOT NULL
)
城市表(存儲各州的城市)-
CREATE TABLE cities (
id serial PRIMARY KEY,
name varchar(80) NOT NULL,
state_id bigint NOT NULL
)
創建一個新config.php
文件。
完成的代碼
<?php
$host = "localhost"; /* Host name */$user = "root"; /* User */$password = "root"; /* Password */$dbname = "tutorial"; /* Database name */
// Create connection
$con = new mysqli($host, $user, $password, $dbname);
// Check connection
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
從表中獲取所有記錄countries
並創建 3 個 <select>
元素 -
<select >
元素是顯示 fetched countries
。完成的代碼
<?php
include "config.php";
// Fetch countries
$sql = "SELECT * from countries order by name";
$stmt = $con->prepare($sql);
$stmt->execute();
$result = $stmt->get_result();
?>
<table>
<tr>
<td>Country</td>
<td>
<select id="country" onchange="getStates(this.value);">
<option value="0" >– Select Country –</option>
<?php
while ($row = $result->fetch_assoc() ){
$id = $row['id'];
$name = $row['name'];
echo "<option value='".$id."' >".$name."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td>State</td>
<td>
<select id="state" onchange="getCities(this.value);" >
<option value="0" >– Select State –</option>
</select>
</td>
</tr>
<tr>
<td>City</td>
<td>
<select id="city" >
<option value="0" >– Select City –</option>
</select>
</td>
</tr>
</table>
創建 ajaxfile.php
文件。
處理 2 個 AJAX 請求 –
states
根據 值 從表中獲取記錄 $country_id
並分配給 $result
. 循環 並使用 和 鍵$result
初始化 $data
Array 。idname
以 JSON 格式返回 $data
。
cities
根據 值 從表中獲取記錄 $state_id
並分配給 $result
. 循環 並使用 和 鍵$result
初始化 $data
Array 。idname
以 JSON 格式返回 $data
。
完成的代碼
<?php
include 'config.php';
// Read POST data
$postData = json_decode(file_get_contents("php://input"));
$request = "";
if(isset($postData->request)){
$request = $postData->request;
}
// Get states
if($request == 'getStates'){
$country_id = 0;
$result = array();$data = array();
if(isset($postData->country_id)){
$country_id = $postData->country_id;
$sql = "SELECT * from states WHERE country_id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $country_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()){
$id = $row['id'];
$name = $row['name'];
$data[] = array(
"id" => $id,
"name" => $name
);
}
}
echo json_encode($data);
die;
}
// Get cities
if($request == 'getCities'){
$state_id = 0;
$result = array();$data = array();
if(isset($postData->state_id)){
$state_id = $postData->state_id;
$sql = "SELECT * from cities WHERE state_id=?";
$stmt = $con->prepare($sql);
$stmt->bind_param("i", $state_id);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()){
$id = $row['id'];
$name = $row['name'];
$data[] = array(
"id" => $id,
"name" => $name
);
}
}
echo json_encode($data);
die;
}
創建 2 個函數 –
空州和城市下拉菜單。將 AJAX POST 請求發送到 ajaxfile.php
,傳遞 {request: 'getStates', country_id: country_id}
為 data
,並設置 dataType: 'json'
。
成功回調循環 response
並添加 <option >
狀態下拉列表。
清空#city
下拉列表並將 AJAX POST 請求發送到 ajaxfile.php
,傳遞 {request: 'getCities', state_id: state_id}
為 data
,並設置 dataType: 'json'
。
成功回調循環 response
並添加 <option >
城市下拉菜單。
完成的代碼
function getStates(country_id){
// Empty the dropdown
var stateel = document.getElementById('state');
var cityel = document.getElementById('city');
stateel.innerHTML = "";
cityel.innerHTML = "";
var stateopt = document.createElement('option');
stateopt.value = 0;
stateopt.innerHTML = '-- Select State --';
stateel.appendChild(stateopt);
var cityopt = document.createElement('option');
cityopt.value = 0;
cityopt.innerHTML = '-- Select City --';
cityel.appendChild(cityopt);
// AJAX request
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = JSON.parse(this.responseText);
var len = 0;
if(response != null){
len = response.length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response[i].id;
var name = response[i].name;
// Add option to state dropdown
var opt = document.createElement('option');
opt.value = id;
opt.innerHTML = name;
stateel.appendChild(opt);
}
}
}
};
var data = {request:'getStates',country_id: country_id};
xhttp.send(JSON.stringify(data));
}
function getCities(state_id){
// Empty the dropdown
var cityel = document.getElementById('city');
cityel.innerHTML = "";
var cityopt = document.createElement('option');
cityopt.value = 0;
cityopt.innerHTML = '-- Select City --';
cityel.appendChild(cityopt);
// AJAX request
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "ajaxfile.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Response
var response = JSON.parse(this.responseText);
var len = 0;
if(response != null){
len = response.length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var id = response[i].id;
var name = response[i].name;
// Add option to city dropdown
var opt = document.createElement('option');
opt.value = id;
opt.innerHTML = name;
cityel.appendChild(opt);
}
}
}
};
var data = {request:'getCities',state_id: state_id};
xhttp.send(JSON.stringify(data));
}
按照相同的步驟自動填充多個下拉列表。
如果在您選擇國家或州時下拉列表中未填充數據,則使用瀏覽器網絡選項卡進行調試。再次檢查 SQL 查詢和 POST 值。