Messaging system in Codeigniter AJAX - php

Good day guys, I don't know how can I make an ajax call on Codeigniter
Is there anyone can show me how to do it here? It will help me too much in my career in programming . I'm watching tutorials but that isn't the way I need.
So here is the process, once I submit a data on the database, the whole page must not load and updates my records on the view. I tried my best, but I think I really need your help now. Advance thank you.
My script
<script>
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: <?php echo base_url()?> + "messages/send_message",
data: {textbox: $("#textbox").val(),owner: $("#owner").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data); //as a debugging message.
}
});// you have missed this bracket
return false;
});
});
</script>
My controller
function send_message()
{
$sk = random_string('alnum',5).time();
$from= $_SESSION['username1'];
$owner = $_POST['owner'];
$desc = $_POST['textbox'];
$to = $this->Model_items->get_owner_name($owner);
$from = $this->Model_items->get_owner_name2($username);
date_default_timezone_set('Asia/Manila');
$date = date("Y-m-d H:i:s");
$data = array('message_from_username'=>$username,'message_to_username'=>$owner,'message_sk'=>$sk,'message_desc'=>$desc,'message_from'=>$from,'message_to'=>$to,'message_date'=>$date,'status'=>1);
$this->Model_messages->message_owner($data);
}
My model
function message_owner($data)
{
$this->db->insert('messages',$data);
}
function view_convo($from,$username)
{
$query = $this->db->query("Select * from messages where
(message_from_username = '$username' AND message_to_username = '$from') OR
(message_from_username = '$from' AND message_to_username = '$username')
order by message_id desc");
return $query->result();
}
And for my views
<div class="col-md-9 ui segment pre-scrollable" style="min-height:100px;">
<h3 class="ui dividing header">Conversation with <?php echo $convo_with?>
</h3>
<div class="ui comments">
<?php
foreach($convo as $key)
{
?>
<div class="comment">
<a class="avatar">
<img src="<?php echo base_url()?>img/default-avatar.png" style="width:30px;height:25px;border-radius:50%;">
</a>
<div class="content">
<a class="author"><?php echo $key->message_from?></a>
<div class="metadata">
<span class="date">
<?php
date_default_timezone_set('Asia/Manila');
$now = strtotime(date("Y-m-d H:i:s"));
$date = strtotime($key->message_date);
$dateDiff = abs($now - $date);
$fullDays = floor($dateDiff/(60*60*24));
if($fullDays==0)
{
echo " Today ";
}
else if($fullDays==1)
{
echo " Yesterday ";
}
else
{
echo $fullDays ." days ago";
}
$at=date('g:iA',$date)
?> at <?php echo $at?>
</span>
</div>
<div class="text">
<?php echo $key->message_desc?>
</div>
</div>
</div>
<?php
}
?>
<br>
</div>
<form method="post">
<input id="owner" type="hidden" value="<?php echo $this->uri->segment(3);?>" name="owner">
<input id="textbox" type="text" name="textbox">
<input id="send" type="submit" name="send" value="Send">
</form>
</div>

You need to send back something to the ajax call
Update your controler function to return a json with the updated list of messages, form that json you use jquery in the success function to update the list of messages
function send_message()
{
$sk = random_string('alnum',5).time();
$from= $_SESSION['username1'];
$owner = $_POST['owner'];
$desc = $_POST['textbox'];
$to = $this->Model_items->get_owner_name($owner);
$from = $this->Model_items->get_owner_name2($username);
date_default_timezone_set('Asia/Manila');
$date = date("Y-m-d H:i:s");
$data = array('message_from_username'=>$username,'message_to_username'=>$owner,'message_sk'=>$sk,'message_desc'=>$desc,'message_from'=>$from,'message_to'=>$to,'message_date'=>$date,'status'=>1);
$this->Model_messages->message_owner($data);
$datareturned = $this->Model_messages->view_convo($from,$to);
return json_encode(array('message'=>'Database Updated successfully','data'=>$datareturned));
}
js:
$(document).ready(function(){
$("#send").click(function()
{
$.ajax({
type: "POST",
url: <?php echo base_url()?> + "messages/send_message",
data: {textbox: $("#textbox").val(),owner: $("#owner").val()},
dataType: "text",
cache:false,
success:
function(data){
alert(data.message); //as a debugging message.
//here you update the message list with the data from "data.data"
//using a loop and append
}
});// you have missed this bracket
return false;
});
});

Controller:
function send_message()
{
$sk = random_string('alnum',5).time();
$from= $_SESSION['username1'];
$owner = $_POST['owner'];
$desc = $_POST['textbox'];
$to = $this->Model_items->get_owner_name($owner);
$from = $this->Model_items->get_owner_name2($username);
date_default_timezone_set('Asia/Manila');
$date = date("Y-m-d H:i:s");
$data = array('message_from_username'=>$username,'message_to_username'=>$owner,'message_sk'=>$sk,'message_desc'=>$desc,'message_from'=>$from,'message_to'=>$to,'message_date'=>$date,'status'=>1);
$value = $this->Model_messages->message_owner($data);
Print_r($value);
die();
}
Use the function in your controller

Related

$_POST value returns blank/empty

I do have a form where the user can retrieve the data depending on the dates selected. Here's what I have:
<form class="form" method="post">
<div class="form-row">
<div class="form-group col-md-2 col-5">
<label class="col-form-label col-form-label-sm" for="From">From</label>
<input type="date" class="form-control" id="fromDate" name="fromDate" value="<?php echo (new DateTime('first day of this month'))->format('Y-m-d');?>">
</div>
<div class="form-group col-md-2 col-5">
<label class="col-form-label col-form-label-sm" for="To">To</label>
<input type="date" class="form-control" id="toDate" name="toDate" value="<?php echo (new DateTime('today'))->format('Y-m-d');?>">
</div>
<div class="form-group col-md-1 col-2">
<label class="col-form-label col-form-label-sm text-white" for="Search">Search</label>
<input type="button" class="btn btn-success btn-block" id="submit" name="submit" value="Submit" onclick="getResult()">
</div>
</div>
</form>
<div id="data_result"></div>
On the same page, I have a script below:
<script>
function getResult(){
var fm = $('#fromDate').val();
var to = $('#toDate').val();
$.ajax({
method: 'POST',
url: 'chart-data/card-sales.php',
data: { fm:fm, to:to },
success: function(data) {
$('#data_result').html(data);
}
});
}
</script>
And finally, my chart-data/card-sales.php file:
<?php
// db settings
$hostname = 'localhost';
$username = 'root';
$password = 'password';
$database = 'accounts';
// db connection
$con = mysqli_connect($hostname, $username, $password, $database) or die("Error " . mysqli_error($con));
$fm = '';
$to = '';
if(isset($_POST['fromDate'],$_POST['toDate']))
{
$date1 = strtr($_POST['fromDate'], '/', '-');
$fm = date('Y-m-d',strtotime($date1));
$date2 = strtr($_POST['toDate'], '/', '-');
$to = date('Y-m-d',strtotime($date2));
} else {
var_dump($_POST);
}
echo'<div id="data_result">
<h6>
<span class="text-danger">'.$fm.'</span> to
<span class="text-danger">'.$to.'</span>
</h6>';
$sql="SELECT * FROM sales WHERE date >='$fm' and date <= '$to'";
foreach ($con->query($sql) as $row) {
echo'//table contents';
};
echo '</div>';
?>
The thing is, $fm and $to returns an empty value (1970-01-01) that is why I couldn't get the proper data I need while the var_dump($_POST); returns array(2) { ["fm"]=> string(10) "2021-01-01" ["to"]=> string(10) "2021-01-26" }. So I think the main problem here is that I cannot get the input value from my form. Why is that so?
The problem is that you're not using the correct indexes on $_POST.
You should use the same indexes that you sent in the ajax: fm and to.
Change this:
if(isset($_POST['fromDate'],$_POST['toDate']))
{
$date1 = strtr($_POST['fromDate'], '/', '-');
$fm = date('Y-m-d',strtotime($date1));
$date2 = strtr($_POST['toDate'], '/', '-');
$to = date('Y-m-d',strtotime($date2));
} else {
var_dump($_POST);
}
To this:
if(isset($_POST['fm'], $_POST['to']))
{
$date1 = strtr($_POST['fm'], '/', '-');
$fm = date('Y-m-d',strtotime($date1));
$date2 = strtr($_POST['to'], '/', '-');
$to = date('Y-m-d',strtotime($date2));
} else {
var_dump($_POST);
}
P.S: Yo should take a look about SQL injection and prepared queries as #Strawberry suggested.
I encourage you to change to an object-oriented aproach using PDO
As you send in your ajax call, data: {fm: fm, to: to} this is what to use.
Try to change:
if (isset ($_POST['fromDate'], $_POST['toDate']))
{
$date1 = strtr($_POST['fromDate'], '/', '-');
...
$date2 = strtr($_POST['toDate'], '/', '-');
...
}
by
if (isset ($_POST['fm'], $_POST['to']))
{
$date1 = strtr($_POST['fm'], '/', '-');
...
$date2 = strtr($_POST['to'], '/', '-');
...
}

Data is not inserting to database but retrieving is working fine using PHP and Ajax?

Before I ask you my question I want to clarify that I'm just a rookie to Ajax and Jquery, so please spare me if the doubt is very small or a piece of cake, sorry for that.
I'm trying to create review system for my E-Commerce using Ajax and PHP. The problem is, the data is not inserting in to the database, but if I insert the the data manually in the database it displaying perfectly in my site.I think there is something going wrong with the variable review or user_review but couldn't find what it is.So, could you please tell me where I've done the mistake.
<div role="tabpanel" class="tab-pane" id="reviews">
<h4>Write your Review</h4>
<form action="" method="post" onsubmit="return post();">
<textarea id="review" class="reviewbox" placeholder="Write Your Review Here....."></textarea>
<button type="submit" class="btn">Submit</button>
</form>
<div id="all_reviews">
<?php
$query = $pdo->prepare("SELECT * FROM reviews WHERE product_id=?");
$query -> bindValue(1, $id);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
$name = $row['user_name'];
$text = $row['review_text'];
$time = $row['post_time'];
?>
<h5>By <?php echo $name; ?></h5>
<p><i>posted on <?php echo $time; ?></i></p>
<p>
<?php echo $text; ?>
</p>
<hr>
<?php
}
?>
</div>
<script type="text/javascript" src="jquery.js">
< script type = "text/javascript" >
function post() {
var review = document.getElementById("review").value;
if (review) {
$.ajax({
type: 'POST',
url: 'post_reviews.php',
data: {
user_review: review
},
success: function(response) {
document.getElementById("all_reviews").innerHTML = response + document.getElementById("all_reviews").innerHTML;
document.getElementById("review").value = "";
}
});
}
return false;
}
</script>
</div>
This is my post_reviews.php:
<?php
session_start();
require('includes/product.php');
require('includes/connect.php');
$product = new Product;
if(isset ($_GET['id'])) {
$id = $_GET['id'];
$data = $product -> fetch_data($id);
if(isset($_POST['user_review'])){
$review=$_POST['user_review'];
if (isset($_SESSION['logged_in'])) {
$query = $pdo -> prepare("INSERT INTO reviews(product_id,user_name,review_text) VALUES (?,?,?)");
$query -> bindValue(1, $id);
$query -> bindValue(2, $_SESSION['name']);
$query -> bindValue(3,$review);
$query ->execute();
}
else{
$review_msg="Please login to post your review";
}
$query = $pdo->prepare("SELECT * FROM reviews WHERE product_id=?");
$query -> bindValue(1, $id);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
$name = $row['user_name'];
$text = $row['review_text'];
$time = $row['post_time'];
?>
<?php if(isset($review_msg)){ ?>
<small style = "color : #aa0000"; ><?php echo $review_msg ?></small>
<br><br>
<?php } ?>
<h5>By <?php echo $name; ?></h5>
<p><i>posted on <?php echo $time; ?></i></p>
<p><?php echo $text; ?></p>
<hr>
<?php
}
}
exit;
}
?>
There is a mistake you have done your script code is not closed
<script type="text/javascript" src="jquery.js">
To
<script type="text/javascript" src="jquery.js"></script>
That is the reason your ajax is not working.
first check your ajax working or not on button click
var review = document.getElementById("review").value;
$.ajax({
type: "POST",
url: "post_reviews.php",
data: review,
cache: false,
dataType: 'json',
success: function(response){
document.getElementById("all_reviews").innerHTML = response + document.getElementById("all_reviews").innerHTML;
document.getElementById("review").value = "";
}
});
return false;
Now I see. You are submiting the form.
<form action="" method="post" onsubmit="return post();">
<textarea id="review" class="reviewbox" placeholder="Write Your Review
Here....."></textarea>
<button type="submit" class="btn">Submit</button>
</form>
Try to replace your form with this:
<form action="" method="post">
<textarea id="review" class="reviewbox" placeholder="Write Your Review
Here....."></textarea>
<button type="button" onclick="post()" class="btn">Submit</button>
</form>
If button type is "button" it will not submit the form. And by clicking it now will call your function and execute ajax call.

