I am creating a forum in which the posted user has option to delete his own posts. So, I am using ajax to send get request to delete a particular post and I am echoing null in place of the deleted post. The problem here is the post is getting deleted but the page is reloading after deletion which shouldn't happen as I am using ajax request. Can anyone help?
PHP CODE TO DISPLAY THE POSTS(ONLY A PART)
$sql = "SELECT * FROM classposts where branch='$branch' and joindate='$year' and class='$class' order by".$orderby." desc";
$result = $connection->query($sql);
if(isset($_SESSION['username'])){
$username=$_SESSION['username'];
}
while($row = $result->fetch_assoc()) {
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "-----------------------------------</br>";
echo "-----------------------------------</br>";
echo "Posted By: ".$row['user']."    ";
if($username==$row['user']){
echo "<a href='classwall.php' onclick='deletepost(".$row['id'].")' >DELETE POST</a>   ";
}
Ignore if any parenthesis are not matching as this is only a part of the code.
javascript function which is called after delete link is clicked
function deletepost(postid){
var r=confirm("Are you sure you want to delete the post?");
if(r==true){
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("postspan"+postid).innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","deletepost.php?pid="+postid,true);
xmlhttp.send();
}else{}
}
deletepost.php page
$pid=$_GET['pid'];
$query="delete from dubiousposts where id='$pid'";
$sql=mysqli_query($connection,$query);
$query="delete from genuineposts where id='$pid'";
$sql=mysqli_query($connection,$query);
$query="delete from posts where id='$pid'";
$sql=mysqli_query($connection,$query);
if($result=mysqli_fetch_array($sql)){
echo "";
}
You have given the ahref link to calsswall.php page that's why you goes to other page.
change
echo "<a href='classwall.php' onclick='deletepost(".$row['id'].")' >DELETE POST</a>   ";
to
echo "<a href='javascript:void(0);' onclick='deletepost(".$row['id'].")' >DELETE POST</a>   ";
Related
I am building a site in which users have the ability to write post's and other users could comment on these posts.
By now I managed to create a div that contain the comment's that are posted, I have a "Like" button(not functional at this moment) and I have a "Comment" button that I want to trigger a small window that will open to recieve text from the user(the comment) and add it to my comment table(tblcomments).
The comment button has the same ID of the post it refers to(I built it that way when I echo'ed the page from php and everything sits in the same div). but I can't seem to find a way to pop-up that comment window to recieve the comment from the user and update my table with a comment for this specific post.
The section of the page that contains the comments is being refreshed every 5 seconds so adding a simple text field to the div is imposible cause it will get reset every 5 seconds.
that is how it looks on the page right now:
And that's the code that generate each and every post like this one on my main page while querying my DB:
<?php
include 'connectDB.php';
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
$hash = mysqli_escape_string($conn, $_SESSION['login_user']);
$resultfr = mysqli_query($conn, "SELECT distinct U.userName,concat(U.firstName,' ',U.lastname) as fullName FROM tblUser U inner join tblfriendswith FW on FW.userName1=U.userName or FW.userName2=U.userName where U.userName!='$hash'");
$uName="";
if($resultfr!= FALSE){
while($row2 = mysqli_fetch_array($resultfr)){
$uName= $uName.$row2['userName']." ";
}
}
$result = mysqli_query($conn, "SELECT U.userName,concat(U.firstName,' ',U.lastname) as fullName,MONTHNAME(P.postDate) as dateM, DAY(P.postDate) as dateD, YEAR(P.postDate) as dateY, P.postID, P.content FROM tblUser U inner join tblPost P on P.userName=U.userName where U.userName in ('$uName','$hash') order by P.postDate desc");
if($result!= FALSE){
echo "<div class='forPosts'>";
while($row = mysqli_fetch_array($result)){
$fullName = $row['fullName'];
$day=$row['dateD'];
$month=$row['dateM'];
$year=$row['dateY'];
$content = $row['content'];
$postID=$row['postID'];
echo "<div class=\"divStyle2\"><span class=\"myText2\">Posted by " .$fullName." - ".$day." ".$month." ".$year."</span><br><div class=\"divStyle\">".$content."</div>";
echo "<br><button class=\"myButton\"> <span class=\"glyphicon glyphicon-heart pull-left\"></span> Like</button>   <button class=\"myButton\"><span class=\"glyphicon glyphicon-comment pull-left\"></span>  Comment</button>   <button class=\"myButton\" name=\"clickB\" id=\"".$postID."\"><span class=\"glyphicon glyphicon-triangle-bottom pull-left\"></span>  Show/hide comments</button></div>";
//echo "<p class=\"alignW\"><input class=\" col-sm-5\" type=\"text\" name=\"comment\" id=\"".$postID."\" placeholder=\"Write a comment\"></div>";
$result2 = mysqli_query($conn, "SELECT C.postID, C.commentID, C.userName, C.content,concat(U.firstName,' ',U.lastname) as fullN,MONTHNAME(C.commentDate) as dateM, DAY(C.commentDate) as dateD, YEAR(C.commentDate) as dateY FROM tblUser U inner join tblComment c on U.userName=C.userName where C.postID=$postID order by C.commentDate desc");
if($result2!= FALSE){
echo"<div class='forComments'>";
while($row2 = mysqli_fetch_array($result2)){
$fullN = $row2['fullN'];
$day2=$row2['dateD'];
$month2=$row['dateM'];
$year2=$row2['dateY'];
$content2 = $row2['content'];
echo "<div class=\"divStyle2\" id=\"".$postID."\"><span class=\"glyphicon glyphicon-comment\" ></span><span class=\"myText3\"> " .$fullN. " : ".$content2."</span></div>";
}
}echo"</div>";
}
echo "</div>";
}
echo" <script>
$(document).ready(function(){";
echo" $(\"button[name=clickB]\").click(function() {
link = $(this).attr('id');
$('div[id=\"'+link+'\"]').toggle();
$(\"span\", this).toggleClass(\"glyphicon glyphicon-triangle-bottom glyphicon glyphicon-triangle-top\");
});";
echo"}); </script>";
?>
I use mysqli and xampp.
I would be grateful if someone could help me to achieve my task.
Thank you!
Tom
I want the output of "cor_resp_template" where is nome and select that values for in next page do some operations like(sum, multiplication,...). I try the first time use JavaScript, but i don´t know if the code is correct. I try to analysis step by step and seems ok for that operation.
In next picture like you see the empty values. Don´t show the table with the values for after submit that values for next page.
The output of database of the table template where is all the values:
That is the output of that page:
http://localhost/dissertacao/conceptualization13.php?menuId=1
After we have the code where we use the JavaScript for get the values in next page where is the PHP query.
<script>
function showUser(str) {
if (str == "") {
document.getElementById("$option").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("$option").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","template1.php?option="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<?php
echo "<select name='template' class='form-control' onchange='showUser(this.value)'>";
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
echo "<center>";
// Get the county names from database - no duplicates
$query = "SELECT DISTINCT nome FROM template";
{
// execute the query, $result will hold all of the Counties in an array
$resultado = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($resultado))
$option .="<option>" . $row['nome'] . "</option>";
echo $option;
}
echo "</select>";
echo "<br>";
?>
<input type="submit" value="Submit">
</form>
<br>
<div id="valores"><b>Os valores para este template são:</b></div>
template1.php
The following code is the PHP QUERY where is called for give the output of the table with the values where is nome in the SQL table.
<?php
$option = (isset($_POST['nome']) ? $_POST['nome'] : '');
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("teste") or die(mysql_error()); // selecciona a database do server escolhido
$query="SELECT * FROM template WHERE 'nome' = '".$option."'";
$resultado = mysql_query($query) or die(mysql_error());
echo "<table>
<tr>
<th>Valores</th>
</tr>";
while($row = mysql_fetch_array($resultado)) {
var_dump ($resultado);
echo "<tr>";
echo "<td>" . $row['corp_resp_template'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>**
I just started to use AJAX, so I apologize if the question is very basic.
I use a simple AJAX script to update a session variable depending on which button you click, but I cant get it to update the heading with the new value when clicking the button. At the moment I got a button to reload the page, but I want to remove that and make the header update on each buttonclick.
index.php
<?php session_start(); ?>
<html>
<head>
<script type='text/javascript'>
function setSession( value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "setSession.php?variable=rider&value=" + value, true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
echo "<h1>You selected: " . $_SESSION['rider'] . "</h1>";
echo "<button type='button' onclick='javascript:setSession(this.value)' value='Kristoff'>Kristoff</button> ";
echo "<button type='button' onclick='javascript:setSession(this.value)' value='Edvald Boasson Hagen'>Edvald Boasson Hagen</button> ";
echo "<input type='submit' value='Re-Load Page'>";
?>
</body>
</html>
setSession.php
<?php
session_start();
if(isset($_REQUEST['variable']) && isset($_REQUEST['value']))
{
$variable = $_REQUEST['variable'];
$value = $_REQUEST['value'];
$_SESSION[$variable] = $value;
}
?>
#Chris and #tej explains the procedure.This is how you do it.
setSession.php
<?php
session_start();
if(isset($_REQUEST['variable']) && isset($_REQUEST['value'])){
$variable = $_REQUEST['variable'];
$value = $_REQUEST['value'];
$_SESSION[$variable] = $value;
echo $_SESSION[$variable];
}
?>
index.php
echo "<h1 id='selection'>You selected: " . $_SESSION['rider'] . "</h1>";
function setSession( value) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "setSession.php?variable=rider&value=" + value, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("selection").innerHTML = "You selected ".xmlhttp.responseText;
}
}
xmlhttp.send();
}
At the moment index.php is only loaded once. Therefore $_SESSION['rider'] has been output once and only once so it won't change. You need to use javascript to read the response from the xhr you're doing (and at the same time output $_SESSION['rider'] in the setSession.php file.
I'm not sure of what your application is trying to do but this can be achieved without any php at all.
After triggering ajax call you have to modify the h1 already displayed.
Add a class to h1 and use jQuery or JavaScript to modify the value once ajax is complete.
if(xhr.status===200){
$('.header').text(//rider text);
}
This will set the value after ajax and if user refreshes page it will automatically load from session.
But as other answer suggests this can easily be attained without php itself but I will leave application technology decision to you.
Last night I had issue with registration where php was saving null data to my database when ajax was used but with a help of stack overflow the issue was resolved. I was sending data in url and rather than using $_GET i used $_POST, problem solved so this morning I thought lets do the same with login page but this time when I add ajax to it the login button it does nothing, it just clicks and does nothing
what I was trying to do was when user login with correct info it goes to home page index.php but when the user try to log in with wrong info then it echo invalid. so I was trying to echo it in index.php rather than taking user to new page.
the following is the code i was working on.this one is saved as index.php where user puts there details.
<?php
if (!isset($_SESSION['uid'])) {
echo "<form action='login_parse.php' method='post' style='display: inline-block'>
Username: <input type='text' name='username' id='username' />
Password: <input type='password' name='password' id='password' />
<input type = 'button' value='login' id='submit' onclick='hello2()'/>";
echo "</form>";
echo "<form action='signup.php' method='post' style='display: inline-block'>";
echo " ";
echo "<input type='submit' name='submit' value='Signup'>";
echo "</form>";
echo "<div id='ack1'></div>";
} else {
echo "<form style='display: inline-block'>";
echo "<p>You are logged in as ".$_SESSION['username']."";
echo "</form>";
echo "<form action='logout_parse.php' method='post' style='display: inline-block'>";
echo " ";
echo "<input type='submit' value='logout'>";
echo "</form>";
}
?>
this one is saved as ajax.js
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
var HTTP = loadXMLDoc();
function hello2(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "login_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack1").innerHTML=HTTP.responseText;
}
}
HTTP.open("POST", url ,true);
HTTP.send();
}
and at last this one is saved as login_parse.php
<?php
session_start();
include_once("connect.php");
if (isset($_POST['username'])) {
$username = mysql_real_escape_string( $_GET["username"]);
$password = mysql_real_escape_string( md5 ($_GET["password"]));
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) == 1) {
$row = mysql_fetch_assoc($res);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: index.php");
exit();
} else{
echo "INVALID login information.";
exit();
}
}
?>
am I doing something wrong, do I have to use ajax just to echo invalid in index.php
Here are the fixes for the ajax code not displaying the invalid login message.
First i removed the function call for the hello2 function and placed in a javascript event at within a script tag at the bottom of the page. This made it easier for me to conduct tests. You will have to add the id submit-button to your button html.
The previous echo in your index php file will look like this now.
echo "<form action='login_parse.php' method='post' style='display: inline-block'>
Username: <input type='text' name='username' id='username' />
Password: <input type='password' name='password' id='password' />
<input id='submit-button' type = 'button' value='login' id='submit' />";
Here is the javascript that will before the closing body tag of your index.php file:
<script src="ajax.js"></script>
<script>
//return XMLHTTP request and store it
var HTTP = loadXMLDoc();
//on click event for #submit-button
var submitEvent = document.getElementById("submit-button").onclick = function(){
hello2(HTTP);
};
</script>
This is were I found the main problem. I made the variable xmlhttp have global scope by placing it at the top your ajax.js code.
I found this problem initially by changed the following line of code:
document.getElementById("ack1").innerHTML= HTTP.responseText;
to:
document.getElementById("ack1").innerHTML= "it worked";
By doing this I discovered that your function call at this point was working but your HTTP.onreadystatechange=function(){} was unable to access the responseText.
Here is the new ajax.js file code below:
//moved variable outside of functions to give it the global scope
var xmlhttp;
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function hello2(HTTP){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "login_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState===4 && HTTP.status === 200){
document.getElementById("ack1").innerHTML= HTTP.responseText;
}
};//<--was missing a semicolon ;
HTTP.open("POST", url ,true);
HTTP.send();
}
Fix for PHP code so that you don't have to refresh index.php to show the You are "logged in as ..." message.
Place this php code before any other php code in you index.php file so that you can access your session variables.
//start the session so that you can echo session variables on this page
session_start();
Here I go again. I am trying to change content of a division with data retrieved from my database. This has to be done without reloading the page, therefore I am using xmlhttp and javascript. The website is running on CodeIgniter. Below is the code with a short summary of it. I have been following this tutorial, but for some reason, when I click the button, nothing is happening.
View *xampInstallFolder/htdocs/application/obs/views/test_v.php*
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$( "#next_btn" ).click(function() {
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("listA").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnext5.php?q="true);
xmlhttp.send();
})
</script>
</head>
<body>
<div id="listA">
</div>
<div id="next_btn">
</div>
</body>
</html>
Right now I trigger the function when my button gets clicked. The function is in the head of the view,. I am not sure where should the file with the query (getnext5.php) be stored. Right now it is inside the views folder. The link to the file is this xmlhttp.open("GET","getnext5.php?q="true); should I somehow change this?
Functions xampInstallFolder/htdocs/application/obs/views/getnext5.php
<?php
$con = mysqli_connect('localhost','root','root','obs2');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"obs2");
$sql="SELECT * FROM user WHERE id > 5";
$result = mysqli_query($con,$sql);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<a style="display:block" href="base_url('core/detail/'.$row[id])">";
echo "<div id="suggested" onmouseover="" style="cursor: pointer;">";
echo "<div id="info">";
echo "<div id="info_center">";
echo "<p>" . $row['name'] . "</p>";
echo "</div>";
echo "</div>";
echo "<div class="mosaic-block fade">";
echo "<a href="base_url('core/detail/'.$row[id])" class="mosaic-overlay">";
echo '<div class="details">';
echo "<p>" . $row['summary'] . "</p>";
echo "</div>";
echo "</a>";
echo "<div class="mosaic-backdrop"><img src="www.puu.sh/5DSWj.jpg">";
echo "</div>";
echo "</div>";
echo "<div id="info">";
echo "<div id="info_center">";
echo "<p>" . "Rating: 7.7" . "</p>";
echo "</div>";
echo "</div>";
echo "</div>";
echo "</a>";
}
echo "</table>";
?>
In this file I establish the connection to my DB, run the query, store the rows in an array called $pages and then style the results using a while loop. The style is echoed, because it is then returned by the xmlhttp request and displayed in the listA division, replacing the original content. I am not sure if the echoes are written right or not.
I am open to any suggestions. Have been trying to resolve this the whole day without any success.
Thank you all for reading and most importantly for your replies.
You're not concatenating the get parameter properly.
xmlhttp.open("GET","getnext5.php?q="true);
q="true <-- true is a boolean!
Try opening like this:
xmlhttp.open("GET","getnext5.php?q=true");
If you do want to concatenate proper, do "q="+variable
You can use jquery ajax api, and then on success function you can replace div content with values retrieved from db.