I want to build a website that can make people post things and comments on it
now I have some problems
I hope that I could submit the comment without refreshing the page (I found a way to solve this problem but the input won't be cleared)
I already search a lot of information about preventing refresh page on submit but there is no one works for me
and I hope that someone can help me with another problem
I want to make the website show the comment immediately after posting it (without refreshing the page)
directly edit my code and paste on here will be appreciated
below is my index.php
<?php
session_start();
require_once 'db.php';
require_once 'new_tdb.php';
//$datas = get_publish_article();
if(isset($_COOKIE["mcsh"])){
}else{
header("Location: ../mcsh/login/index.php");
exit();
}
?>
<html>
<head>
<title>
website
</title>
<link rel="shortcut icon" href="icon.png" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
<?php include 'menu.css' ?>
</style>
</head>
<body>
<?php include 'menu.php' ?>
<center>
<font class="corn-blue">
</font>
</center>
<p> </p>
<?php
$bij = "SELECT * FROM `post` WHERE `comment` != 1 order by id DESC";
$result = mysqli_query($conn, $bij);
$rows = mysqli_num_rows($result);
while($row = mysqli_fetch_array($result)){
$post_id = $row['id'];
$ins = $row['ins'];
$s_uid = $row['s_uid'];
$p_id = $row['id'];
//$selc = "SELECT * FROM `post` WHERE `post_id` = $p_id";
?>
<center>
<table>
<tr>
<th>
Poster: <?php echo $s_uid;?>
</th>
</tr>
<tr>
<td>
<?php echo $ins;?>
</td>
</tr>
<tr>
<td>
<details>
<summary>Comment</summary>
<form id="worker" action="comment.php" method="post" target="the_iframe">
<input type="hidden" name="post_id" value="<?php echo $p_id; ?>">
<p><input type="text" name="comment" placeholder="Comment......"> <input type="submit" hidefocus="true" name="submit"></p>
</form>
<iframe id="is_iframe" name="the_iframe" style="display: none;"></iframe>
<?php
$sel = "SELECT * FROM `post` WHERE `post_id` = $post_id order by id DESC";
$result2 = mysqli_query($conn, $sel);
$rows2 = mysqli_num_rows($result2);
while($row2 = mysqli_fetch_array($result2)){
$ins2 = $row2['ins'];
$poster2 = $row2['s_uid'];
?>
<p><?php echo $poster2 . ': ' . $ins2; ?></p>
<?php } ?>
</details>
</td>
</tr>
</table>
</center>
<h1>
-
</h1>
<?php
}
?>
<?php if (empty($row['file'])){
}else{
echo('<img src="image/'); echo $row['file']; echo('"width="100%" height="auto">');
}
?>
</body>
</html>
As #Barmar said you want to use AJAX for Asynchronous actions in your website. Submit event must refresh the page to resend the new form data.
PHP is synchrony, what means if you want to do something with synchronous codes you will need to refresh the whole page.
Lear Further : Javascript documentation of Ajax by mozila here
Related
hello i have a problem everytime i submitted a form . This is script i made
<?php include 'rumahtable.php';
include 'connect.php';
$result = $conn -> query("select kodhomestay from rumah");
?><br><br>
<form action="" method="POST">
<label>Memadam data rumah : </label>
<select name="rumah">
<option>--Pilih Kod Rumah--</option>
<?php while ($rows = $result->fetch_assoc()){
$jrumah = $rows['kodhomestay'];
echo "<option value='$jrumah'>$jrumah</option>";
} ?>
</select><br><br>
<button type="submit" name="submit" >Delete</button>
<button type="submit" name="update">Update</button>
</form>
<?php if(isset($_POST["submit"])){
include 'deletedata.php';
}
if(isset($_POST["update"])){
ob_clean();
$rumah = $_POST["rumah"];
include 'updatedata.php';
}?>
and this is the deletedata.php:
<?php include 'connect.php';
$rumah=$_POST["rumah"];
$query = "delete from rumah where kodhomestay = '$rumah'";
$delete= mysqli_query($conn,$query);
if($delete){ ?>
<script type="text/javascript">
window.alert("Data Berjaya Dipadam.");
</script>
<?php header("Refresh:0");
}else{ ?>
<script type="text/javascript">
window.alert("Maaf data tidak dapat dipadamkan atau data tidak wujud.");
</script>
<?php header("Refresh:0");
}
and this is updatesenarai.php:
<?php $rumah = "RH007";
if(empty($_POST['submit'])){ ?>
<h2>Kemaskini Data Rumah</h2>
<?php include 'updaterumahtable.php'; ?>
<form action="" method="POST">
<label>Kod Rumah : </label><?php echo $rumah ?><br><br>
<label>Nama Rumah : </label><input type="text" name="jrumah"><br><br>
<label>Harga : </label><input type="number" name="price"><br><br>
<input type="submit" name="submit" value="Kemaskini">
<form>
<?php }else{
include 'connect.php';
$jr = $_POST['jrumah'];
$price = $_POST['price'];
$query = "update rumah set jenishomestay='$jr', harga=$price where kodhomestay='$rumah'";
$update= mysqli_query($conn,$query);
if($update){?>
<script type="text/javascript">
window.alert("Data Berjaya Dikemaskini.");
</script>
<?php header("Refresh:0");
}else{ ?>
<script type="text/javascript">
window.alert("Maaf data tidak dapat dikemaskini atau data tidak wujud.");
</script>
<?php header("Refresh:0");
}
mysqli_close($conn);
}?>
everytime i click the update button. it uses the updatesenarai.php but when i want to update the data in sql. it wont update and keep saying the first window alert in delete data. But when i used only updatedata.php it works just fine. If i change the submit button name it the whole file refreshes even without the header(). I tried changing the $conn into something else but it still saying the first window alert from deletedata.php. Im still new.
Check your updatesenarai.php. Your deletedata.php and updatesenarai.php are exactly same. Please write the code for updating in updatesenarai.php.
Objective Inserting name(input-text) and info(textarea-contains multiple lines) into the database, and after submission of the form, at the same page, 2 columns are for displaying the same data in columns, name & info, but under info column. I have made buttons for each row in front of the names, which is used as slideToggle for showing/hiding which contains the data retrieved from the 'info' column
Problem - when I am clicking the button of 1st row, instead of displaying the info related to 1st entry only, it is sliding and showing all info(s) related to all entries at only click.
*others - one more input has been added to the form but as hidden used for id(auto increment)
----index.php-----
<?php include('php_code.php'); ?>
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM records WHERE id=$id");
if (count($record) == 1 ) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$acc = $n['acc_no'];
$info = $n['info'];
}
}
?>
<html>
<head>
<title>JSK</title>
<link rel="stylesheet" href="style.css" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('form').hide();
$('p').hide();
$('#sp').hide();
$("#inf").click(function(){
$("p").slideToggle();
$('#sp').slideToggle();
});
$("#fo").click(function(){
$("form").slideToggle();
});
});
</script>
</head>
<body>
<div class="container">
<div class="left">
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<?php $results = mysqli_query($db, "SELECT * FROM records"); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Account No</th>
<th>Info</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['acc_no']; ?></td>
<td><button id="inf" onclick="myFunction()">show</button></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
Delete
</td>
</tr>
<tr id="sp"> <td colspan="4"><p> <?php echo $row['info']; ?> </p></td>
</tr>
<?php } ?>
</table>
<div id="fotable" align="center">
<button id="fo">Add New/Edit</button>
</div>
<form method="post" action="php_code.php" >
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Name</label>
<input type="text" autocomplete="off" name="name" value="<?php echo $name; ?>">
</div>
<div class="input-group">
<label>Account No</label>
<input type="text" name="acc" value="<?php echo $acc; ?>">
</div>
<div class="input-group">
<label for="info">Info</label>
<textarea class="form-control" rows="8" name="info" id="info"><?php echo $row['info']; ?></textarea>
</div>
<div class="input-group">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Add Account</button>
<?php endif ?>
</div>
</form>
</div><!-- left closed -->
<div class="right">
hello
</div> <!-- right closed -->
</div> <!-- container closed -->
</body>
</html>
---php_code.php-----
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'jskrecords');
// initialize variables
$name = "";
$acc = "";
$info = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "INSERT INTO records (name, acc_no, info) VALUES ('$name', '$acc', '$info')");
$_SESSION['message'] = "Account saved";
header('location: index.php');
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$acc = $_POST['acc'];
$info = $_POST['info'];
mysqli_query($db, "UPDATE records SET name='$name',acc_no='$acc',info='$info' WHERE id=$id");
$_SESSION['message'] = "Account updated!";
header('location: index.php');
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM records WHERE id=$id");
$_SESSION['message'] = "ACC deleted!";
header('location: index.php');
}
?>
Concept:
If you are creating multiple form from same mysql table using php script, You need to give each form a unique id.
e.g.
<form method="post" action="php_code.php" id="form<?= $id ?>">
Then add data-target="#form" to button with class 'inf'. It will store id of form.
<button class="inf" data-target="#form<?= $id ?>">show</button>
When button is clicked we know which form to open from data-target.
<script>
$('.container').on('click','button.inf',function(e){
e.preventDefault();
var formid=$(this).attr('data-target'); //get value of data-target attribute
//...proceed to play toggle with this form 'formid'
I just started to learn how to program and I have been having issues with ajax when it comes to adding items to my cart. Everything is fine when it comes to adding items, its the ajax that is not working and my page constantly keeps refreshing. For the code since there is a lot of it I will put the things I think are the most important.
Index.php
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<title></title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click', '.add_to_cart', function(){
var product_id = $(this).attr("id");
var product_name = $('#name'+product_id+'').val();
var product_price = $('#price'+product_id+'').val();
var product_quantity = $('#quantity'+product_id).val();
if(product_quantity > 0)
{
$.ajax({
url:"index.php",
method:"POST",
data:{product_id:product_id, product_name:product_name, product_price:product_price, product_quantity:product_quantity},
success:function(data)
{
alert("Item has been Added into Cart");
}
});
}
else
{
alert("lease Enter Number of Quantity");
}
});
});
</script>
</head>
<body>
<header>
<?php
include_once'widget/header.php';
if (isset($_SESSION['u_id'])) {
include_once"include/addcart.php";
include_once "widget/shoppingcart.php";
}
?>
</header>
<main>
<div class="item-container">
<?php
$item = mysqli_query($db,"SELECT * FROM itemlist ORDER BY title");
include_once 'widget/container.php';
?>
</div>
</main>
Addcart.php
<?php
$row_ids = array();
//session_destroy();
//check if Add to Cart button has been submitted
if(filter_input(INPUT_POST, 'add_to_cart')){
if(isset($_SESSION['shopping_cart'])){
//keep track of how mnay products are in the shopping cart
$count = count($_SESSION['shopping_cart']);
//create sequantial array for matching array keys to products id's
$row_ids = array_column($_SESSION['shopping_cart'], 'id');
if (!in_array(filter_input(INPUT_POST, 'id'), $row_ids)){
$_SESSION['shopping_cart'][$count] = array
(
'id' => filter_input(INPUT_POST, 'id'),
'name' => filter_input(INPUT_POST, 'name'),
'price' => filter_input(INPUT_POST, 'price'),
'quantity' => filter_input(INPUT_POST, 'quantity')
);
// header("Location:index.php?addedtocart");
}
else { //product already exists, increase quantity
//match array key to id of the product being added to the cart
for ($i = 0; $i < count($row_ids); $i++){
if ($row_ids[$i] == filter_input(INPUT_POST, 'id')){
//add item quantity to the existing product in the array
$_SESSION['shopping_cart'][$i]['quantity'] += filter_input(INPUT_POST, 'quantity');
// header("Location:index.php?multtocart");
}
}
}
}
else { //if shopping cart doesn't exist, create first product with array key 0
//create array using submitted form data, start from key 0 and fill it with values
$_SESSION['shopping_cart'][0] = array
(
'id' => filter_input(INPUT_POST, 'id'),
'name' => filter_input(INPUT_POST, 'name'),
'price' => filter_input(INPUT_POST, 'price'),
'quantity' => filter_input(INPUT_POST, 'quantity')
);
}
}
if (filter_input(INPUT_POST, 'delete')) {
//loop thru intil products in shop cart == variable
foreach ($_SESSION['shopping_cart'] as $key => $row) {
if ($row['id'] == filter_input(INPUT_POST, 'id')) {
unset($_SESSION['shopping_cart'][$key]);
}
}
$_SESSION['shopping_cart'] =array_values($_SESSION['shopping_cart']);
}
?>
Shoppingcart.php
<div class="cart-container" align="right">
<div class="table-responsive">
<table class="table">
<table class="table">
<tr><th colspan="5"><h5>Order Details</h5></th></tr>
<tr>
<th width="40%">Product Name</th>
<th width="10%">Quantity</th>
<th width="20%">Price</th>
<th width="15%">Total</th>
<th width="5%">Action</th>
</tr>
<?php
if(!empty($_SESSION['shopping_cart'])):
$total = 0;
foreach($_SESSION['shopping_cart'] as $key => $product):
?>
<tr>
<td><?php echo $product['name']; ?></td>
<td><?php echo $product['quantity']; ?></td>
<td>$ <?php echo $product['price']; ?></td>
<td>$ <?php echo number_format($product['quantity'] * $product['price'], 2); ?></td>
<td>
<form method="post">
<input class="delete" type="submit" name="delete" value="Delete">
<input type="hidden" name="id" value="<?php echo $product['id']; ?>">
</form>
</td>
</tr>
<?php
$total = $total + ($product['quantity'] * $product['price']);
endforeach;
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<tr>
<!-- Show checkout button only if the shopping cart is not empty -->
<td colspan="5">
<?php
if (isset($_SESSION['shopping_cart'])):
if (count($_SESSION['shopping_cart']) > 0):
?>
Checkout
<?php endif; endif; ?>
</td>
</tr>
<?php
endif;
?>
</table>
</div>
</div>
Container.php
<?php
while ($row = mysqli_fetch_assoc($item)) {
?>
<div class='item-box'>
<img class='item_img' src="itemimg/<?php echo $row['img']; ?>"><figcaption><?php echo $row['title']; ?></ficgcaption>
<form method="post" class="add-form">
<div class='input-group xs-2'>
<input class="form-control" type="text" id="quantity<?php echo $row['id'] ?>" name="quantity" value="1">
<input class="btn btn-outline-primary btn-sm add-btns add_to_cart" type="submit" id="<?php echo $row['id'] ?>" name="add_to_cart" value="Add To Cart">
</div>
<input type="hidden" id="name<?php echo $row['id'] ?>" name="name" value="<?php echo $row['title'] ?>">
<input type="hidden" id="price<?php echo $row['id'] ?>" name="price" value="<?php echo $row['price']; ?>">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
</div>
</form>
<?php
}
?>
Your page will refresh because you are not telling your form to not submit by the default method (which is to reload the page as a POST). To stop the page from reloading and let ajax do the submission, you need to inject the event and then use preventDefault():
$(document).on('click', '.add_to_cart', function(e){
// This will stop the form from submitting and allow the rest of the
// ajax to continue working. If you don't have this, you will immediately
// submit the form which negates the use of ajax
e.preventDefault();
Good morning! Please some body help or give some sample code about how to read text value (per line)
<body onLoad="displayResult()">
<table align="center">
<tr>
<td>
<?php $query2="SELECT * FROM upload1 WHERE NAME='xmlsample1.xml'";
$result1=mysql_query($query2);
$row = mysql_fetch_array($result1);
?>
<form action="">
<textarea id="validxml" rows="50" cols="100">
<?php echo $row['CONTENT']; ?>
</textarea>
<br><br>
<input type="button" value="Verify XML" onClick="validateXML()" />
</form>
</td>
</tr>
</table>
</body>
Access the value of textareaand split newline
console.log(document.getElementById('validxml').value.split("\n"));
JSFiddle
connect.php should be kept on a separate, secure web page.
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
Now on your other page:
<?php
include 'connect.php'; $db = db();
$sq = $db->query("SELECT * FROM upload1 WHERE name='xmlsample1.xml'"); $ta = '';
if($sq->num_rows > 0){
while($row = $sq->fetch_object()){
$ta .= "<textarea class='validxml' name='{$row->name}'>{$row->content}</textarea>";
}
}
$sq->free(); $db->close();
?>
Now just echo $ta into your HTML. Of course, I wouldn't even use a <textarea> to just output code, unless you want your user to be able to edit it.
This question already has answers here:
undefined index text fields php database?
(2 answers)
Closed 8 years ago.
how exactly ajax jquery working. i am new in ajax and jquery.
i want to delete row my using ajax.
index.php
<head><link rel="stylesheet" type="text/css" href="css/style.css"></head>
<h1>Login Here</h1>
<form name="f1" action="login.php" method="post">
<table border="1">
<tr><td>username</td><td><input type="text" name="t1"></td>
</tr>
<tr><td>password</td><td><input type="password" name="t2"></td></tr>
<tr><td><input type="submit" value="login"></td>
<td class="error"><?php if(isset($_GET['wrong_detial'])){
echo "RE-ENTER username and password !! "; }?>
</td>
</tr>
</table>
</form>
login.php
<head>
<script type="text/javascript" src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript">
function del() {
var info = 'id=' + id;
$.ajax({
type: 'get',
url: 'delete.php',
success: function (result) {
$("#div1").html(result);
}
});
return false;
}
</script>
</head>
<?php
include "db/db.php";
$user=$_POST['t1'];
$pass=$_POST['t2'];
$result=mysql_query("select * from registor where username='$user' and password='$pass' ")or die(mysql_error());
$row=mysql_fetch_row($result);
?>
<h1>Welcome Mr. <?php echo $user;?></h1>
<?php
if(!$user == $row[1] || !$pass ==$row[2]){ //if username or password not matched with database
header("location:account.php?wrong_detial");
}
else{
if($user == 'admin'){ //if admin login
?>
<table border="1">
<tr><td>User ID</td><td>Username</td><td>Password</td><td>Email-ID</td><td>delete</td></tr>
<?php
$admin_result=mysql_query("select * from registor");
while($admin_db=mysql_fetch_row($admin_result)){
?>
<tr>
<td><?php echo $admin_db[0];?></td>
<td><?php echo $admin_db[1];?></td>
<td><?php echo $admin_db[2];?></td>
<td><?php echo $admin_db[3];?></td>
<td id="div1">
Delete <!-- Deleting single record-->
</td>
</tr>
<?php
}
?>
</table>
<?php }
?>
delete.php
<?php
include "db/db.php";
if($_GET['delete']){
$drop=$_GET['delete'];
}
$result=mysql_query("delete from registor where username='$drop'");
if($result){
echo "deleted";
}
?>
what is the solution of this.
is there better way to delete record from database using ajax jquery.
Missing end curly braces in login.php for else block.
</table>
<?php }
?>
should be
</table>
<?php }
}
?>