ajax with jquery php not working properly? [duplicate] - javascript

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 }
}
?>

Related

prevent refresh on submit and clear input after submit

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

Problems with Ajax when adding items to my shopping Cart PHP

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();

How To Fix This JavaScript Function?

I want to add confirm box by using JavaScript. So, here is the code that I have used. When I click on the Delete button, it shows me a Confirmation message and when I click Ok, it doesn't delete my row.
What is wrong with this? How can I fix this?
Here is the Index Page
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Bootstrap core CSS -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row"> <!-- Start Of The Row Class -->
<div class="col-md-8 col-sm-4 hero-feature"> <!-- Start Of The Col Class -->
<br><br>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
include('ksdb.php');
// get results from database
$result = mysql_query("SELECT * FROM academic")
or die(mysql_error());
?>
<table class='table table-bordered'>
<tr class='danger'>
<th>ID</th>
<th>Name</th>
<th>Username</th>
</tr>
<?php
// display data in table
while($row = mysql_fetch_array( $result )) {
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['username']; ?></td>
<td><a href="AdminChangePw.php?id=<?php echo $row['id']; ?>" alt="edit" >Change</a></td>
<td><a href="AdminEdit.php?id=<?php echo $row['id']; ?>" alt="edit" >Edit</a></td>
<td><input type="button" onClick="deleteme(<?php echo $row['id']; ?>)" name="Delete" value="Delete"></td>
</tr>
<script language="javascript">
function deleteme(delid)
{
if(confirm("Do you want Delete!")){
window.location="AdminDel.php?id=' +id+'";
return true;
}
}
</script>
<?php
}
?>
</table>
</div> <!-- End Of The Col Class -->
</div> <!-- End Of The Row Class -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"></script>
</body>
</html>
Change the id to 'delid'. You are calling the function as deleteme(delid).
So You Must use delid, instead of id.
function deleteme(delid)
{
if(confirm("Do you want Delete!")){
window.location.href="AdminDel.php?id="+delid; /*Change id to 'delid'*/
return true;
}
}
Use
window.location.href
Instead of window.location
There are a couple of problems with your function:
function deleteme(delid) {
if(confirm("Do you want Delete!")){
window.location="AdminDel.php?id='+id+'";// this should be delid, also bad quotes, also you want to set the href, not the location
return true;
}
}
Fixed:
function deleteme(delid) {
if(confirm("Do you want Delete!")){
window.location.href="AdminDel.php?id=" + delid;
return true;
}
}

submit form not working/ not reload

i create a form(form1) to search mysql data into table without reload the page using ajax, it's working fine, but when i want to insert data from the second form(formorder) the submit button not refresh or reload.
this my code
index.php
<html>
<head>
<title>Search Data Without Page Refresh</title>
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
</head>
<body>
<center>
<br>
<?php include("koneksi1.php");
$sql="select * from supplier";
$query=mysqli_query($koneksi,$sql);
?>
<form action="" name = "form1">
<select name="namea" style="width:300px; padding:8px;">
<?php
while($data=mysqli_fetch_assoc($query)){
echo "<option value='".$data['id_supplier']."'>".$data['id_supplier']."</option>";
}
?>
</select>
<input type="submit" value="Search" id="search-btn" style="padding:8px;"/>
</form>
<br>
<div id = "s-results">
<!-- Search results here! -->
</div>
<script type = "text/javascript">
$(document).ready(function(){
$('#s-results').load('search.php').show();
$('#search-btn').click(function(){
showValues();
});
$(function() {
$('form').bind('submit',function(){
showValues();
return false;
});
});
function showValues() {
$.post('search.php', { namea: form1.namea.value },
function(result){
$('#s-results').html(result).show();
});
}
});
</script>
</center>
</body>
</html>
search.php
<?php
include("koneksi1.php");
isset( $_REQUEST['namea'] ) ? $name=$_REQUEST['namea'] : $name='';
$name = mysqli_real_escape_string($koneksi,$name);
if( empty( $name )){
echo '<script> alert("Please search something!")</script>';
}else{
$sql = "select * from barang where id_supplier like '%$name%'";
$rs = mysqli_query($koneksi,$sql ) or die('Database Error: ' . mysql_error());
$num = mysqli_num_rows($rs);
if($num >= 1 ){
echo "<div style='margin:10px; color:green; font-weight: bold;'>$num records found!</div>";
echo "<table width='365' border ='0' cellspacing='5' cellpadding='5'>";
echo"<tr><th>RESULTS</th></tr>";
echo "<div class='table-responsive'>";
echo "<table class='table table-hover'>";
while($data = mysqli_fetch_array( $rs )){
?>
<tbody>
<?php
$kuantitas=0;
$kuantitas++;
?>
<form action="aksi.php" method="post" id="formorder">
<tr>
<td><?php echo $data['nama_barang']?></td>
<td><?php echo $data['stok']?></td>
<td><input type="text" name="kuantitas" size="4"></td>
<td><input type="text" name="harga_satuan" id="harga_satuan" size="10"></td>
<td><input type="text" name="ppn" id="ppn" size="3"> %</td>
<td><button type="submit" class="btn btn-success btn-sm" id="add" name="add">ADD</button></td>
</tr>
</form>
<?php }?>
</tbody>
</table>
</div>
<?php
}else{
echo "<tr><th>NO RESULTS</th></tr>";
}
}
?>
the button submit in formorder not working, what wrong with my code???

Validation of password using javascript

Following is code for username.php
<html>
<head>
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script>
<!-- <script type="text/javascript" src="js/jquery-ui-1.8.17.custom.min.js"></script> -->
<script type="text/javascript">
$(document).ready(function(){
$("#username").change(function(){
$("#message").html("<img src='ajax-loader.gif' /> checking...");
var username=$("#username").val();
$.ajax({
type:"post",
url:"check.php",
data:"username="+username,
success:function(data){
if(data==0){
$("#message").html("Username available");
}
else{
$("#message").html("Username already taken");
}
}
});
});
});
</script>
</head>
<body>
<table>
<tr>
<td>Username</td>
<td>:</td>
<td><input type="text" name="id" id="username""/><td>
<td id="message"><td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input type="text" name="password" id="password" /><td>
</tr>
</table>
</body>
</html>
And the code for check.php
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['id']))
$username=$_POST['id'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
this code gives output as username and password boxes. I have included all the 3 files ajax-loader.gif, username.php and check.php in one single folder.On entering username no validation is performed. Can anyone help me to figure out why is this happening?
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['username']))// because in ajax you send username not id
$username=$_POST['username'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
?>
Use data:"id="+username in Ajax request because that is the POST variable your checking in PHP.
Also on a side note:
Make sure you handle a case where $_POST['username'] is not set.
<?php
mysql_connect("localhost","healhmate","healthmate");
mysql_select_db("hmdb");
if(isset($_POST['username'])) {// because in ajax you send username not id
$username=$_POST['username'];
$query=mysql_query("SELECT * from user where id='$username' ");
$find=mysql_num_rows($query);
echo $find;
} else {
echo "-1";
}
?>
And do not use mysql_* functions. They are deprecated. Use mysqli_* functions or PDO.

Categories

Resources