你好,堆栈现在我面临一个问题我无法通过 jQuery Ajax 在数据库中插入数据我已附加所有相关文件任何人都可以通过它我是 php 开发的新手。
**task.php**
<html>
<head>
<style type="text/css">
html, body {
margin: 5px;
padding: 5px;
background: #fff;
}
form {
border: 1px solid #999;
padding: 0.25em;
background: #EEE;
}
div {
padding-bottom: 0.25em;
}
/* essential */
label {
float: left;
width: 6em;
text-align: right;
padding-right: 0.5em;
}
input, textarea {
text-align: left;
width: 200px;
height:30px;
}
input.submit {
margin-left: 6.5em;
width: auto;
}
label, input.submit {
font: normal 0.8em Verdana, Geneva, Arial, Helvetica, sans-serif;
}
</style>
<script src="jquery-3.3.1.js"></script>
<script src="insert.js"></script>
<script>
</script>
</head>
<body>
<h1>FORM</h1>
<form>
<div>
<label>Name:</label>
<input type="text" name="name" id="Name" />
</div>
<div>
<label>Age:</label>
<input type="text" name="age" id="age"/>
</div>
<div>
<label>Email Id:</label>
<input type="text" name="emailId" id="emailId"/>
</div>
<div>
<label>Password:</label>
<input type="text" name="password" id="pass"/>
</div>
<div>
<input type="submit" id="submit" name="submit" value="Submit" onclick="insertData()" />
</div>
</form>
</body>
</html>
这是我的 insert.php 文件,我在其中编写了与插入数据相关的所有查询。
**insert.php**
<?php
include("connection.php");
if(isset($_POST['submit']))
{
$Fname=$_POST["name"];
$Age=$_POST["age"];
$EmailId=$_POST["emailId"];
$Password=$_POST["password"];
$Insert = "INSERT INTO simpleform (Name, Age, Email_Id, Password)
VALUES ('.$Fname.', '.$Age.', '.$EmailId.', '.$Password.')";
$Query=mysqli_query($con, $Insert);
print_r($Insert);
if(!$Query)
{
echo mysqli_error();
}
else
{
echo "Successfully Inserted <br />";
}
}
?>
这是我的 insert.js 文件,我在其中完成了所有与 ajax 相关的工作。
**insert.js**
function insertData() {
debugger;
var name=$("#Name").val();
var age=$("#age").val();
var emailId=$("#emailId").val();
var pass=$("#pass").val();
debugger;
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "kamalesh/insert.php",
data: {name:name,age:age,emailId:emailId,pass:pass},
dataType: "JSON",
success: function(data) {
alert("Data Inserted");
}
});
}
看起来在您的
insert.php
中,当您的 if(isset($_POST['submit']))
函数将参数传递给 insert.js
时,insert.php
会阻止脚本运行。当 AJAX 向 insert.php
传递参数时,isset($_POST['submit'])
将返回 false。
您需要从
if(isset($_POST['submit']))
中删除 nsert.php
。我还建议您阻止表单提交和刷新您的页面。看看e.preventDefault
。
对于您的 $insert 查询,您应该删除“。” “VALUES”中每个变量之前和之后。不需要它们。
// Form
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manpower</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
</head>
<body style="background: #000;">
<div class="container">
<div class="container col-sm-7 mt-5 mb-5">
<div class="card text-center">
<div class="card-header">
<p class="fs-2 text-center">Manpower Form</p>
</div>
<div class="card-body">
<form method="post" id="myform">
<!-- Name -->
<div class="row mb-3">
<label for="inputName" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-10">
<input type="text" id="id" name="id" hidden>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter your name" aria-label="Name">
</div>
</div>
<!-- DOB -->
<div class="row mb-3">
<label for="inputDate" class="col-sm-2 col-form-label">Date of Birth</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="dob" id="dob" aria-label="Date of Birth">
</div>
</div>
<!-- Skill code -->
<div class="row mb-3">
<label for="inputSkill" class="col-sm-2 col-form-label">Skill Code</label>
<div class="col-sm-10">
<select class="form-select" name="skill" id="skill" aria-label="Select Skill">
<option selected disabled>Select Skill</option>
<?php
require_once 'db.php';
$select = "SELECT * FROM mst_skillsets";
$result = pg_query($connection, $select);
if(pg_num_rows($result) > 0){
while($row = pg_fetch_assoc($result)){
$sid = $row['id']; // Use the id as the value
$skillset = $row['skillset'];
echo "<option value='$sid'>$skillset</option>"; // Value is now the id
}
}
?>
</select>
</div>
</div>
<!-- Address -->
<div class="row mb-3">
<label for="inputAddress" class="col-sm-2 col-form-label">Address</label>
<div class="col-sm-10">
<textarea class="form-control" name="address" id="address" rows="2" placeholder="Enter your address"></textarea>
</div>
</div>
<!-- Mobile No -->
<div class="row mb-3">
<label for="inputMobile" class="col-sm-2 col-form-label">Mobile</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="mobile" id="mobile" maxlength="10" placeholder="Enter your mobile number">
</div>
</div>
<!-- Email -->
<div class="row mb-3">
<label for="exampleEmail" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email">
</div>
</div>
<!-- Remarks -->
<div class="row mb-3">
<label for="inputRemarks" class="col-sm-2 col-form-label">Remarks</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="remark" id="remark" placeholder="Any remarks">
</div>
</div>
<div class="row mb-3 mt-3">
<button class="btn btn-primary rounded-pill" type="button" id="submit" name="submit">Submit</button>
<button class="btn btn-success rounded-pill" type="button" id="update" name="update" style="display: none;">Update</button>
</div>
</form>
</div>
</div>
</div>
<!-- Table -->
<div class="container col-sm-12 mt-5" id="mantable">
<!-- The data table will be loaded here -->
</div>
</div>
<script>
$(document).ready(function () {
// Load Data Table
$('#mantable').load('mantable.php');
// Regex code for text & number
$(document).on('keyup blur', '#name', function () {
$(this).val($(this).val().replace(/[^A-Za-z ]/g, ''));
});
$(document).on('keyup blur', '#mobile', function () {
$(this).val($(this).val().replace(/[^0-9]/g, ''));
});
// Form Submit
$(document).on('click', "#submit", function () {
try {
if ($("#name").val().length == 0) {
throw { msg: "Enter your name", foc: "#name" };
}
if ($("#dob").val().length == 0) {
throw { msg: "Enter your date of birth", foc: "#dob" };
}
// Calculate age
var dob = new Date($("#dob").val());
var age = new Date().getFullYear() - dob.getFullYear();
var monthDifference = new Date().getMonth() - dob.getMonth();
if (monthDifference < 0 || (monthDifference === 0 && new Date().getDate() < dob.getDate())) {
age--;
}
if (age < 25) {
throw { msg: "You must be at least 25 years old.", foc: "#dob" };
}
if ($('#skill').val().length == 0) { //Select Skill
throw { msg: 'Choose a Skill', foc: '#skill' };
}
if ($('#address').val().length == 0) {
throw { msg: 'Enter your address', foc: '#address' };
}
if ($("#mobile").val().length == 0) {
throw { msg: "Enter mobile number", foc: "#mobile" };
}
if (!$('#mobile').val().match('[6-9]{1}[0-9]{9}')) {
throw { msg: "Invalid mobile number", foc: "#mobile" };
}
if (['6666666666', '7777777777', '8888888888', '9999999999'].includes($('#mobile').val())) {
throw { msg: "Repeated numbers not allowed", foc: "#mobile" };
}
if ($('#email').val().length == 0) {
throw { msg: 'Enter your Email', foc: '#email' };
}
if (!$('#email').val().match(/^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/)) {
throw { msg: "Enter valid Email", foc: "#email" };
}
$.ajax({
url: 'insertman.php',
type: 'post',
dataType: 'html',
data: $('#myform').serialize(),
success: function (s) {
console.log(s);
alert(s);
$('#myform')[0].reset();
$('#mantable').load('mantable.php');
},
error: function(xhr, status, error) {
alert("Request failed: " + error);
}
});
} catch (e) {
alert(e.msg);
$(e.foc).focus();
}
});
// Update
$('#update').click(function () {
$.ajax({
url: 'updateman.php',
type: 'post',
dataType: 'html',
data: $('#myform').serialize(),
success: function (s) {
alert(s);
$('#myform')[0].reset();
$('#submit').show();
$('#update').css('display', 'none');
$('#mantable').load('mantable.php');
}
});
});
});
</script>
</body>
</html>
// Table
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Man Table</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet"/>
</head>
<body>
<p class="fs-3 text-center fw-bold">Existing Man Data</p>
<table class="table" id="table">
<thead>
<tr class="text-primary">
<th scope="col">Man Id</th>
<th scope="col">Name</th>
<th scope="col">DOB</th>
<th scope="col">Skill</th>
<th scope="col">Address</th>
<th scope="col">Mobile</th>
<th scope="col">Email</th>
<th scope="col">Remarks</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody>
<!-- Data will be appended here -->
</tbody>
</table>
<script>
$(document).ready(function () {
// Fetch and populate table
$.ajax({
url: 'fetchman.php',
method: 'post',
dataType: 'json',
success: function(response) {
console.log(response);
var data = response;
for (i in data) {
console.log("Table Data", data);
$("table").append(
"<tr id='" + data[i].manid + "'><td>" + data[i].manid + "</td>" +
"<td>" + data[i].name + "</td>" +
"<td>" + data[i].date_of_birth + "</td>" +
"<td>" + data[i].skill_code + "</td>" +
"<td>" + data[i].address + "</td>" +
"<td>" + data[i].mobileno + "</td>" +
"<td>" + data[i].email + "</td>" +
"<td>" + data[i].remarks + "</td>" +
"<td>" + '<i class="fas fa-pen text-warning" id="edit"></i>' + "</td>" +
"<td>" + '<i class="far fa-trash-alt text-danger" id="delete"></i>' + "</td></tr>");
}
},
error: function(xhr, status, error) {
// alert("Request failed: " + error);
}
});
// Delete
$(document).ready(function(){
$("#table").on('click','#delete',function(){
var id = $(this).parents("tr").attr("id");
console.log("Deleting record with manid: ", id); // Log the ID
if(confirm('Are you sure to remove this record ?'))
{
$.ajax({
url: 'deleteman.php',
type: 'GET',
data: {id: id},
error: function() {
alert('Something went wrong while deleting the record.');
},
success: function(data) {
console.log(data);
alert("Record removed successfully");
$("#"+id).remove();
}
});
}
});
});
// Edit
$('#table').on('click', '#edit', function () {
var id = $(this).closest("tr").attr("id");
if (confirm('Are you sure you want to edit this record?')) {
$.ajax({
url: 'editman.php',
type: 'GET',
data: { id: id },
success: function (response) {
$('#submit').hide();
$('#update').css('display', 'block');
var data = JSON.parse(response);
for(i in data){
$('#id').val(data[i].manid);
$('#name').val(data[i].name);
$('#dob').val(data[i].date_of_birth);
$('#skill').val(data[i].skill_code);
$('#address').val(data[i].address);
$('#mobile').val(data[i].mobileno);
$('#email').val(data[i].email);
$('#remark').val(data[i].remarks);
}
},
error: function() {
alert('Something went wrong while fetching the record.');
}
});
}
});
});
</script>
</body>
</html>