2016-09-11 12:39
浏览 78

如何使用Jquery ajax和php将数据插入mysql数据库?

I am trying to learn Ajax. I am inserting some data to mysql database from a Html Form by php. It works nicely. But my ajax part does not work. I get the success message but data dont go to my php file. My html and js code:

<!DOCTYPE html>
    <title>Insertion of data with Ajax</title>
    <script src="">    </script>
    <form id="myForm" method="POST" action="ajax-save.php">

    Title: <input type="text" name="title" id="title"><br /><br />
    Description: <textarea name="description" id="description" rows="20" cols="40"></textarea><br /><br />
    Url: <input type="text" name="url" id="url"><br /><br />

    <input type="submit" id="submit" name="submit" value="submit">




            url: 'ajax-save.php',
            async: true,
            cache: false,
            data: $('#myForm').serialize() ,
            type: 'POST',
            success: function(){
           return false;




My php codes are working properly. I have tested it without ajax. Here is my php code.

    $conn = mysql_connect('localhost', 'root', '');
    $db = mysql_select_db('hospital');

    if (isset($_POST['title'])) { $title = $_POST['title'];}
    if (isset($_POST['description'])) { $description = $_POST['description'];}
    if (isset($_POST['url'])) { $url = $_POST['url'];}

        if(mysql_query("insert into `wp_upload_video` (`id`, `title`, `description`, `url`) values (NULL, '$title', '$description', '$url')"))
            echo "Successfully Inserted";
            echo "Insertion Failed";

Please let me know where is my fault.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dongpu5600 2016-09-11 19:35

    When you submit via ajax on a click of the submit button.... that condition is always true.

    Checking if $_POST['submit'] is set in the PHP will always result in true because if it is not true the ajax never gets processed.

    So... remove the if submit condition in the PHP and handle error notification in the ajax call.

    Also, as pointed out by @NiettheDarkAbsol in comments, it's a good idea to add e.preventDefault() to the jquery as well to stop the submit button submitting the form as it normally would and allow the jquery to handle the submit (via ajax).

    解决 无用
    打赏 举报