如何使用ajax发送表单和id

时间:2014-04-17 10:19:18

标签: javascript php jquery ajax

我已经创建了一个ajax函数来在我的数据库中输入一个表单,但我还需要带上用户ID,这样我才能知道该表属于谁。我用ajax尝试了这个:

data: $("#add_form").serialize(), { id : <?php echo $_SESSION['user_id']; ?> }, 

但是这不起作用,我只是得到了这个错误:Uncaught SyntaxError: Unexpected token ,我如何在Ajax中将我的id发送给我的表单?这是我的表格:

<form action="" method="post" id="add_form" name="add_form">            
<h5>Name: </h5><input type="text" name="name" class="addinput"/>
<h5>Artist: </h5><input type="text" name="artist" class="addinput"/>
<h5>Link to song: </h5><input type="text" name="url" class="addinput"/>
<h5>Lyrics: </h5><textarea name="lyrics" class="addinputtext">Here goes the lyrics...</textarea>
<input type="button" value="Add track" class="loginbtn" /> 
</form>

我的完整ajax电话:

// this is the id of the form
                        $("#add_form").submit(function() {

                            var url = "includes/addtrack.php"; // the script where you handle the form input.

                            $.ajax({
                                   type: "POST",
                                   url: url,
                                   data: $("#add_form").serialize(), { id : <?php echo $_SESSION['user_id']; ?> }, // serializes the form's elements.
                                   success: function(data)
                                   {
                                       alert(data); // show response from the php script.
                                        $.ajax({ //Get the name of the artist 
                                          url: "includes/getsongs.php",
                                          type: "POST",
                                          data: {id: <?php echo $_SESSION["user_id"]; ?>},
                                          success: function(data) {
                                            //called when successful
                                            console.log("The data is:");
                                            console.log(data);
                                            $(".yoursongs").html(data); //Update
                                          },
                                          error: function(e) {
                                            //called when there is an error
                                            console.log(e.message);
                                          }
                                        });
                                   }
                                 });

                            return false; // avoid to execute the actual submit of the form.
                        });

PHP代码

    <?php 

include 'db_connect.php';

$stmt = $mysqli->prepare("INSERT INTO song VALUES (?)");
$stmt->bind_param('ssssi', $name, $artist, $url, $lyrics, $userid);   // bind $sample to the parameter

// escape the POST data for added protection
$name = isset($_POST['name'])
          ? $mysqli->real_escape_string($_POST['name'])
          : '';
$artist = isset($_POST['artist'])
          ? $mysqli->real_escape_string($_POST['artist'])
          : '';
$url = isset($_POST['url'])
          ? $mysqli->real_escape_string($_POST['url'])
          : '';
$lyrics = isset($_POST['lyrics'])
          ? $mysqli->real_escape_string($_POST['lyrics'])
          : '';
$userid = isset($_POST['userid'])
          ? $mysqli->real_escape_string($_POST['userid'])
          : '';

/* execute prepared statement */
$stmt->execute();

printf("%d Row inserted.\n", $stmt->affected_rows);
echo 'done';

/* close statement and connection */
$stmt->close();


?>

2 个答案:

答案 0 :(得分:2)

目前您的data未正确设置,因为serialize()会将表单值转换为查询字符串,因此您可以使用&id值连接到此字符串:

data : $('#add_form').serialize() + "&id=" + <?php echo $_SESSION['user_id']; ?>,

而不是:

data: $("#add_form").serialize(), { id : <?php echo $_SESSION['user_id']; ?> },

答案 1 :(得分:0)

您可以使用以下代码通过ajax

发布值
var queryString = $('#formId').serialize();

queryString     += '&id='+ <?php echo $_SESSION['user_id']; ?>;

$.post('post-url', queryString, function(data) { 
   //validation code 
},"json");