How to return output on the same page ajax php

I want to organize the selection query from index.php to action, so i can be able to call the file with ajax to show the data on the page.(index.php). So, the activity I want to do is to able to submit data of the form to the database and to display result on the same page(index.php) without refreshing the page. Help please
Here's my files
1.action.php
2.index.php
3.maker.js
//-----------------------action.php-----------------------------
<?php
include ("db_connect.php"); // Connecting to the database
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$action = $_REQUEST['action'];
if ($action=="add")
{
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
?>
//index.php
<div id="table_content"></div>
<script type="text/javascript" src="maker.js">
<?php
function ShowForm($AnswerCommentId)
{ ?>
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerCommentId);?>"/>
<button type='button' OnClick=SendComment()>Comment</button>
</form>
<?php
}
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
function tree($treeArray, $level, $pid = 0)
{
global $AnswerId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
?>
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60);?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) { echo 'Reply'; }
echo 'Delete';
?> </div> <?php
if ($AnswerId == $item[0])
{
?><div id="InnerDiv"><?php ShowForm($AnswerId); ?></div>
<?php
}
?> </div> <?php
tree($treeArray, $level+1, $item[0]); // Recursion
}
}
}
tree($mytable, 0);
?>
//maker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "index.php",
data: "AnswerId="+id,
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
clean_form();
}
});
return false;
}
So you are basically trying to make ajax based comment system, From what i see, your code organization is not clear based on there tasks, specifically your index.php file so here is what you can do to simplify things :
your action.php should hanlde all php database releted tasks
Move your html code to some other file (Create Template)
Here is the modified code that i have come up with (This is just for your reference, you should modify this accoring to you needs, and as Xorifelse suggested in comment you should always use prepared statements in production system because of security concerns):
Action.php
<?php
include ("db_connect.php"); // Connecting to the database
$action = $_REQUEST['action'];
if ($action=="add")
{
$user = $_REQUEST['user'];
$text = $_REQUEST['text'];
$ParentId = $_REQUEST['ParentId'];
$query="INSERT into `comments` VALUES (NULL,'{$ParentId}','{$user}','{$text}',NOW())";
$result = mysqli_query($conn,$query);
}
if ($action=="delete")
{
$text = $_REQUEST['text'];
$delete = "DELETE FROM `comments` WHERE id=$text";
$result = mysqli_query ($conn,$delete);
}
if ($action=="get")
{
$query="SELECT * FROM `comments` ORDER BY id ASC";
$result = mysqli_query($conn,$query);
if (isset($_REQUEST['AnswerId']))
{ $AnswerId = $_REQUEST['AnswerId']; }
else
{ $AnswerId = 0; }
$i=0;
$mytable = array();
while ($mytablerow = mysqli_fetch_row($result))
{
$mytable[$i] = $mytablerow;
$i++;
}
tree($mytable, 0, $AnswerId);
}
function tree($treeArray, $level, $ansId, $pid = 0)
{
$AnswerId = $ansId;
if (! $treeArray)
{ return; }
foreach($treeArray as $item){
if ($item[1] == $pid)
{
include('comments.template.php');
tree($treeArray, $level+1,$AnswerId, $item[0]); // Recursion
}
}
}
?>
index.php
<html>
<head>
<title>Test page</title>
<script src="https://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript" src="maker.js"></script>
</head>
<body onload="loadComments();">
<div id="table_content">
</div>
</body>
</html>
comments.template.php
<div class="CommentWithReplyDiv" style="margin-left:<?php echo($level*60); ?>px">
<div class="CommentDiv">
<pre class="Message"><?php echo($item[3]) ; ?></pre>
<div class="User"><?php echo($item[2]) ; ?></div>
<div class="Date"><?php echo($item[4]) ; ?></div>
<?php
if ($level<=4) {
echo 'Reply';
}
echo 'Delete';
?>
</div>
<?php if ($AnswerId == $item[0]) { ?>
<div id="InnerDiv"><?php include('commentForm.template.php'); ?></div>
<?php } ?>
commentForm.template.php
<form id="myForm">
<input type="hidden" name="comment_on" id="comment_on" readonly="readonly" value="<?php print md5($_SERVER['PHP_SELF']); ?>" />
<input id="user" name="user" value="name" autocomplete="off" onfocus="if(this.value == 'name'){this.value = ''}" onblur="if(this.value == ''){this.value = 'name'}"/>
<textarea id='text' name='text' value="comment" onfocus="if(this.value == 'comment'){this.value = ''}" onblur="if(this.value == ''){this.value = 'comment'}" ></Textarea>
<input id="ParentId" name="ParentId" type="hidden" value="<?php echo($AnswerId);?>"/>
<button type='button' OnClick="SendComment()">Comment</button>
</form>
marker.js
function DeleteComment(number){
$.ajax({
type: "POST",
url: "action.php",
data: "user=1"+"&text="+number+"&ParentId=1"+"&action=delete",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
}
function AnswerComment (id){
$.ajax({
type: "POST",
url: "action.php",
data: "AnswerId="+id+"&action=get",
success: function(html){
$("#table_content").html(html);
}
});
}
function SendComment (){
var user1 = $("#user").val();
var text1 = $("#text").val();
var ParentId1 = $("#ParentId").val() + "";
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "user="+user1+"&text="+text1+"&ParentId="+ParentId1+"&action=add",
success: function(html){
$("#table_content").html(html);
loadComments();
}
});
return false;
}
function loadComments (){
$.ajax({
type: "POST",
url: "action.php",
cache: false,
data: "action=get",
success: function(html){
$("#table_content").html(html);
//clean_form();
}
});
return false;
}

