我有以下PHP
代码处理由JSON
AJAX
对象
我的问题是没有任何东西被添加到MySql表中。因此,我一直将referenceNumber
视为空。
有什么建议吗?
PHP
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$firstName = $_POST["firstName"];
$lastName = $_POST['lastName'];
$name = $firstName. ' ' .$lastName ;
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$hear = $_POST['hear'];
$message = $_POST['message'];
date_default_timezone_set("EST");
$date = date("Y.m.d"); // 2015.10.01
$day = date("l"); // Sunday
$time = date("g:ia"); // 1:25am
// Create connection
$conn = new mysqli("localhost", "aaa", "xxx", "onlineMessages");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$add = mysqli_query("INSERT INTO `test` (`Date`, `Day`, `Time`, `Name`, `Email`, `Phone`, `Subject`, `From`, `Message`)
VALUES ('$date','$day','$time','$name','$email','$phone','$subject','$hear','$message')");
$get_ref_number = mysqli_query(" SELECT `Reference #` FROM `test` where Name='$name' and Phone='$phone' and Message='$message' ");
$ref_number_fetch = mysqli_fetch_array($get_ref_number);
$ref_number = $ref_number_fetch['Reference #'];
// Close connection
mysqli_close($link);
//Returned Data
$arr = array('Name' => $name, 'Phone' => $phone, 'referenceNumber' => $ref_number);
echo json_encode($arr);
}
?>
JS
$(document).ready(function(){
var form = $('#contact-form');
form.submit(function(){
var data = {
"action": "test"
};
data = form.serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: form.attr('action'),
data: data,
success: function(data) {
$(".the-return").html(
data["Name"] + data["Phone"] + data["referenceNumber"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
},
error : function(){
form.html("Error!" + data["json"]);
}
});
return false;
});
});