[英]Getting output to update without page load after inserting data into database
I am looking for a way that I can make this part of my code more interactive. 我正在寻找一种使我的代码的这一部分更具交互性的方法。 I send announcements through my form to ajax to my php file and it updates my db successfully. 我通过表单向Ajax发送公告到我的php文件,它成功更新了我的数据库。 My table outputs the data just fine. 我的表输出的数据很好。 How can I make the changes live though. 我如何才能使更改生效。 So if I add a new announcement, how can I get the table to update right away without a page reload? 因此,如果添加新公告,如何在不重新加载页面的情况下立即更新表?
Form to send Announcement 表格发送公告
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
}
$user_stmt->store_result();
$user_result = array();
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
Table 表
<?php
if ($announcements_stmt = $con->prepare("SELECT announcements.id, announcements.user_id, announcements.message, announcements.date, users.username FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
</table>
<?php
}
}
AJAX AJAX
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP file that AJAX sends to AJAX发送到的PHP文件
$announcement_user_id= $_POST['user_id'];
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $announcement_user_id, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
?>
As an example, you could probably do something like this. 例如,您可能可以执行以下操作。
/* insert into db script - more code above not shown */
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
$errors=array();
if( !$stmt2 || $con->error ) $errors[]='Announcement INSERT prepare() failed: ' . htmlspecialchars( $con->error );
if( !$stmt2->bind_param( 'is', $announcement_user_id, $announcement_message ) ) $errors[]='Announcement INSERT bind_param() failed: ' . htmlspecialchars( $stmt2->error );
if( !$stmt2->execute() ) $errors[]='Announcement INSERT execute() failed: ' . htmlspecialchars( $stmt2->error );
echo json_encode( array(
'user' => $announcement_user_id,
'announcement' => $announcement_message,
'status' => empty( $errors ) ? 1 : 0,
'message' => empty( $errors ) ? 'Announcement was added successfully!' : 'Announcement Failed!',
'errors' => $errors ) );
The script will echo back a structured json object to the calling ajax function which can be processed by the assigned callback function. 该脚本会将结构化的json对象回显到调用的ajax函数,该函数可以由分配的回调函数进行处理。 ( success: function (data) {/**/}
) ( success: function (data) {/**/}
)
That callback function could be modified - something like:- 可以修改该回调函数-类似于:-
success: function( data ) {
var json=typeof( data )=='string' ? JSON.parse( data ) : data;
var msg=json.message;
var user=json.user;
var announcement=json.announcement;
var status=parseInt( json.status );
var errors=json.errors;
if( Object.keys( errors ).length==0 && status==1 ){
/*
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html( msg );
$('.announcement_success').delay(5000).fadeOut(400);
*/
/* Insert new row into table - assumed table has an id=updates !!!! */
var tbl=document.getElementById('updates');
var tbody=tbl.querySelectorAll('tbody')[0];
var col=tbl.querySelectorAll('tr');
var last=col[ col.length-1 ].id;
var tr=createNode( 'tr',{}, null );
createNode('td',{innerHTML:'? id ? '},tr);
createNode('td',{innerHTML:user},tr);
createNode('td',{innerHTML:announcement},tr);
createNode('td',{innerHTML:'a date'},tr);
insertAfter( tbody, tr, last );
} else {
var tmp=[];
for( var e in errors ) tmp.push( errors[e] );
alert( tmp.join( String.fromCharCode(10) ) );
}
}
jQuery possibly has similar functions but the above relies upon these:- jQuery可能具有类似的功能,但以上功能依赖于这些功能:
function createNode( t, a, p ) {
var el = ( typeof( t )=='undefined' || t==null ) ? document.createElement( 'div' ) : document.createElement( t );
for( var x in a ) if( a.hasOwnProperty( x ) && x!=='innerHTML' ) el.setAttribute( x, a[ x ] );
if( a.hasOwnProperty('innerHTML') ) el.innerHTML=a.innerHTML;
if( p!=null ) typeof( p )=='object' ? p.appendChild( el ) : document.getElementById( p ).appendChild( el );
return el;
}
function insertAfter( p, n, r ) {
p.insertBefore( n, r.nextSibling );
}
I do not use jQuery so am unfamiliar with it's trickeries - but one thing to remember is to use console.log('some data here...')
in your js code to aid debugging! 我不使用jQuery,所以不熟悉它的诡计-但是要记住的一件事是在您的js代码中使用console.log('some data here...')
来帮助调试! Hope it helps, good luck 希望对您有帮助,祝您好运
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.