2

3 つのことが進行中です。

次の HTML フォームを使用して jQuery に情報を送信しています。

        <div id="note_add_container">
            <form id="note_add" method="post">
                <input type="text" name="name" placeholder="name" />
                <input type="text" name="location" placeholder="location" />
                <button id="submit_note">Add note!</button>
            </form>
        </div>

これは、そのようなシリアル化された情報をデータベースに投稿するために使用している jQuery スクリプトです。

   $('button').click(function () {  
        $.ajax ({
            type: "POST",
            url: "post.php",
            data: $('#note_add').serialize(), 
            success: function(){
                  alert("Done"); 
            }
        });    
    });

これは、情報をデータベースに挿入する PHP です。

$name = $_POST['name'];
$location = $_POST['location'];

$sql = "INSERT INTO get (name, location)
VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
    die('Error: ' . mysqli_error($link));
}

これは動作しません。ボタンをクリックしても何も起こりません。アラートは発生しません。私のコードが機能しない理由について、誰かが私を正しい方向に導くことができますか?

4

5 に答える 5

0

呼び出しで指定したコールバック関数$.ajaxは、サーバーから応答を受信したときにのみ起動します。データがデータベースに挿入された後、サーバーからクライアントに何も送信しないため、クライアントが を呼び出すことはありませんalert("Done");。SQL の挿入が成功した後にクライアントに応答を送信する行を PHP ファイルに追加します。応答は、{'status': 'success'}.

于 2013-10-06T04:40:20.870 に答える
0

フォームを処理するためのより良い方法を適用する必要があります。serialize() が役立ちますが、データを JSON 文字列に変換する方が適切です。JSO を使用する場合は、ajax 呼び出しで dataType も設定する必要があります。

$('#note_add').submit(function (event) {
    event.preventDefault();

    var formdata = $('#note_add').serializeArray();
    var formobject = {};

    $(formdata).each(function (event) {
        formobject[formdata[event].name] = formdata[event].value;
    });

    var data = {
        action: "formsend",
        json: JSON.stringify(formobject)
    };

    //* * send with ajax * *

    function sendajax(data) {
        var deferred = $.ajax({
            method: "post",
            url: "ajax.php",
            dataType: "json",
            data: data
        });
        return deferred.promise();
    }

    sendajax(formdata).done(function (response) {
        console.log(response);
        if (response.success == true) {
            alert("Done!");
        }
    })
});

PHPでキャッチ

if(isset($_POST['action']) && $_POST['action'] == 'formsend') {

  $data = json_decode($_POST['json'];

// here you can now access the $data with the fieldnames

  $name = $data->name;
  $location = $data->location;

 // Write to the database
$sql = "INSERT INTO get (name, location) VALUES ('$name', '$location')";
if (!mysqli_query($connection, $sql)) {
    die('Error: '.mysqli_error($link));
}

if (mysqli_affected_rows($connection) > 0) {
    echo json_encode(array("success" = > true, "message" = > "data is submitted"));
} else {
    echo json_encode(array("success" = > false, "message" = > "an error occurred"));
}
}
于 2013-10-06T05:13:07.247 に答える
-1
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/jquery-1.7.min.js"></script>
<title></title>
</head>
<body>
<div id="note_add_container">
  <form id="note_add" method="post">
    <input type="text" name="name" placeholder="name" />
    <input type="text" name="location" placeholder="location" />
    <button id="submit_note">Add note!</button>
  </form>
</div>
<div id="response"> </div>
</body>
<script type="text/javascript">
        $("#submit_note").click(function() {
            var url = "post.php"; // the script where you handle the form input.
            $.ajax({
                   type: "POST",
                   url: url,
                   data: $("#note_add").serialize(), // serializes the form's elements.
                   success: function(data)
                   {
                       $('#response').empty();
                       $('#response').append(data); // show response from the php script.
                   }
                 });

        return false; // avoid to execute the actual submit of the form.
    });
   </script>
</html>

post.php

// Insert here your connection path

<?php
if((isset($_REQUEST['name']) && trim($_REQUEST['name']) !='') && (isset($_REQUEST['location']) && trim($_REQUEST['location'])!=''))
{           
    $name = addslashes(trim($_REQUEST['name']));
    $location = addslashes(trim($_REQUEST['location']));    

    $sql = "INSERT INTO get (name, location) VALUES ('".$name."', '".$location."')";
    if (!mysqli_query($connection, $sql)) {
    die('Error: ' . mysqli_error($link));
    }

    echo "1 record added";
}
?>
于 2013-10-06T07:25:09.230 に答える