im new for working with ajax so i have couple of problems:
I have 4 files:
- process.php
- main.php
- style.css
I have some problems with displaying results.I first time working with ajax, this script i found on internet and what to insert in my website. When someone use update status form its works but user cant use comment form, also this comment code working on first status on top. When using ajax i cant order DESC OR ASC result it display down shows all results,when i reload page it showing with order the all code is main.php
What is the best way to using ajax do i need to separate some other way? Like to use all process and html in one page or what? Can u give me some good ajax mysql php tutorials to watch?
In main.php is this code:
<script type="text/javascript">
$(document).ready(function() {
//##### send add record Ajax request to response.php #########
$("#FormSubmit").click(function (e) {
e.preventDefault();
if($("#contentText").val()==='')
{
alert("Please enter some text");
return false;
}
$("#LoadingImage").show().delay(50); //show loading image
var myData = {
content_txt: $("#contentText").val(),
content_privacy: $("#contentPrivacy").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "/process.php?task=update_status", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
$(response).hide().appendTo('#responds').fadeIn();
$("#contentText").val(''); //empty text field on successful
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").delay(50).fadeTo("fast", 0); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$("#FormSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
//##### send add record Ajax request to response.php #########
$("#CommSubmit").click(function (e) {
e.preventDefault();
if($("#commentText").val()==='')
{
alert("Please enter some text");
return false;
}
$("#LoadingImage").show().delay(50); //show loading image
var myData = {
comment_txt: $("#commentText").val(),
status_id: $("#statusID").val()
};
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "/process.php?task=post_comment", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
$(response).hide().appendTo('#responds-comments').fadeIn();
$("#commentText").val(''); //empty text field on successful
$("#CommSubmit").show(); //show submit button
$("#LoadingImage").delay(50).fadeTo("fast", 0); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
$("#CommSubmit").show(); //show submit button
$("#LoadingImage").hide(); //hide loading image
alert(thrownError);
}
});
});
//##### Send delete Ajax request to response.php #########
$("body").on("click", "#responds .del_button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-'); //Split ID string (Split works as PHP explode)
var DbNumberID = clickedID[1]; //and get number from array
var myData = 'recordToDelete='+ DbNumberID; //build a post data structure
$("#LoadingImage").show().delay(50); //show loading image
$('#item_'+DbNumberID).addClass( "sel" ); //change background of this element by adding class
$(this).hide(); //hide currently clicked delete button
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "/process.php?task=delete_status", //Where to make Ajax calls
dataType:"text", // Data type, HTML, json etc.
data:myData, //Form variables
success:function(response){
//on success, hide element user wants to delete.
$('#item_'+DbNumberID).fadeOut();
$("#LoadingImage").delay(50).fadeTo("fast", 0); //hide loading image
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
});
});
</script>
<div class="status">
<div class="update_status ">
<span class="fa fa-refresh fa-spin" id="LoadingImage" style="display:none" /></span>
<ul>
<li class="active"> <span class="glyphicon glyphicon-tasks"></span> <b>Share status</b> </li>
<li> <span class="glyphicon glyphicon-picture"></span> <b>Upload Photo/Album</b> </li>
<li> <span class="glyphicon glyphicon-facetime-video"></span> <b>Upload Video</b> </li>
<li> <span class="glyphicon glyphicon-share"></span> <b>Share Link</b> </li>
</ul>
</div>
<textarea class="textarea" name="content_txt" id="contentText" rows="3" cols="72" placeholder="<?php echo $user['ime']; ?> , what are you doing right now?"></textarea>
<div class="status_below">
<ul>
<a href='#'> <li data-toggle="tooltip" data-placement="top" title="Tag people in this post"> <span class="glyphicon glyphicon-tag"></span> </li> </a>
<a href='#'> <li data-toggle="tooltip" data-placement="top" title="Add location to a post"> <span class="glyphicon glyphicon-map-marker"></span> </li> </a>
<a href='#'> <li data-toggle="tooltip" data-placement="top" title="Add what you filling"> <span class="glyphicon glyphicon-list-alt"></span> </li> </a>
</ul>
<p>
<select name="content_privacy" id="contentPrivacy" class="form-control">
<option value="1">Public</option>
<option value="2">Friends</option>
<option value="0">Only me</option>
</select>
<button id="FormSubmit" class="btn btn-primary btn-sm"><i class="glyphicon glyphicon-ok-sign"></i> POST</button></p>
</div>
</div>
<div class="space"></div>
<ul id="responds">
<?php
$feed = mysql_query("SELECT * FROM posts ORDER BY id DESC");
while($row = mysql_fetch_array($feed)) {
$time = time_ago($row['time']);
$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE userid='{$row[author]}'"));
$content = emoticons($row['content']);
$content_br = nl2br(links($content));
$privacy = $row['privacy'];
if($privacy == "0"){
$prv = "<i data-toggle='tooltip' data-placement='top' title='Shared only to me' class='glyphicon glyphicon-lock'></i> Only me";
} else if($privacy == "1"){
$prv = "<i data-toggle='tooltip' data-placement='top' title='Shared with all members' class='glyphicon glyphicon-globe'></i> Public";
} else if($privacy == "2"){
$prv = "<i data-toggle='tooltip' data-placement='top' title='Shared with your friends/fallowers' class='glyphicon glyphicon-user'></i> Friends";
} else {}
if($row['author'] == $_COOKIE['userid']){
$del_btn = "
<div style='float:right;margin-top:-5px;'>
<div class='btn-group'>
<button type='button' class='btn btn-primary btn-sm dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>
<i class='glyphicon glyphicon-cog'></i>
</button>
<ul class='dropdown-menu'>
<li><a href='#' class='del_button' id='del-$row[id]'> <i class='glyphicon glyphicon-remove'></i> Delete post </a></li>
<li><a href='#'>Action</a></li>
<li><a href='#'>Action</a></li>
<li role='separator' class='divider'></li>
<li><a href='#'>Action</a></li>
</ul>
</div>
</div>
";
} else { $del_btn == ""; }
echo "
<div id='item_$row[id]'>
<div class='widget-body'>
<div class='post-user mt-n-lg'>
<span class='thumb-lg pull-left mr'>
<img style='height:50px;width:50px;' style='border-radius:none;' src='/assets/photos/$user[avatar]' alt='...'>
</span>
$del_btn
<h5 class='mt-sm fw-normal text-white'><a href='#'> $user[ime] $user[prezime] </a> </h5>
<p style='font-size:11px;margin-top:-5px;' class='fs-mini text-muted text-white'><time>$time</time> <span role='presentation' aria-hidden='true'> · </span> $prv </p>
</div>
<p class='text-light fs-mini m text-white'> $content_br </p>
</div>
<footer class='bg-body-light'>
<ul class='post-links'>
<li><a href='#'><span class='text-blue'><i class='glyphicon glyphicon-asterisk'></i> Favorite</span></a></li>
<li><a href='#'><i class='glyphicon glyphicon-comment'></i> Comment</a></li>
<li><a href='#'><i class='glyphicon glyphicon-share'></i> Share</a></li>
<li style='float:right;'><a href='#'> <b><i class='glyphicon glyphicon-asterisk'></i> 69</b> people favorited this.</a></li>
</ul>
"; ?>
<ul id='responds-comments' class='post-comments mt mb-0'>
<?php
$c_q = mysql_query("SELECT * FROM posts_comments WHERE status_id='$row[id]' ORDER BY id DESC");
while($c = mysql_fetch_array($c_q)){
$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE userid='$c[author]'"));
$time = time_ago($c['time']);
$content = links(emoticons($c['content']));
echo "
<li>
<span class='thumb-xs avatar pull-left mr-sm'>
<img style='width:30px;height:30px;' src='/assets/photos/$user[avatar]'>
</span>
<div class='comment-body'>
<h6 class='author fw-semi-bold'> $user[ime] $user[prezime] <small>$time</small></h6>
<p>$content</p>
</div>
</li>";
}
?>
<?php echo "
<li>
<span class='thumb-xs avatar pull-left mr-sm'>
<img style='width:30px;height:30px;' src='/assets/photos/$user[avatar]' alt='...'>
</span>
<div class='comment-body'>
<input type='hidden' name='status_id' id='statusID' value='$row[id]'> <input name='comment_txt' id='commentText' class='form-control input-sm' type='text' placeholder='Write your comment...'> <button id='CommSubmit' class='btn btn-primary btn-sm'><i class='glyphicon glyphicon-ok-sign'></i> POST</button>
</div>
</li>
</ul>
</footer>
</div>
<div class='space'></div>
";
}
?>
</ul>
</div>
In process.php i have this code:
if (isset($_GET['task']) && $_GET['task'] == "update_status") {
if(isset($_POST["content_txt"]) && strlen($_POST["content_txt"])>0) { //check $_POST["content_txt"] is not empty
if(empty($_COOKIE['userid'])){
$_SESSION['error'] = "Error: Please login";
header("location:/index.php#sign-in");
die();
}
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
$author = $_COOKIE['userid'];
$contentToSave = filter_var($_POST["content_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$privacy = filter_var($_POST["content_privacy"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$time = time();
// Insert sanitize string in record
$insert_row = mysql_query("INSERT INTO posts(author,time,content,privacy) VALUES('$author','$time','$contentToSave','$privacy')");
if($insert_row)
{
//Record was successfully inserted, respond result back to index page
$my_id = mysql_insert_id(); //Get ID of last inserted row from MySQL
$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE userid='$author'"));
$post = mysql_fetch_array(mysql_query("SELECT * FROM posts WHERE id='$my_id'"));
$before = time_ago($time);
$content = emoticons($contentToSave);
$content_br = nl2br(links($content));
if($privacy == "0"){
$prv = "<i class='glyphicon glyphicon-lock'></i> Only me";
} else if($privacy == "1"){
$prv = "<i class='glyphicon glyphicon-globe'></i> Public";
} else if($privacy == "2"){
$prv = "<i class='glyphicon glyphicon-user'></i> Friends";
} else {}
if($post['author'] == $_COOKIE['userid']){
$del_btn = "
<div style='float:right;margin-top:-5px;'>
<div class='btn-group'>
<button type='button' class='btn btn-primary btn-sm dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>
<i class='glyphicon glyphicon-cog'></i>
</button>
<ul class='dropdown-menu'>
<li><a href='#' class='del_button' id='del-$my_id'> <i class='glyphicon glyphicon-remove'></i> Delete post </a></li>
<li><a href='#'>Action</a></li>
<li><a href='#'>Action</a></li>
<li role='separator' class='divider'></li>
<li><a href='#'>Action</a></li>
</ul>
</div>
</div>
";
} else { $del_btn == ""; }
echo "
<div id='item_$my_id'>
<div class='widget-body'>
<div class='post-user mt-n-lg'>
<span class='thumb-lg pull-left mr'>
<img style='height:50px;width:50px;' style='border-radius:none;' src='/assets/photos/$user[avatar]' alt='...'>
</span>
$del_btn
<h5 class='mt-sm fw-normal text-white'><a href='#'> $user[ime] $user[prezime] </a> </h5>
<p style='font-size:11px;margin-top:-5px;' class='fs-mini text-muted text-white'><time>Just now</time> <span role='presentation' aria-hidden='true'> · </span> $prv </p>
</div>
<p class='text-light fs-mini m text-white'> $content_br </p>
</div>
<footer class='bg-body-light'>
<ul class='post-links'>
<li><a href='#'><span class='text-blue'><i class='glyphicon glyphicon-asterisk'></i> Favorite</span></a></li>
<li><a href='#'><i class='glyphicon glyphicon-comment'></i> Comment</a></li>
<li><a href='#'><i class='glyphicon glyphicon-share'></i> Share</a></li>
<li style='float:right;'><a href='#'> <b><i class='glyphicon glyphicon-asterisk'></i> 69</b> people favorited this.</a></li>
</ul>
<ul class='post-comments mt mb-0'>
<li>
<span class='thumb-xs avatar pull-left mr-sm'>
<img style='height:30px;width:30px;' style='border-radius:none;' src='/assets/photos/$user[avatar]' alt='...'>
</span>
<div class='comment-body'>
<input type='hidden' name='status_id' id='statusID' value='$my_id'> <input name='comment_txt' id='commentText' class='form-control input-sm' type='text' placeholder='Write your comment...'> <button id='CommSubmit' class='btn btn-primary btn-sm'><i class='glyphicon glyphicon-ok-sign'></i> POST</button>
</div>
</li>
</ul>
</footer>
</div>
<div class='space'></div>
";
}else{
//header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
} else {
$_SESSION['error'] = "e r r o r";
header("location:/index.php");
die();
}
} else if (isset($_GET['task']) && $_GET['task'] == "delete_status") {
if(isset($_POST["recordToDelete"]) && strlen($_POST["recordToDelete"])>0 && is_numeric($_POST["recordToDelete"])){ //do we have a delete request? $_POST["recordToDelete"]
//sanitize post value, PHP filter FILTER_SANITIZE_NUMBER_INT removes all characters except digits, plus and minus sign.
$idToDelete = filter_var($_POST["recordToDelete"],FILTER_SANITIZE_NUMBER_INT);
$kveri = mysql_query("SELECT * FROM posts WHERE id='$idToDelete'");
if(mysql_num_rows($kveri) < 1){
//If mysql delete query was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
//try deleting record using the record ID we received from POST
$delete_row = mysql_query("DELETE FROM posts WHERE id=".$idToDelete);
$delete_row = mysql_query("DELETE FROM posts_comments WHERE status_id=".$idToDelete);
if(!$delete_row)
{
//If mysql delete query was unsuccessful, output error
header('HTTP/1.1 500 Could not delete record!');
exit();
}
} else {
//Output error
header('HTTP/1.1 500 Error occurred, Could not process request!');
exit();
}
} else if (isset($_GET['task']) && $_GET['task'] == "post_comment") {
if(isset($_POST["comment_txt"]) && strlen($_POST["comment_txt"])>0) { //check $_POST["content_txt"] is not empty
if(empty($_COOKIE['userid'])){
$_SESSION['error'] = "Error: Please login";
header("location:/index.php#sign-in");
die();
}
//sanitize post value, PHP filter FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH Strip tags, encode special characters.
$author = $_COOKIE['userid'];
$contentToSave = filter_var($_POST["comment_txt"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$status_id = filter_var($_POST["status_id"],FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$time = time();
// Insert sanitize string in record
$insert_row = mysql_query("INSERT INTO posts_comments(author,time,content,status_id) VALUES('$author','$time','$contentToSave','$status_id')");
if($insert_row)
{
//Record was successfully inserted, respond result back to index page
$my_id = mysql_insert_id(); //Get ID of last inserted row from MySQL
$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE userid='$author'"));
$post = mysql_fetch_array(mysql_query("SELECT * FROM posts WHERE id='$status_id'"));
$before = time_ago($time);
$content = emoticons($contentToSave);
$content_br = links($content);
echo "
<li>
<span class='thumb-xs avatar pull-left mr-sm'>
<img style='width:30px;height:30px;' src='assets/photos/$user[avatar]'>
</span>
<div class='comment-body'>
<h6 class='author fw-semi-bold'><a href=''>$user[ime] $user[prezime]</a> <small>$before</small></h6>
<p>$content_br</p>
</div>
</li>
";
}else{
//header('HTTP/1.1 500 '.mysql_error()); //display sql errors.. must not output sql errors in live mode.
header('HTTP/1.1 500 Looks like mysql error, could not insert record!');
exit();
}
} else {
$_SESSION['error'] = "e r r o r";
header("location:/index.php");
die();
}