[英]Sending json data via post .ajax() and also receiving a json response
請在我目前正在編碼的注冊頁面上需要幫助。 我已經在這個死胡同里呆了兩天了。 如果有人可以幫助調試我的代碼,我將不勝感激。
問題
我正在使用 javascript 來驗證表單是否存在錯誤。 如果沒有錯誤,腳本應該使用 .ajax() 通過 post 方法提交表單數據,並返回一個 json 響應。
如果用戶名或電子郵件已經存在,則響應將是錯誤的。 該腳本處理表單驗證,但不提交表單或得到任何響應。
以下是我的代碼:
Javascript
var errorcheck;
var errorcheck1;
function validateForm() {
/*
error handling codes
*/
errorcheck1 = errorcheck;
errorcheck = 0;
};
$('form').on('submit', function(e) {
e.preventDefault();
validateForm();
if(errorcheck1 < 9){
//prevent the form form submitting
e.preventDefault();
} else {
document.getElementById("sendbtn").innerHTML = "Registering...";
var sendInfo = { firstname: firstnameValue, lastname: lastnameValue, email: emailValue, username: usernameValue, userpassword: passwordValue, country: countryValue, state: stateValue, zip: zipcodeValue };
$.ajax({
url:"signup-exec.php",
method:"POST",
data: sendInfo,
dataType:"JSON",
success: function(result){
//if the result is 10
if(result.status == 10){
window.location.href = '../welcome';
}else if(result.status == '11'){
document.getElementById('formerrorbox').style.display='block';
document.getElementById('formerrorbox').innerHTML='Email is already registered';
document.getElementById("sendbtn").innerHTML = "Get Started";
}else if(result.status == 12){
document.getElementById('passwordbox').style.display='block';
document.getElementById("sendbtn").innerHTML = "Get Started";
}else{
document.getElementById('formerrorbox').style.display='block';
document.getElementById('formerrorbox').innerHTML='Trouble connecting to server.';
document.getElementById("sendbtn").innerHTML = "Get Started";
}
}
});
PHP
<?php
session_start();
include ('../config.php');
$firstname= strtolower($_POST['firstnameValue']);
$lastname= strtolower($_POST['lastnameValue']);
$phone= strtolower($_POST['phoneValue']);
$email= strtolower($_POST['emailValue']);
$username= strtolower($_POST['usernameValue']);
$userPassword= $_POST['passwordValue'];
$country= $_POST['countryValue'];
$state= $_POST['stateValue'];
$zipcode= $_POST['zipcodeValue'];
$check_email=mysqli_query($conn, "SELECT * FROM users WHERE email='$email'");
$count_email=mysqli_num_rows($check_email);
$check_username=mysqli_query($conn, "SELECT * FROM users WHERE username='$username'");
$count_username=mysqli_num_rows($check_username);
if($count_email !=0 || $count_username != 0){
$data["status"] = '11';
echo json_encode($data);
exit();
}
提前致謝!
您正在嘗試使用此 Handel multipart/form-data
使用$_POST
發送json
數據和 Handel 數據,確保使用JSON
正確發送請求,然后使用 PHP 發送 Handel 請求數據。
// Takes raw data from the request
$json = file_get_contents('php://input');
// Converts it into a PHP object
$data = json_decode($json);
來源: geeksforgeeks
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.