2016-04-28 52 views
0

我建立使用AJAX形式和遇到一个问题:空白值 - Ajax表单

每当我提交表单,存储在数据库中的值变为空白......(仅供参考,当然页不刷新..这是整点)

Blank Values

这里是我的文件的index.php

<!doctype html> 
<html> 
<head> 
    <title>Form Practice</title> 
</head> 
<body> 
    <div id="myForm"> 
     Name: <input name="username" type="radio" value="Sagar">Sagar</input> 
       <input name="username" type="radio" value="Saransh">Saransh</input><br /><br /> 
     Profession: <input name="profession" type="radio" value="Coder">Coder</input> 
        <input name="profession" type="radio" value="Entrepreneur">Entrepreneur</input> 
        <input name="profession" type="radio" value="Blogger">Blogger</input><br /><br /> 
     <input type="submit" id="submit" value="Submit"></input> 
    </div> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script> 
    $.ajax({ 
     url: "data.php", 
     type: "POST", 
     async: false, 
     data:{ 
      "username":$('input[name=username]:checked', '#myForm').val(), 
      "profession": $('input[name=profession]:checked', '#myForm').val() 
     } 
    }); 
</script> 
</body> 
</html> 

而且我Data.php

<?php 

require 'connect.php'; 

$db_selected = mysql_select_db(DB_NAME, $link); 

if(!$db_selected){ 
    die('cant use'. DB_NAME . ':'. mysql_error()); 
} 

$username = $_POST['username']; 
$profession = $_POST['profession']; 

$sql = mysql_query("INSERT INTO info (Name, Profession) VALUES('{$username}', '{$profession}')"); 

if(!mysql_query($sql)){ 
    die('Some Error '. mysql_error()); 
} 

mysql_close(); 
?> 
<!doctype html> 
<html> 
<head> 
    <title>Data</title> 
</head> 
<body> 

</body> 
</html> 
+0

你有回声出的userame和职业,以确保数据被发送通过ajax后? – Matt

+0

页面甚至没有刷新..所以在data.php中回显用户名没有意义。如果你要求在index.php本身回显它,那么这个变量就不存在,因为我们还没有提交表单。所以,无论哪种方式它不会帮助。 –

回答

0

试试这个

<script>  
    $(document).ready(function(){ 

     $('#submit').on('click', function(){ 

      $.ajax({ 
       type: 'POST', 
       async: false, 
       url: 'data.php', 
       data:{ 
        "username":$('input[name=username]:checked', '#myForm').val(), 
        "profession": $('input[name=profession]:checked', '#myForm').val() 
       }, 
       success: function(response) 
       {  

       } 
      }).error(function(request, status, error){ 
       console.log(e); 
      }); 
    }); 

    }); 
</script> 
0

编辑与此

<script>  
     $(document).ready(function(){ 
      $('#submit').on('click', function(){ 
       var username=$('input[name="username"]:checked').val(); 
       var profession=$('input[name="profession"]:checked').val(); 
       $.ajax({ 
        type: 'POST', 
        async: false, 
        url: 'data.php', 
        data:"username=" + username+ "&profession="+ profession, 
        success: function(response) 
        {  

        } 
       }).error(function(request, status, error){ 
        console.log(e); 
       }); 
     }); 

     }); 
    </script>