如何处理从jQuery序列化和发送的PHP中的数据?

时间:2011-05-15 20:03:31

标签: php jquery ajax post

我正在努力获得$ .ajax调用以正确地将一些表单数据发送到PHP(它被记录到数据库然后显示)。我很难过,因为我之前有$ .ajax做类似的任务而且工作得很好但我必须在这里找不到一些关键的东西。我已经研究了其他答案(例如this one),但找不到任何表明我当前代码不起作用的内容。任何见解将不胜感激!

表格如下:

            <div id="note_add_container">
                <form id="note_add" method="POST">
                    <input type="text" name="title" placeholder="title" />
                    <input type="text" name="summary" placeholder="summary" />
                    <input type="text" name="details" placeholder="details" />
                    <button id="submit_note">Add note!</button>
                </form>
            </div>

            <div id="entries">
                <!-- AJAX call will populate entries here -->
            </div> 

这是jQuery:

    $('#submit_note').click(function () {
        var text = $.ajax ({
            type: "POST",
            url: "note_process.php",
            data: $('#note_add').serialize(), 
            dataType: "json",
            async: false,
        }).responseText;
        $('#entries').html(text); 
    })

这是PHP note_process.php:

include_once "connect.php";
session_start();

$id = $_SESSION['userid'];
$title = $_POST['title'];
$summary = $_POST['summary'];
$details = $_POST['details'];

$query = mysql_query("INSERT INTO notes (id, title, summary, details) VALUES ('$id', '$title','$summary','$details')");

echo $title . $summary . $details;

4 个答案:

答案 0 :(得分:1)

尝试使用'success',而不是让Ajax请求不是异步...

   $('#submit_note').click(function () {
        $.ajax ({
            type: "POST",
            url: "note_process.php",
            data: $('#note_add').serialize(), 
            success: function(text){
                  $('#entries').html(text); 
            }
        });    
    });

答案 1 :(得分:0)

如果事情仍然无效,我会对你的网址是否准确感到厌倦...... 尝试使用PHP文件的绝对路径,例如“/note_process.php”(或文件相对于站点根目录的位置)

答案 2 :(得分:0)

这是一个猜测:

  1. 您已关闭错误报告(在开发阶段时出现错误)
  2. title列在required表格中为notes
  3. (这是事实)您在$title = $_POST['type'];
  4. 中使用了错误的post参数

    所以:

    1. $title = $_POST['type'];应生成警告,但不会,
    2. $title将为空,您的查询无法插入记录,但您会收到致命错误,但看不到它。

答案 3 :(得分:-1)

我对jsFiddle的调查结果:<button>似乎正在提交表单!?天知道为什么!?解决方案非常简单=)不要使用<button>

用A标签替换BUTTON标签,它可以正常工作。

Jordan Rynard说得好:你确定你的网址有效且正确吗?