Below is a php code for inserting comment to a post, It works fine now I want to add ajax code to add comments live (without page being refreshed). I prefer ajax code and php code on same page because code will be carrying id's of users so don't want to send such data to another page through ajax/js. I am not good at programming tried few ajax codes but failed so if anyone can help me with ajax code will be thankful.

<?php
   if(isset($_POST['submit'])) {
     $comment=strip_tags($_POST['content']);
     $com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, blog) VALUES (:comment, :userto, :userfrom, :blog)");
     $com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':blog'=>$blogId));
   }
?>

<form method='post' name='form' action='' class='commentbox2'>
<textarea  name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit' class='comment_button'/>
</form>

There are multiple tutorials on this.
Use google - "php and ajax" The W3Schools one is pretty easy to follow, and many others will help you learn what you need to know.

Since you will have user id's and other such security, PHP sessions will help you. Feel free to read up on them as well.
google - "php sessions"

Member Avatar for diafol

I prefer ajax code and php code on same page because code will be carrying id's of users so don't want to send such data to another page through ajax/js

If I understand you right - then this can't be done very easily at all. In fact, you should be discouraged from doing so. I assume you mean js code when you say Ajax code. As ryantroop says, keep id's in session vars, then no need to transport any personal info.

The form and the js (ajax code) go in one file and the php will be in its own file. Ajaxing to itself is nonsensical as you'd probably get a copy of the actual form and everything else (head, css, scripts, etc) in the return data.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.