How to refresh the comments with ajax? - javascript

I was to use ajax to automatically update the page so when a new comment is added I don't have to refresh the page to see it. I have a commented out section in my code where I have tried to do this. I can add posts new comments but when I do I have to refresh the page in order to see the new comment and I just want it to appear automatically when posted.
$(document).ready(function() {
var comments = document.getElementById("allcomments").value;
//Get Storage
var username = window.localStorage.getItem("username");
// Call Ajax for existing comments
$.ajax({
type: 'GET',
url: 'URL.php',
success: function(result) {
var arr = JSON.parse(result);
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
var output = document.getElementById("allcomments");
output.innerHTML += '<div class="comment-container"><div class="username">'+obj.username+'</div><div class="comment">'+obj.comment+'</div><div class="date">'+obj.commDate+'</div><div class="like">'+obj.sentiment+'</div></div>';
}
}
});
return false;
});
/*//Refresh comments
var int=self.setInterval("showComments()",5000);
function showComments(){
$.post("comments.php", function ( arr ) {
$("#allcomments").html( arr );
});
} */
HTML
<h1>Forum</h1>
<form id="forumPost" method='POST'>
<textarea rows="3" col="60" name="comment" placeholder="Create a Post..." id="comment"></textarea>
<button><input type='submit' name='submit' value='Post' class="post"></button>
</form>
<p id="error" class="errormessage"></p>
<p id="allcomments" class="postmessage"></p>
<div class="comment-container">
<div class="username"><!--obj.username--></div>
<div class="comment"><!--obj.comment--></div>
<div class="date"><!--obj.commDate--></div>
<div class="like"><!--obj.sentiment--></div>
</div>
PHP
// Print out existing comment
$query = "SELECT comments.commDate, comments.ID, comments.username, comments.comment, users.username, comments.sentiment FROM comments LEFT JOIN users ON comments.username = users.username";
$result = mysqli_query($db_server, $query);
if (!$result)
die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)) {
$comments[] = $row;
}
mysqli_free_result($result);
require_once("db_close.php");
echo json_encode($comments);

