我創建了一個ajax函數來在我的數據庫中輸入表單,但是我還需要帶上用戶標識,以便我可以知道該表是屬於哪個表。我已經與阿賈克斯試過這樣:如何使用ajax發送表單和標識
data: $("#add_form").serialize(), { id : <?php echo $_SESSION['user_id']; ?> },
但是,這並不工作,我剛剛得到這個錯誤:Uncaught SyntaxError: Unexpected token ,
如何將我把我的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();
?>
張貼值提供完整的Ajax調用 –
不只是顯示的數據:請提供完整的代碼 –
的路上我通常這是通過向表單添加一個隱藏的輸入,這樣當表單序列化時,會話變量將被包含。 – martincarlin87