2015-12-15 26 views
0

我想使用JavaScript和PHP做一個註冊表單,但我遇到了一個問題。 JavaScript代碼不會將數組發送到register_submit.php。我試着在互聯網和StackOverflow上的其他帖子上查找一些例子,但沒有一個答案似乎解決了我自己的問題。數據沒有被髮送到一個JavaScript函數的PHP表格

用戶來到registration.php頁面,填寫表單並點擊調用checkForms()方法的提交按鈕。 setValues()方法將註冊表單中的值設置爲單個變量。我檢查了檢索的變量是否正確(他們是)。

編輯:問題不是有兩個$密碼變量的事實。意外測試錯誤。

JavaScript代碼:

function checkForms() { 
    setValues(); 
    callPHP(); 
} 

function callPHP() { 


    alert(registration.emailR); 
     // call ajax 
     $.ajax({ 
      type: "POST", 
      url: 'register_submit.php', 
      data:{name:registration.usernameR, email:registration.emailR, password:registration.password1R, forename:registration.forenameR, surname:registration.surnameR, country:registration.countryR, dob:registration.dobR}, 
      success:function(msg) { 
       alert("Register Complete");  
      }  
     }); 

     // Go to homepage 
     window.location.href = "index.php"; 

} 

PHP代碼:

<?php 
    $username = $_POST['username']; 
    $email = $_POST['email']; 
    $password = $_POST['password']; 
    $forename = $_POST['forename']; 
    $surname = $_POST['surname']; 
    $country = $_POST['country']; 
    $dob = $_POST['dob']; 

    $host = "host"; 
    $user = "user"; 
    $password = "password"; 
    $database = "database"; 

$con = new mysqli($host, $user, $password, $database); 

if(!$con) 
    die('Connection failed'.mysql_error()); 
else echo "Connection successful "; 
mysqli_select_db($con, $database); 

     $query = "INSERT INTO user (userID, username, dob, email, password, isAuthor, isAdmin, country, surname, firstname) VALUES ('user001', '$username', '$dob', '$email', '$password', '0', '0', '$country', '$surname', '$forename')"; 
     echo $query; 
     mysqli_query($con, $query); 
     echo "Registration Complete!!"; 
?> 
+1

你爲什麼這樣做:'window.location.href =「的index.php」'因爲你是重裝頁_before_你的Ajax已發送...... – somethinghere

回答

3

Ajax是asyncronous這意味着它在後臺運行,直到任務完成後,你從阿賈克斯之前的頁面導航離開用這條線完成:

window.location.href = "index.php"; 

把它放在成功的方法裏面:

success:function(msg) 
{ 
    alert ("Register Complete"); 
    window.location.href = "index.php"; 
} 
+0

工程。我感覺像一個阻礙。謝謝。 – Lemoncide