I am not able to send parameters to server file via ajax. i have checked comment.php with get parameters its working fine. But with ajax post parameter are not received by comment.php and else condition executes
Request Payload inside headers show url parameters received by server but when i echo $_POST array die(print_r($_REQUEST));
it gives me empty array
Here is the code i am using
<input type="text" name="comment" id="q_comment" placeholder="Add a comment" onKeyPress="postComment('q_comment')" autocomplete="off">
<script>
function $(id){
return document.getElementById(id);
}
document.onkeydown = function(event){
key_code = event.keyCode;
}
function postComment(comment_type){
if(key_code == 13){//If enter is pressed
if(comment_type == "q_comment"){//if comment added in question
var comment = $("q_comment").value;
}
else{//if comment added in answer
var comment = $("a_comment").value;
}
if(comment != ""){
var question_id = "<?php echo $id; ?>";//Returns current question id
//var params = "comment="+comment+"&question_id="+question_id;
var params = "question_id="+question_id+"&comment="+comment;//data to send to server
var ajax = new XMLHttpRequest();
ajax.open("POST","/ajax_call_files/comment.php",true);
ajax.setRequestHeader("Content-type","application/x-www-url-encoded");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
var response = ajax.responseText;
console.log(response);
}
}
ajax.send(params);
console.log(params);
}
}
</script>
Comment.php
if(isset($_POST['comment']) && isset($_POST['question_id']) && !empty($_POST['comment']) && !empty($_POST['question_id'])){
require_once('../db_conn.php');
$user_id = $_SESSION['id'];
$comment = substr($_POST['comment'],0,530);
$comment = htmlspecialchars($comment);
$comment = mysqli_real_escape_string($conn,$comment);
$question_id = preg_replace('#[^0-9]#','',$_POST['question_id']);
$sql = "INSERT INTO comments(question_id,user_id,comment,date_time) VALUES('$question_id','$user_id','$comment',now())";
$query = mysqli_query($conn,$sql);
if($query){
echo mysqli_insert_id($conn);
}
else{
echo "Comment not added. Try again later";
}
}
else{
echo "no data recieved";
}
i have rewrite rule on file from which i am calling ajax. could it be the reason why url parameters are not received by the server this is the rule i am using
RewriteRule ^questions/([0-9]+)/([a-zA-Z0-9_]+) questions.php?id=$1&title=$2 [NC,L]