I want to mess with jQuery and Ajax for a litt开发者_JAVA百科le while.
For my first I want to create just a single input box, type in my comment and then the comment will appear below. No page refreshes. How can I do this?
The basic idea is that you would have a client side page with a textarea or input. Attach a .click to a submit button and the .click will make a call to a server side script via .ajax.
Client Side:
<script type="text/javascript">
$(document).ready(
$('#submit').click({
$.ajax({
type=POST,
data: "comment="+$("#comments").val(),
dataType: json,
url: 'somePage.php',
success: function(data) {
if(data.error){
alert("server reported error");
}else{
$('#postedComments').append(data);
}
}
});
});
});
</script>
<div id="postedComments></div>
<textarea id="comments"></textarea>
<input type="submit" id="submit" value="Post Comment" />
Server Side:
<?php
if(isset($_POST['comments'])){
//perform Database insert of value $_POST['comments']
if(<database error>){
echo json_encode(array('error'=>'-1'));
}else{
echo json_encode(array('success'=>'1'));
}
}
?>
Basically when client clicks submit, the .ajax posts "comments" to the server side script. The script then procseses request and reports back in json encoding error or success which is how in the success of ajax call you can determine what happened with the server call. Success in the ajax is not success it merely indicates the server responded back, which is why you can encode some message to send back to client script to determine if the server responded with error or success message.
You should post the input box content to the server and append it to the comments upon getting success message from the server.
I have built a jQuery powered ajax comment system similar to that of wordpress. The create/delete actions are all ajax powered.
I done it by manually doing $.post() operations for creating comments and $.get() for deleting comments.
精彩评论