Click here to Skip to main content
15,889,335 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
Hello. As in the title.I would like to write such a 'system'. Someone knows how I can do it? I don't know how I can use Ajax. Please somebody help me. Okay to the point.
I want send data to addcomment.php
PHP
<form method="post" action="addcomment.php">
<input type="hidden" name="nick" id="nick_ajax" value="'.$_SESSION['user'].'" />
<input type="text"id="content_ajax" placeholder="Write a comment..." name="content" />
<input type="hidden" name="id" id="id_content_ajax" value="'.$article['id'].'" />
<input type="submit" id="o_sl" name="sent" value="Send" />
</form>


Script addcomment.php
PHP
<?php
	require_once('config/config.php');
	if($_POST['sent']){
		$nick = $_POST['nick'];
		$content = $_POST['content'];
		$postID = $_POST['id'];
		
		$sql_comment = $PDO->prepare('insert into `comments` (`nick`,`content`,`postID`) values (:nick,:content,:id)');
		$sql_comment->execute(array(':nick' => $nick, ':content' => $content, ':id' => $postID));
		header('Location: home.php?success');
	}
	else {
		header('Location: home.php?fail');
		die();
	}
?>


What I have tried:

JavaScript
$(function() {
     $("#o_sl").click(function() {
     var nick_ajax = $('#nick_ajax').val();
     var content_ajax = $('#content_ajax').val();
     var id_content_ajax = $('#id_content_ajax').val();
     var dataString = '&nick='+ nick_ajax + '&content=' + content_ajax +'&id=' +id_content_ajax;

     $.ajax({
         type: 'POST',
         url: 'add_comment.php',
         data: dataString,
         success: function(data) {
             if( data == '0' )
                 alert( 'Error' );
             else
                 window.location = window.location;
         }
     });
     });
 });
Posted
Updated 15-May-17 0:40am

1 solution

Here's where I learned to do it. AJAX Introduction[^]

Once I got used to the idea I almost never use forms (and thus go to a new page) - just update what I have. If you can master this and extend it, afterward, to something like JSON, you'll be very glad you did.
 
Share this answer
 
Comments
Mike CJ 15-May-17 10:59am    
Okay. So how I can add other variable ?
I have now this code:
$(document).ready(function(){
$('#button').on("click",function(){
var postid = $(this).attr('id');
$.ajax({
url:'comment_post.php',
type: 'post',
data:{'postid': postid
}
});
W Balboos, GHB 15-May-17 11:48am    
The link tells you how ajax is done
As far as jQuery goes . . . I don't use it.

You'll need to put in some effort, here, either to learn to use javaScript/AJAX or stick with your jQuery and hope for someone to help with that.
Mike CJ 15-May-17 12:13pm    
This is very difficult, but fine now I have to learn it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900