Try removing your code from this block-
$(document).ready(function() {
}
Then change
<button><input type='submit' name='submit' value='Post' class="post"></button>
to:
<button><input type='button' id='submit' value='Post' class="post"></button>
And now put your ajax post code in this block:
$("#submit").on("click", function(){
});

Related

How to get a selected value from HTML and handle it in js or php?

I have created an array of events and now I have a filter by location dropdown. How do I get the value selected in the dropdown and handle it in js or php? Which one would it be better so it shows events from that location and not all the events. I have have different files one for displaying the events (events.js and events.php) and the other files (filterevents.js and filter events.php) this is what I want to handle the filtering in.
HTML
<div class="events">
<form method="POST" id="eventForm">
Filter By Location<br/>
<select name="Locations">
<option value="Leeds">Leeds</option>
<option value="Newcastle">Newcastle</option>
<option value="London">London</option>
</select>
<input type="submit" name="submit" value="Search"/>
</form>
<div class="eventname"><!--obj.eventname--></div>
<div class="date"><!--obj.date--></div>
<div class="time"><!--obj.time--></div>
<div class="location"><!--obj.location--></div>
<p id="error" class="errormessage"></p>
<p id="allevents" class="postmessage"></p>
</div>
events.php
<?php
require_once('checklog.php');
require_once("db_connect.php");
require_once("functions.php");
session_start();
// Print out existing events
$query = "SELECT eventname, date, time, location FROM events ORDER BY eventname";
$result = mysqli_query($db_server, $query);
if (!$result)
die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)) {
$events[] = $row;
}
mysqli_free_result($result);
require_once("db_close.php");
echo json_encode($events);
?>
events.js
$(document).ready(function() {
var events = document.getElementById("allevents").value;
// Call Ajax for existing comments
$.ajax({
type: 'GET',
url: 'events.php',
success: function(result) {
var arr = JSON.parse(result);
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
var output = document.getElementById("allevents");
output.innerHTML += '<div class="comment-container"><div class="eventname">'+obj.eventname+'</div><div class="date">'+obj.date+'</div><div class="time">'+obj.time+'</div><div class="location">'+obj.location+'</div></div>';
}
}
});
filterevents.php
<?php
require_once('checklog.php');
require_once("db_connect.php");
require_once("functions.php");
This is where I want to filter but not sure how to do it.
?>
filterevents.js
// When post button is clicked
$(document).ready(function() {
var forum = $("#eventForm");
$("#eventForm").on('submit', function(event) {
event.preventDefault();
var events = new FormData(this);
if (events) {
// Call Ajax for new comment
$.ajax({
type: 'POST',
url: 'filterevents.php',
data: events,
processData: false,
contentType: false,
success: function(response) {
if(response == "Success")
{
document.getElementById("comment").innerHTML = response;
} else {
document.getElementById("error").innerHTML = response;
}
}
});
} else {
document.getElementById("error").innerHTML = "Please Select A Location";
}
return false;
});
});

Delete any row in MySQL with button click

First, I will summary my demo for you: I have a form for me to type an api link and type of the chart I want to draw from my api link. After that, I will click the button to create chart and insert my input to MySQL database to show it on screen. Each chart have a button for me to delete it if I want.
Everything worked fine except delete funtion to delete my input from database. When I press delete button, it's only delete in html, not delete in my database. Can you help me? Thank you!
Here is my code:
My input form:
<!--HTML Form input-->
<div class = "login-block">
<form id="form1" style="display: block" method="POST" action="chart_test.php">
<!--Input link api-->
<b>Link: </b><input type="text" id="link" name="apilink"><br>
<br>
<!--Chart Type-->
<b>Chart Type:</b>
<label class="custom-select">
<select id="chartType" name="chartType">
<option value="">Select</option>
<option value="pie">Pie Chart</option>
<option value="column">Column Chart</option>
<option value="bar">Bar Chart</option>
</select>
</label>
<br><br>
<!--Button create chart-->
<div class ="wrapper">
<button type="submit" name="create" onClick="drawChart()">Create</button>
<br><br>
</div>
</form>
</div>
Insert input to database and show to screen:
<!--insert form data to mysql-->
<?php
$con = mysql_connect("localhost","root","123456");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysql_select_db("activiti_report");
//check data when first load page to not showing notice error
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$apilink = $_POST["apilink"];
$chartType = $_POST["chartType"];
}
if(isset($_POST['create'])) {
$sql = "INSERT INTO chartinfo (link, typeChart) VALUES ('$apilink', '$chartType')";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
Query database to show chart on screen and the button with script to delete:
<?php //query data from database
$result = mysql_query("SELECT * FROM chartinfo");
?>
<?php //while loop to read data from query result
while($db_field = mysql_fetch_assoc($result)):
?>
<?php //unique chartId for not the same to show more chart
$idChart = 'chartContainer_' . uniqid();
?>
<!--Show chart from database-->
<br>
<div class = "chart-block">
<?php // 2 lines about chart infomation
echo ("<b>API Link:</b> "); print $db_field['link'] . "<BR>";
echo ("<b>Chart Type:</b> "); print $db_field['typeChart'] . "<BR>";
?>
<!-- The <div> and <script> to show the chart -->
<div id="<?=$idChart?>" style="height: 360px; width: 70%;"></div>
<script>
$(document).ready(function() {
var dataPointsA = []
var text = document.getElementById('chartType')
var strChart = text.options[text.selectedIndex].value
$.ajax({
type: 'GET',
url: "<?php echo $db_field['link']?>", //assign URL from query result field
dataType: 'json',
success: function(field) {
for (var i = 0; i < field.length; i++) {
dataPointsA.push({
label: field[i].name,
y: field[i].value
});
}
var chart = new CanvasJS.Chart("<?=$idChart?>", {
title: {
text: "Activiti Report"
},
data: [{
type: "<?php echo $db_field['typeChart']?>", //assign type of chart from query result field
name: "chart",
dataPoints: dataPointsA
}]
});
chart.render();
}
});
});
</script>
<br>
<!--Button to delete the chart and row in database-->
<button type="submit" name="delete" onClick="removeParent(this.parentNode)">Delete</button>
<!--Script remove <div> contain the chart-->
<script>
function removeParent(parent) {
parent.remove();
}
</script>
<!--Script delete form data from mysql-->
<?php
if(isset($_POST['delete'])) {
$sql = "DELETE FROM chartinfo (link, typeChart) WHERE link ='" .$db_field['link']. "' AND typeChart = '" .$db_field['link']. "'";
$result = mysql_query($sql);
header("Location:chart_test.php");
exit;
}
?>
I know I should use mysqli_* instead mysql_* but this is just a demo for me to understand PHP, I learned it only a few days. Sorry for a lot of code but I think I should show to you to understand what I am doing.
Thank you very much!
Your delete button trigger its action from the js code not the php code. It only remove from the view but will appear on reload. You can use ajax in your remove function or use a delete link instead of button
<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php",
data: {id:id},
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>
<button type="submit" name="<?php echo chart id here?>" id="btn_del">Delete</button>
<script>
$("#btn_del).on("click", function(){
var btn_this = $(this);
var id= $(this).attr('name');
$.ajax({
type: 'GET',
url: "delete.php?id="+id,
success: function(resp) {
btn_this.parentNode.remove();
}
});
});
</script>
<?php
if(isset($_GET['id'])) {
$sql = "DELETE FROM chartinfo WHERE link ='" .$_GET['id']. "';
$result = mysql_query($sql);
}
?>