Ajax form submission with php PDO and return message from server

I'm using below php PDO and ajax program to submit user comment on post.
At first when I did this, it was work fine but now it stopped working what am I doing wrong can someone fix this for me or decide a better way to achieve it?
Problem
Currently, when I submit reply it will post to my database but it will not return back the message from server.
Example: when I post "hello" I expect it to instantly show it without reloading page.
Here is AJAX
<script>
$(document).ready(function(){
$('#add-comment').submit(function()
{
var comment = $('#comment').val();
var name = $('#anony').val();
var rid = $('#rid').val();
$('#response-out').html("<i class='fa fa-spinner fa-spin' style='font-size:19px;'></i>");
$.ajax({
type: 'POST',
url: '/alter_reply.php',
data: 'comment='+comment+'&name='+name+'&rid='+rid,
})
.done(function(data){
$('#response-out').html(data);
})
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>
alter_reply.php
<?php
if($_POST){
$db_host = "localhost";
$db_user = "root";
$db_pass = "pass";
$db_name = "cods";
try {
$db_conn = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("INSERT INTO replys(rid,mesreplys,rtime,rusername) VALUES(:rid,:mesreplys,:rtime,:rusername)");
$stmt->bindParam(':rid', $rid);
$stmt->bindParam(':mesreplys', $comment);
$stmt->bindParam(':rtime', $timedate);
$stmt->bindParam(':rusername', $user);
$form = $_POST;
$rid = mysql_real_escape_string($form['rid']);
$comment = mysql_real_escape_string($form['comment']);
$timedate = date("Y-m-d H:i:s");
if(isset($_SESSION['username'])){
$user = $_SESSION['username'];
}else{
$anony_user = mysql_real_escape_string($form['name']);
$user = $anony_user;
}
$stmt->execute();
//I don't know how to do it again that why i echo back the submitted values
//if you can do it more better for me i will appricite
echo "<td><table>
<tbody>
<tr>
<td class='comment-score'>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</td>";
echo "<td class='comment-text'>
<div style='display: block;' class='comment-body'>";
echo "<span class='comment-copy'>";
echo "$comment";
echo "</span> <a href='' class='comment-user'>";
echo "$user";
echo "</a> <span class='comment-date' dir='ltr'> #<a class='comment-link' href='#'><span title='' class='relativetime-clean'>";
echo "$timedate";
echo "</span></a></span></div></td>";
}
catch(PDOException $e)
{
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}
?>
here is HTML
<div id="response-out" class='comment'> </div>
<form id="add-comment" action="javascript:void(0);" style="font-size: 100%;">
<textarea placeholder="" name="comment" cols="68" rows="3" style="min-height:30px;" id="comment" required="true"></textarea>
<br/>
<?php
if(!isset($_SESSION['username'])) {
echo "<label>Enter name</label><br>";
echo "<input placeholder='Enter a name' style='width:130px;height: inherit;' required='true' id='anony' type='text' name='name'/>";
}?>
<input tabindex="0" value="Add Comment" class="btnpostq" id="donedbtn" type="submit"/>
<input type="hidden" value="<?php echo $_GET['postid'];?>" name="rid" id="rid"/>
</form>
First : please check your php error are displayed.
Then, I suppose you are using are debugger like FireBug to check your javascript and AJAX request.
If not, configure php error and install a debugger for your browser.
If yes, please confirm you have no JS error nor PHP error returne by AJAX.
The purpose of my answer is to first clean your code and try to avoid errors.
Javascript :
<script>
$(document).ready(function(){
$('#add-comment').submit(function()
{
var comment = $('#comment').val();
var rid = $('#rid').val();
// Check if anony exist to avoid JS error
if(0 < $('#anony').length)
{
var name = $('#anony').val();
var dataToSend = 'comment='+comment+'&rid='+rid;
}
else
{
var name = '';
var dataToSend = 'comment='+comment+'&rid='+rid;
}
var dataToSend =
$('#response-out').html("<i class='fa fa-spinner fa-spin' style='font-size:19px;'></i>");
$.ajax({
type: 'POST',
url: '/alter_reply.php',
data: dataToSend,
})
.done(function(data){
$('#response-out').html(data);
})
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>
PHP :
if(0 < sizeof($_POST))
{
//First retrieve your data
$form = $_POST;
$rid = $form['rid'];
$comment = $form['comment'];
$timedate = date("Y-m-d H:i:s");
if(isset($_SESSION['username'])){
$user = $_SESSION['username'];
}else{
$anony_user = $form['name'];
$user = $anony_user;
}
$db_host = "localhost";
$db_user = "root";
$db_pass = "pass";
$db_name = "cods";
try
{
$db_conn = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$db_conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $db_conn->prepare("INSERT INTO replys(rid,mesreplys,rtime,rusername) VALUES(:rid,:mesreplys,:rtime,:rusername)");
//Now you have first retrieve data, you can bind
$stmt->bindParam(':rid', $rid);
$stmt->bindParam(':mesreplys', $comment);
$stmt->bindParam(':rtime', $timedate);
$stmt->bindParam(':rusername', $user);
$stmt->execute();
}
catch(PDOException $e)
{
echo "Error:" . $e->getMessage();
}
$db_conn = null;
//I don't know how to do it again that why i echo back the submitted values
//if you can do it more better for me i will appricite
//Cleaning HTML : your tags where crossing and you were including spans in spans, not sure its usefull
echo
'<table>'.
'<tbody>'.
'<tr>'.
'<td class="comment-score">'.
' '.
'</td>'.
'<td>'.
' '.
'</td>'.
'</tr>'.
'<tr>'.
'<td class="comment-text">'.
'<div style="display: block;" class="comment-body">'.
'<span class="comment-copy">'.$comment.'</span>'.
''.$user.''.
'<span class="comment-date" dir="ltr">'.
'#<a class="comment-link relativetime-clean" href="#">'.$timedate.'</a>'.
'</span>'.
'</div>'.
'</td>'.
'</tr>'.
'</tbody>'.
'</table>';
}
else
{
echo 'no data';
}
I have finally found a solution to my problem
here is what i did and is working fine
$(document).ready(function(e){
$("#add-comment").submit(function(){
var comment = $('#comment').val();
var name = $('#anony').val();
var rid = $('#rid').val();
$.ajax({
url:'/alter_reply.php',
data:'comment='+comment+'&name='+name+'&rid='+rid,
type: "POST",
beforeSend: function(){
$('#response-out').html("<i class='fa fa-spinner fa-spin' style='font-size:19px;'></i>");
},
success: function(data){
$('#response-out').html(data);
}
});
});
});

Issue with using ajax to update without refresh

I have this code here which is supposed to help me update a phone number.
It doesn't do it though, well, i get the successfully changed message but no insertion on the database.
Here is my code:
index.php
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var phone = $("#phone").val();
var dataString = 'phone='+ phone ;
if(phone=='') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "update-phone.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<div class="modal" style="display: none;">
<?php
if (empty($phone)) {
?>
<form method="post" name="form">
<input id="phone" name="phone" type="text" />
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
update-phone.php
<?php
require_once('db.php');
if($_POST) {
$phone = $_POST['phone'];
mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
}else {}
?>
What am i missing?
Thanks
Try this..
<?php
require_once('db.php');
if($_POST) {
$phone = $_POST['phone'];
mysql_query("UPDATE `users` SET `phone` = '$phone' WHERE `ID` = 5884 ");
}else {}
?>
Have you tried inspecting the ajax request with firebug/developer tools/etc?
Try adding echo mysql_error(); right after your mysql_query.
Not 100% sure but it could be the if ($_POST) should be replaced with if (isset($_POST['phone']))
Try the following php:
<?php
require_once('db.hp');
if (isset($_POST['phone']))
{
$phone = $_POST['phone'];
mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
echo mysql_error();
}
else
{
echo "Failed";
}
?>
EDIT: Have you confirmed if it actually updates the DB?
Also you should also sanitise your input and consider rolling with mysqli instead of mysql_*

Categories