使用HTML,PHP,AJAX将数据插入数据库

I have a HTML form with action to a PHP file (insert.php). This PHP file is inserting my form values into the database (MySQL).

HTML

<form method="post" id="myForm" action="insert.php">
First Name:<input type="text" name="Fname" id="Fname" maxlength="12" size="12"/> <br/>
Mark1:<input type="text" name="Mark1" id="Mark1" maxlength="12" size="12"/> <br/>
<p><input type="submit" id="myButton" value="Submit" /></p>
</form>
<div id="someElement">Response is Here:</div>

the insert.php file is -->

<?php
$con=mysqli_connect("localhost","root","root","student");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO student_details (full_name, mark1) VALUES ('$_POST[Fname]', '$_POST[Mark1]')";

if (!mysqli_query($con,$sql))
  {
  die('Error: ' . mysqli_error($con));
  }
echo "1 record added";

mysqli_close($con);
?> 

There is no problem in data insertion with the above scenario.

I tried the same to do with AJAX and I don't see any result

my Ajax code -->

<script type="text/javascript">

$(document).ready(function(){ 
    $("#myButton").click(function() { 
    alert("am in the function now");
        $.ajax({
        cache: false,
        type: 'POST',
        url: 'insert.php',
        data: $("#myForm").serialize(),
        success: function(d) {
            $("#someElement").html(d);
        }
        });
    }); 
});

</script>

Kindly help me out where I am missing the logic. I am guessing that I am missing something basic somewhere. It's been almost two days of time on this. Thanks in advance.

you should prevent default submit form action

$("#myButton").click(function(e) {
e.preventDefault();
...

If I may suggest, use PHP5 PDO for working with databases.

[1]: http://php.net/manual/en/book.pdo.php php.net pdo

You should change

  • <input type="button" id="myButton" value="Submit" />

  • Also change <form method="post" id="myForm" action="">

  • You should also check using print_r() for checking $_POST array.

  • And try to echo $sql exit; your Query and run in PhpMyadmin for fixing values.

  • Most important you should use mysql_real_escape_string for sanitize data and security.

I guess you are missing quotes around index in $_POST array. Even though it worked in some cases, it may create problem.

Please have a look at these:

Is it okay to use array[key] in PHP?

http://fr2.php.net/manual/en/language.types.array.php#language.types.array.foo-bar

Your problem could be with your sql query. I don't know how did it work without ajax but your should put the index position of $_POST array in single quotes. such as $_POST['name']; Better approach would be, storing them in variables and use these variables instead.

Also change $("#button").click to $("#button").event("click", function(){.....}).