Jason Singh Jason Singh - 7 months ago 16
Javascript Question

Blank values stored in database - Ajax Forms

I am building forms using AJAX and encountering a problem:

Whenever I submit the form, the values stored in the database go blank ... (FYI, of course the page doesn't refresh.. that's the whole point.)

Blank Values

Here is my file 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>


And my 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>

Answer

try this

<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>