PHP to read DB value, JS to increment it, AJAX to save to DB, but why does it default to 0.0 before refreshing the page?

I am making a temperature target page where the form will read the current target, allow the user to +/- by 0.5 using Javascript buttons and then 'set' the target which takes the new value and saves it back to the database.
I have a working page which can read the DB value and set it, but then automatically reverts to '0.0' as the target. If the page is refreshed then it will display the target, but sometimes saves it at 0.0 in the DB.
I'm very confused as to why as I've spent far too long on this, but its bugging me! Any help is much appreciated, thanks.
Here is my code:
<?php
$conn = connect DB stuff here...
$queryTarget = "SELECT * FROM target;";
$result2 = $conn->query($queryTarget);
$conn->close();
if ($result2->num_rows > 0) {
while($row = $result2->fetch_assoc()) {
$target = $row['target'];
}
}
?>
<form id="input" method="post" action="">
Temp <input type="text" value="<?php echo $target; ?>" name="temp" id="temp" >
<input type="button" id="Up" value="up" / >
<input type="button" id="Down" value="down"/ >
<input type="submit" id="submit" value="submit " name="submit">
</form>
<?php
$conn = connect DB stuff here...
$temp = $_POST['temp'];
$updateTarget = "UPDATE target SET target = '";
$updateTarget = $updateTarget . $temp . "' WHERE id = 1;";
$result = $conn->query($updateTarget);
$conn->close();
?>
<script>
var min = 15,
max = 25;
$("#Up").click(function(){
if($("#temp").val() < 25 && $("#temp").val() >= 15)
$("#temp").val(Number($("#temp").val()) + 0.5);
});
$("#Down").click(function(){
if($("#temp").val() <= 25 && $("#temp").val() > 15)
$("#temp").val(Number($("#temp").val()) - 0.5);
});
</script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'form.php',
data: srt,
success: function(d) {
$("#input").html(d);
}
return false;
});
});
});
</script>
just echo this temp value
<?php
//$conn = connect DB stuff here...
$temp = $_POST['temp'];
or
print_r($_POST);
echo $temp;
die();
$updateTarget = "UPDATE target SET target = '";
$updateTarget = $updateTarget . $temp . "' WHERE id = 1;";
then check alert if alert show right data then
then use single query like this
$updateTarget = "UPDATE target SET target = '$temp' WHERE id = 1";
//i think it will help you to find issue
$result = $conn->query($updateTarget);
$conn->close();
?>
and your javascript function need to update
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'form.php',
data: srt,
success: function(d) {
alert(d);
$("#input").html(d);
}
});
return false;
});
});
</script>
if you find right data then check your db structure that is it allow float etc. i think it will work
you can also check this
How to Search value from input by mysqli in database

Submiting for using ajax and php and return response

