I'm still in a learning shift when it comes to Ajax. I made a script that sends data to a database and it works. The data inserts. Now my question is how can I display the data on the page?
display.php
<div class='displayMessage' style='height: 540px; padding:5%; overflow-x:hidden;'>
<?php
$chatmsgQ="SELECT * FROM ve_chat c
WHERE c.isActive='1' AND c.fromUserId='$loginid_session'
OR c.toUserId='$loginid_session'";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){?>
<?php if($chatmsg['fromUserId']==$loginid_session):?>
<!-- user one -->
<p class='bubble pull-left'><?=$chatmsg['message'];?></p>
<?php elseif($chatmsg['fromUserId']!=$loginid_session):?>
<!-- user two-->
<p class='bubbleother pull-right'><?=$chatmsg['message'];?></p>
<?php endif;?>
<?php } ;?>
</div>
<!-- write message-->
<form id="chatForm" method='post' action='chat.php'>
<textarea id='chatMessage' name='chatMessage' placeholder="Type your message here... " value=''></textarea>
<button id='buttons' type="submit" name='sendChat' class="btn btn-default">Send</button>
<input type='hidden' id='fromUserId' name='fromUserId' value='<?=$loginid_session;?>'>
<input type='hidden' id='toUserId' name='toUserId' value='<?=$touserid;?>'>
</form>
js script
<script>
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: false,
success: function(result){
//what do I put here exactly?
}
});
return false;
});
});
</script>
chat.php
//get variables
$chatMessage= $_POST['chatMessage'];
$fromUserId= $_POST['fromUserId'];
$toUserId= $_POST['toUserId'];
$chatStatus='1';
//insert in ve_articles_comments
$startChatQ = $db->prepare("INSERT INTO ve_chat (fromUserId,toUserId,message,isActive) VALUES (?,?,?,?)");
$startChatQ ->bind_param("iisi",$fromUserId,$toUserId,$chatMessage,$chatStatus);
$startChatQ ->execute() or die(mysqli_error($db));
if($startChatQ ){
// echo "Data Submitted succesfully";
$_SESSION['success']='<h4 style="text-align: center;" class="alert alert-success alert-dismissable" >×Your chat request was sent with success.</h4>';
header('Location: ' . $_SERVER['HTTP_REFERER']);
exit;
}
$startChatQ ->close();
$db->close();
Alright so this works for me:
display.php
<div class='displayMessage' style='height: 540px; padding:5%; overflow-x:hidden;'>
<?php
$chatmsgQ="SELECT * FROM ve_chat c
WHERE c.isActive='1' AND c.fromUserId='$loginid_session'
OR c.toUserId='$loginid_session'";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){?>
<?php if($chatmsg['fromUserId']==$loginid_session):?>
<!-- user one -->
<p class='bubble pull-left'><?=$chatmsg['message'];?></p>
<?php elseif($chatmsg['fromUserId']!=$loginid_session):?>
<!-- user two-->
<p class='bubbleother pull-right'><?=$chatmsg['message'];?></p>
<?php endif;?>
<?php } ;?>
</div>
<!-- write message-->
<form id="chatForm" method='post' action='chat.php'>
<textarea id='chatMessage' name='chatMessage' placeholder="Type your message here... " value=''></textarea>
<button id='buttons' type="submit" name='sendChat' class="btn btn-default">Send</button>
<input type='hidden' id='fromUserId' name='fromUserId' value='<?=$loginid_session;?>'>
<input type='hidden' id='toUserId' name='toUserId' value='<?=$touserid;?>'>
</form>
jQuery
$(document).ready(function(){
$("#buttons").click(function(){
var fromuserid = $("#fromUserId").val();
var touserid = $("#toUserId").val();
var chatMessage = $("#chatMessage").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'fromUserId='+ fromuserid + '&toUserId='+ touserid + '&chatMessage='+ chatMessage;
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
cache: false,
success: function(response){
$("#displayMessage").html(response);
}
});
return false;
});
});
chat.php
//get variables
$chatMessage= $_POST['chatMessage'];
$fromUserId= $_POST['fromUserId'];
$toUserId= $_POST['toUserId'];
$chatStatus='1';
$loginid_session=$_POST['fromUserId'];
//insert in ve_articles_comments
$startChatQ = $db->prepare("INSERT INTO ve_chat (fromUserId,toUserId,message,isActive) VALUES (?,?,?,?)");
$startChatQ ->bind_param("iisi",$fromUserId,$toUserId,$chatMessage,$chatStatus);
$startChatQ ->execute() or die(mysqli_error($db));
if($startChatQ ){
// echo "Data Submitted succesfully";
$chatmsgQ="SELECT * FROM ve_chat c WHERE c.isActive='1' AND (c.fromUserId='$loginid_session' OR c.toUserId='$loginid_session')";
$chatmsgresult= mysqli_query($db,$chatmsgQ);
while($chatmsg= mysqli_fetch_array($chatmsgresult)){
if($chatmsg['fromUserId']==$loginid_session){
echo " <p class='bubble pull-left'>" .$chatmsg['message'] . "</p> ";
}
elseif($chatmsg['fromUserId']!=$loginid_session){
echo " <p class='bubbleother pull-right'>" . $chatmsg['message'] . "</p> ";
} }
}
$startChatQ ->close();
$db->close();
Related
I have an problem, I have multiple button generate with while, with different names (button[$nostation]).
Now, I want to update MySQL database (table: smt, column: no) with the same id ($nostation).
How I can generate AJAX function for that?
This is my code:
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
echo "
<div class='col-xs-2-2'>
<form action='coba.php' method='post'>
<button name='button[$nostation]' value='2' style='background-color:#02780d; width:140px; height:75px; margin : 2px; border-radius:10%;'>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
";}?>
And this is my code for update database with PHP:
<?php
include 'connect.php';
$array=$_POST['button'];
foreach ($array as $nostation => $value) {
$updch=mysqli_query($connect,"UPDATE smt SET status='$value' WHERE no='$nostation'");
}?>
How I can update with AJAX without refreshing the page?
View Part :-
<?php
$query1 = mysqli_query($connect,"SELECT * FROM smt WHERE no <= 15");
while ( $data=mysqli_fetch_array($query1)){
$nostation = $data['no'];
$namastation = $data['name'];
?>
<div class='col-xs-2-2'>
<form method='post'>
<input type="hidden" value="<?php echo $nostation;?>" id="name_<?=$nostation;?>" name="name">
<button type="submit" id="button_<?=$nostation;?>" data-id="<?=$nostation;?>">SAVE</button>
<center>
<b style='font-size:15px; color: #fff; font-family:Calibri;'>$namastation</b>
</center>
</button>
</form>
</div>
<?php } ?>
jQuery / AJAX Part:-
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){ //when DOM is Ready.
$("[id^=button_]").click(function () { //when Button is Clicked.
var id = $(this).data('id'); // Get the ID of the button that was clicked on.
var name = $("#name_"+id).val(); // value from `input` which is connected the clicked button.
// console.log(id+"---"+name);
$.ajax({ // AJAX request
url: 'update.php', // send request to server.
method: 'POST', // method is POST.
data: { //data which is sent to server.
id: id,name: name
},
success: function (data) { //success function called.
alert(data); // alert success data.
}
});
});
});
</script>
update.php:-
And in the php-side We catch it by:-
echo $id = $_POST['id'];
echo $name = $_POST['name'];
//use update query.
Note:- For more info regarding click()
https://api.jquery.com/click
So I've got this form for adding comments under a post. The methods utilized here are MYSQL(holds the submitted form data in a database) PHP(communicating with the database) and JavaScript, more specifically AJAX (for hooking up the submit button and handling events).
Typing in your comment into the form and pressing submit is supposed to print the comment onto the screen.
When I click submit, it doesn't print anything. Then, when I type another comment and click submit once more, it prints the contents of that comment. Other times, it successfully prints the contents of the comment instead of failing to submit.
I checked it out in inspect element and in the console log, whenever it misses, it still sends some blank <p> tags through with the class of the comment that should be submitted.
The PHP page for the comment form:
<head>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="Forums.css">
</head>
<body>
<?php
$result = mysqli_query($link, $displayPost); ?>
<?php $row = mysqli_fetch_assoc($result);?>
<p> <?php echo $row["title"];?> </p>
<br>
<p> <?php echo $row["body"];?> </p>
<form action="<?php echo $url ?>" method="post" id="form-group">
<div class="forum col-md-12">
<textarea type="text" style="overflow: auto; resize: none;" name="body" class="txtBody"></textarea>
<input type="submit" name="submit" class="btnCreate" style="margin-bottom: 4px;">
</div>
</form>
</body>
<script>
function refreshData() {
$.ajax({
type:'GET',
url: 'getcomments.php?id=<?php echo $id ?>',
dataType: 'html',
success: function(result){
console.log(result);
$('#comments').html(result);
}
});
}
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData
});
refreshData();
event.preventDefault();
});
});
</script>
<div id="comments"></div>
The PHP page for getting previously submitted comments and printing them on the screen
<?php
$link = mysqli_connect("localhost", "root", "WassPord64", "forum");
$id = $_GET["id"];
$displayPost = "SELECT * FROM comments WHERE post_id='$id'";
$link->query($displayPost);
$result = mysqli_query($link, $displayPost);
if (mysqli_num_rows($result) > 0) :
// output data of each row
while($row = mysqli_fetch_assoc($result)) :
$row = mysqli_fetch_assoc($result);?>
<p class="postBody"><?php echo $row['body'];?></p>
<?php endwhile; ?>
<?php endif; ?>
You are calling refreshData() when the Ajax is not done. You can make a callback function by using $.ajax.success
Try this:
$(document).ready(function () {
refreshData();
$("#form-group").submit(function (event) {
var $form = $(this);
console.log($form.attr('action'));
var serializedData = $form.serialize();
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: serializedData,
success: function(){
refreshData();
}
});
event.preventDefault();
});
});
I'm a newbie in the world of php and I was trying to learn it with a simple page.
I've created an html form and I want to send data using ajax but it still
POST http://localhost/Home.php 500 (Internal Server Error)
In particular I want to create a button for every table in a database which I'm using for testing, when I push a button it will show all lines from the database (I've not implemented it yet, I'm only trying to understend how php and ajax communicate)
This is my form (Home.php)
<?php
session_start();
if(!isset($_SESSION['login'])) {
header("Location: Login.php");
unset($_REQUEST);
}
else echo "<span class=\"welcome\"><strong>Benvenuto</strong> <em>" . $_SESSION['username'] . "</em></span>";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src='jquery-1.11.3.js'></script>
<script src='Script.js'></script>
</head>
<body>
<div id="functions">
<button id="createTable">CREATE</button>
<button id="displayTable">DISPLAY</button>
</div>
<div id="createForm">
<form id="queryForm" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input class ="text" name="query" type="text" size="50">
<input type="submit" class="submit" name="createQuery">
</form>
</div>
<div id="displayForm">
<form method="post" id="selectForm">
<?php
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Tables = $Database->countTable();
foreach($Tables as $column) {
echo "<input type=\"radio\" class=\"submit\" id=\"selectQuery\" name=\"selectQuery\" value=\"". $column . "\"> " . $column;
}
?>
<input type="submit" class="submit" name="createSelect">
</div>
<div style="position:absolute; bottom:10px; left:50%; font-size: 15pt"></span><em>...</em> Logout</div>
</body>
</html>
<?php
if(isset($_POST['createQuery'])) {
include ("Database.php");
$Database = new Database( "localhost", "root", "1234");
$Database->connectToServer();
$Database->connectToDatabase("test");
$Database->createTable($_POST["query"]);
header("Location:Home.php");
}
?>
And this is my ajax file
$(document).ready(
function() {
$("#createTable").click(goCreate);
$("#displayTable").click(goDisplay);
$('#selectForm').submit(goSelect);
$("#createForm").hide();
$("#displayForm").hide();
}
);
function goCreate(data) {
$("#createForm").show();
$("#functions").hide();
}
function goDisplay(data) {
$("#displayForm").show();
$("#functions").hide();
}
function goSelect() {
var selectedTable = $("#selectQuery:checked").val();
console.log($("#selectQuery:checked").val());
$.ajax({
url: "Prova.php",
type: "POST",
dataType: "html",
data: {
'select': 'display',
'table': selectedTable
},
success: function(msg) {
console.log(msg);
},
error: function(xhr, desc, err) {
console.log("error");
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
return false;
};
And this is Prova.php where I managed ajax call
<?php
include 'ChromePhp.php';
ChromePhp::log("corretto");
echo "ok belo";
?>
So i am haveing this page where it is displaying articles andunderneet each article it will have a textarea asking allowing the user to insert a comment.I did the AJAX and it works fine.Some of the validation works fine aswell(Meaning that if the textarea is left empty it will not submit the comment and display an error).The way i am doing this validation is with the ID.So i have multi forms with the same ID.For the commets to be submited it works fine but the validtion doesnt work when i go on a second form for exmaple it only works for the first form
AJAX code
$(document).ready(function(){
$(document).on('click','.submitComment',function(e) {
e.preventDefault();
//send ajax request
var form = $(this).closest('form');
var comment = $('#comment');
if (comment.val().length > 1)
{
$.ajax({
url: 'ajax_comment.php',
type: 'POST',
cache: false,
dataType: 'json',
data: $(form).serialize(), //form serialize data
beforeSend: function(){
//Changeing submit button value text and disableing it
$(this).val('Submiting ....').attr('disabled', 'disabled');
},
success: function(data)
{
var item = $(data.html).hide().fadeIn(800);
$('.comment-block_' + data.id).append(item);
// reset form and button
$(form).trigger('reset');
$(this).val('Submit').removeAttr('disabled');
},
error: function(e)
{
alert(e);
}
});
}
else
{
alert("Hello");
}
});
});
index.php
<?php
require_once("menu.php");
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="comments.js" type="text/javascript" ></script>
<?php
$connection = connectToMySQL();
$selectPostQuery = "SELECT * FROM (SELECT * FROM `tblposts` ORDER BY id DESC LIMIT 3) t ORDER BY id DESC";
$result = mysqli_query($connection,$selectPostQuery)
or die("Error in the query: ". mysqli_error($connection));
while ($row = mysqli_fetch_assoc($result))
{
$postid = $row['ID'];
?>
<div class="wrapper">
<div class="titlecontainer">
<h1><?php echo $row['Title']?></h1>
</div>
<div class="textcontainer">
<?php echo $row['Content']?>
</div>
<?php
if (!empty($row['ImagePath'])) #This will check if there is an path in the textfield
{
?>
<div class="imagecontainer">
<img src="images/<?php echo "$row[ImagePath]"; ?>" alt="Article Image">
</div>
<?php
}
?>
<div class="timestampcontainer">
<b>Date posted :</b><?php echo $row['TimeStamp']?>
<b>Author :</b> Admin
</div>
<?php
#Selecting comments corresponding to the post
$selectCommentQuery = "SELECT * FROM `tblcomments` LEFT JOIN `tblusers` ON tblcomments.userID = tblusers.ID WHERE tblcomments.PostID ='$postid'";
$commentResult = mysqli_query($connection,$selectCommentQuery)
or die ("Error in the query: ". mysqli_error($connection));
#renderinf the comments
echo '<div class="comment-block_' . $postid .'">';
while ($commentRow = mysqli_fetch_assoc($commentResult))
{
?>
<div class="commentcontainer">
<div class="commentusername"><h1>Username :<?php echo $commentRow['Username']?></h1></div>
<div class="commentcontent"><?php echo $commentRow['Content']?></div>
<div class="commenttimestamp"><?php echo $commentRow['Timestamp']?></div>
</div>
<?php
}
?>
</div>
<?php
if (!empty($_SESSION['userID']) )
{
?>
<form method="POST" class="post-frm" action="index.php" >
<label>New Comment</label>
<textarea id="comment" name="comment" class="comment"></textarea>
<input type="hidden" name="postid" value="<?php echo $postid ?>">
<input type="submit" name ="submit" class="submitComment"/>
</form>
<?php
}
echo "</div>";
echo "<br /> <br /><br />";
}
require_once("footer.php") ?>
Again the problem being is the first form works fine but the second one and onwaord dont work properly
try this:
var comment = $('.comment',form);
instead of
var comment = $('#comment');
That way you're targeting the textarea belonging to the form you're validating
ps.
remove the id's from the elements or make them unique with php, all element id's should be unique
As shown from the diagram, I have two tables in my mysql and I would like the system to add and retrieve comment without refreshing the page.
I have three php pages involved in this function and they are 'DB.php', 'comment.php' and 'action.php'
The codes are as shown:
DB.php
<?php
$conn = mysql_connect('localhost','Practical4','1234') or die (mysql_error);
$db=mysql_select_db('Practical4', $conn) or die (mysql_error);
?>
comment.php
<----------------ajax script-------------------->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<-----retrieve hotel id from hotel table-------->
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<---------------post form------------------->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string(trim($_POST['content']));
$name=mysql_real_escape_string(trim($_POST['name']));
mysql_query("insert into comment(content,name) values ('$content','$name')");
$fetch= mysql_query("SELECT content FROM comment order by commentID desc where name = '$name'");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['content']; ?> </div>
when I run this, the page display nothing when I insert the comment, can anyone help me to solve this? Thanks a lot!!
Some changes have been made as follows:
comment.php
<!-- ajax script -->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = 'content='+ textcontent + '&name='+name;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<!-- retrieve hotel id from hotel table -->
<?php
include('DB.php');
$id=$_GET['id'];
$query = mysql_query("select * from hotel where name='$id'");
while($rows=mysql_fetch_array($query)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<!-- post form -->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
mysql_query("insert into comment (content,name) values ('$content','$name')");
echo '<div class="showbox">'.$content.'</div>';
}
?>
Reasons why your code failed:
name not added in dataString causing name not sent in post
some mysql errors