I am using this php to submit a form and is working now i want to post to it using ajax and return what i have submitted without reloading the page but is not posting to me database and it not showing me errors.
Which other simple way can i archive this or can anyone show me where am doing it wrong
Here is the full program <?php echo $_GET['postid'];?> < this get ID of my main blog post
HTML STRUCTURE
<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"></textarea>
<?php
if(!isset($_SESSION['user_login'])) {
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"/>
</form>
Ajax
<script>
$(document).ready(function(){
$('#add-comment').submit(function(){
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'alter_reply.php',
data:'comment='+comment+'&name='+name+'&rid='+rid,
})
.done(function(data){
$('#response').html(data);
})
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>
alter_reply.php
<?php
if($_POST) {
$db_host = "localhost";
$db_user = "root";
$db_pass = "";
$db_name = "post";
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= $form['rid'];
$comment = $form['comment'];
$timedate = date("Y-m-d H:i:s");
if(isset($_SESSION['user_login'])){
$user = $_SESSION['user_login'];
}else{
$anony_user = $form['name'];
$user = $anony_user;
}
$stmt->execute();
}
catch(PDOException $e)
{
echo "Error:" . $e->getMessage();
}
$db_conn = null;
}
?>
You have not gathered the variables values. Get them and then pass to $.ajax as below :
var comment = $('#comment').val();
var name = $('#anony').val();
var rid = $('#rid').val();
Make sure you have id in your inputs.
You form should look like :
<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"></textarea>
<?php
if(!isset($_SESSION['user_login'])) {
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'];?>" id="rid" name="rid"/>
</form>
And script must be :
<script>
$(document).ready(function(){
$('#add-comment').submit(function()
{
var comment = $('#comment').val();
var name = $('#anony').val();
var rid = $('#rid').val();
$('#response').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: 'alter_reply.php',
data:'comment='+comment+'&name='+name+'&rid='+rid,
})
.done(function(data){
$('#response').html(data);
})
.fail(function() {
alert( "Posting failed." );
});
return false;
});
});
</script>

Ajax call not working after page reload.

I have my home page in php with checkboxes by the names of brand and store list.and in the end one submit button which is given below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="brand"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
function get_store_value(){
var d_value=[];
$('input[name="store"]:checked').each(function () {
d_value.push(this.value);
});
return d_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (e)
{e.preventDefault();
alert("hi");
//var os = $('#originState').val();
//var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
var store=get_store_value();
//var queryString = "os=" + os;
var data = "?ser=" + ser;
var queryString = "&ser=" + ser;
alert(ser);
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: {ser:ser,store:store},
dataType : 'html',
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
brand
<input type="checkbox" name="brand" value="Sunbaby" />Sunbaby
<br/>
<input type="checkbox" name="brand" value="Advance Baby" />Advance Baby
<br/>
store
<br/>
<input type="checkbox" name="store" value="JCPenny" />JCPenny
<br/>
<input type="checkbox" name="store" value="Supermart" />Suoermart
<br/>
<input type="checkbox" name="store" value="Target" />Target
<br/>
<button id="btnSubmit">sort</button>
<div id="results">
</div>
</body>
</html>
On click of submit,button it goes for ajax call and displays the result in results div.
<?php
include('connection.php');
$query=$_POST['ser'];
$query1=$_POST['store'];
echo $query;
echo $query1;
$query=explode(",",$query);
$query = array_filter($query);
$query1=explode(",",$query1);
$query1 = array_filter($query1);
$result=count($query);
$result1=count($query1);
//echo $result;
echo $result1;
$parts = array();
$limit = 10;
$offset = 0;
if(!empty($query))
{
foreach( $query as $queryword ){
$parts[] = '`BRAND` LIKE "%'.$queryword.'%"';
}
$brandsql='SELECT * FROM XML WHERE ('.implode ('OR',$parts).') order by price asc';
$brandsql1=mysql_query($brandsql);
$numrows = mysql_num_rows($brandsql1);
$countArray=array();
print($brandsql);
echo "<br />";
while($row = mysql_fetch_array($brandsql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
$parts1=array();
if(!empty($query1)){
foreach( $query1 as $queryword1 ){
$parts1[] = '`STORE` LIKE "%'.$queryword1.'%"';
}
$storesql='SELECT * FROM XML WHERE ('.implode ('OR',$parts1).') order by price desc';
$storesql1=mysql_query($storesql);
$numrows1 = mysql_num_rows($storesql1);
$countArray=array();
print($storesql);
while($row = mysql_fetch_array($storesql1)) {
// Append to the array
$countArray[] = $row;
//echo $row['PID']."<BR />";
}
}
?>
<?php
foreach($countArray as $array)
{
?>
<div>
hi</div>
<?php $i++; } ?>
But iF I refresh my page or press F5 from keyboard,after getting content in results div,it goes back to previous content i.e.first page with checkboxes and submit button.
Please tell me where m doing wrong in the code or what do i need to include so that after ajax call if i refresh the page,content should remain same,should not go to previous content...
Use setTimeout() to run a refresh on the page after X seconds inside the AJAX callback, after you display content.
You could use the _SESSION variable in your PHP script to store what checkboxes were selected most recently, and display results on your results div, appropriately.
Although, if a user clicks refresh he might want to reset the choices he made anyway. You could give him a warning that his changes will be lost if he refreshes.
window.onbeforeunload = function() {
return confirm("You have made changes to this form. Do you want to continue without saving these changes?");
}

Categories

Resources