Jquery Delete Button - php

I want to delete some records by using jQuery, i don't know what the error is, i cannot delete records. when i click edit button the records, it seems to work fine and record can be modified, but when i click delete button it does not work. here is my code:
index.php
<?php
include('database_connection.php');
$query = "SELECT * FROM apps_countries ORDER BY country_name ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<html>
<head>
<title>How to Make Editable Select Box using jQuery with PHP</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<link rel="stylesheet" href="jquery-editable-select.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="jquery-editable-select.min.js"></script>
</head>
<body>
<div class="container">
<br />
<br />
<br />
<h2 align="center">How to Make Editable Select Box using jQuery with PHP</h2><br />
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<form method="post" id="sample_form">
<div class="form-group">
<label>Enter Name</label>
<input type="text" name="name" id="name" class="form-control">
</div>
<div class="form-group">
<label>Select Country</label>
<select name="country" id="country" class="form-control">
<?php
foreach($result as $row)
{
echo '<option value="'.$row["country_name"].'">'.$row["country_name"].'</option>';
}
?>
</select>
</div>
<div class="form-group">
<input type="hidden" name="action" id="action" value="add" />
<input type="hidden" name="hidden_id" id="hidden_id" value="" />
<input type="hidden" name="hidden_id1" id="hidden_id1" value="" />
<input type="submit" name="Save" id="save" class="btn btn-success" value="Save" />
</div>
</form>
<br />
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Country</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<br />
<br />
<br />
</div>
</body>
</html>
<script>
$(document).ready(function(){
fetch_data();
function fetch_data()
{
$.ajax({
url:"fetch.php",
method:"POST",
success:function(data)
{
$('tbody').html(data);
}
});
}
$('#country').editableSelect();
$('#sample_form').on('submit', function(event){
event.preventDefault();
if($('#name').val() == '')
{
alert("Enter Name");
return false;
}
else if($('#country').val() == '')
{
alert("Select Country");
return false;
}
else
{
$.ajax({
url:"action.php",
method:"POST",
data:$(this).serialize(),
success:function(data)
{
alert(data);
$('#sample_form')[0].reset();
$('#action').val("add");
$('#save').val('Save');
fetch_data();
}
});
}
});
$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("edit");
$('#save').val('Edit');
}
});
});
$(document).on('click', '.Delete', function(){
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id1').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("delete");
$('#save').val('Delete');
}
});
});
});
</script>
fetch.php
<?php
include('database_connection.php');
$query = "SELECT * FROM sample_data ORDER BY id DESC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = '';
if($total_row > 0)
{
foreach($result as $row)
{
$output .= '
<tr>
<td>'.$row["name"].'</td>
<td>'.$row["country"].'</td>
<td><button type="button" name="edit" class="btn btn-primary btn-xs edit" id="'.$row["id"].'">Edit</button></td>
<td><button type="button" name="delete" class="btn btn-danger btn-xs delete" id="'.$row["id"].'">Delete</button></td>
</tr>
';
}
}
else
{
$output .= '
<tr>
<td colspan="3" align="center">Data not found</td>
</tr>
';
}
echo $output;
?>
action.php
<?php
include('database_connection.php');
if(isset($_POST["action"]))
{
if($_POST["action"] == "add")
{
$data = array(
':name' => $_POST["name"],
':country' => $_POST["country"]
);
$query = "
INSERT INTO sample_data (name, country)
VALUES (:name, :country)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
echo 'Data Inserted';
}
}
if($_POST["action"] == 'fetch_single')
{
$query = "SELECT * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output['name'] = $row["name"];
$output['country'] = $row["country"];
}
echo json_encode($output);
}
if($_POST["action"] == "edit")
{
$data = array(
':name' => $_POST["name"],
':country' => $_POST["country"],
':id' => $_POST["hidden_id"]
);
$query = "
UPDATE sample_data
SET name = :name, country = :country
WHERE id = :id
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
echo 'Data Updated';
}
}
if($_POST["action"] == "delete")
{
$data = array(
':name'=> $_POST["name"],
':country' => $_POST["country"],
':id' => $_POST["hidden_id1"]);
$query = "DELETE * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect ->prepare($query);
if($statement->execute($data))
{
echo 'data deleted';
}
}
}
?>
database_connection.php
<?php $connect = new PDO("mysql:host=localhost;dbname=sampl1", "root", ""); ?>

instead of button you can give tag like this
Delete
and featch id using $_REQUEST['id']
<?php
$id =$_REQUEST['id'];
// sending query
$query = "DELETE * FROM sample_data WHERE id='".$_POST["id"]."'";
$statement = $connect ->prepare($query);
if($statement->execute($data))
{
echo 'data deleted';
}
?>

I think your error could be here in this piece of code here.
Sometimes JQuery can be case sensitive.
Change this:
$(document).on('click', '.Delete', function(){
to this:
$(document).on('click', '.delete', function(){
At:
$(document).on('click', '.Delete', function(){ <-- CHANGE THIS LINE HERE AND LEMME KNOW IF IT WORKS
var id = $(this).attr("id");
var action = 'fetch_single';
$.ajax({
url:"action.php",
method:"POST",
data:{id:id, action:action},
dataType:'json',
success:function(data)
{
$('#hidden_id1').val(id);
$('#name').val(data.name);
$('#country').val(data.country);
$('#action').val("delete");
$('#save').val('Delete');
}
});
});

Related

How to get ID of item from database in <select><option> Tag

Hello. I have a problem with the more difficult code but here I tried to simplify it a bit just to ask a question ... I have 3 tables in database: cars(cars_id,model), customers(customer_id,name,surname), sales(sales_id,customer_id,cars_id).And I don't know how to get the ID for the selected option in the select option tag. For example, for BMW X6 I want to get to ID = 2 and put this value in the cars_id column in the SALES table to avoid data redundancy. It's about relation. cars_id in the CARS table is the same as cars_id in the SALES table. But I want to do this using PHP MySQL.
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=store", "root", "");
function fill_unit_select_box($connect)
{
$output = '';
$query = "SELECT * FROM cars";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output .= '<option value="'.$row["model"].'">'.$row["model"].'</option>';
}
return $output;
}
?>
<html>
<head>
<title>Sales form</title>
<script src="jquery-3.5.0.min.js" defer></script>
<link rel="stylesheet" href="bootstrap.min.css" />
<script src="jquery-3.5.0.min.js"></script>
</head>
<body>
<div class="container">
<h3 align="center">Sales form</h3><br />
<form method="post" id="insert_form">
<div class="table-repsonsive">
<span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th >sales</th>
<th >customer</th>
<th >cars</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus">Add</span></button></th>
</tr>
</table>
<div align="center">
<input type="submit" name="submit" class="btn btn-info" value="Send" />
</div>
</div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td class="lp"></td>';
html += '<td><input type="text" name="customers_name[]"></td>';
html += '<td><select style="backbround-color:white;"name="cars_name[]" class="form-control size_id"><option value=""><?php echo fill_unit_select_box($connect); ?></option></select></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Usuń</span></button></td></tr>';
$('#item_table').append(html);
var count=0;
$('.lp').each(function(){
count=count+1;
$(this).text(count);
});
});
$('#insert_form').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
if(error == '')
{
$.ajax({
url:"insert.php",
method:"POST",
data:form_data,
success:function(data)
{
if(data == 'ok')
{
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Dane zostały wysłane</div>');
}
}
});
}
else
{
$('#error').html('<div class="alert alert-danger">'+error+'</div>');
}
});
});
</script>
<?php
//insert.php;
session_start();
if(isset($_POST["customers_name"]))
{
$connect = new PDO("mysql:host=localhost;dbname=store", "root", "");
for($count = 0; $count < count($_POST["customers_name"]); $count++)
{
$query = "INSERT INTO sales
(customer_id,cars_id)
VALUES (:customer_id,:cars_id)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':customer_id' => $_POST["customers_name"][$count],
':cars_id' => $_POST["cars_name"][$count],
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
?>
So, you just have to edit your $output like this.
value="'.$row["model"] to value="'.$row["cars_id"]
change to cars_id only for value, so the user can see the name but you get id on form submit.

How to update database value based on checkbox? Jquery/php/ajax

Been trying for hours trying to figure this out but not getting anywhere.
I am using labels as a checkbox. On check a checkbox, I would like the value of the database to be updated to 1. If the user unchecks the checkbox, I would like the value in the database to be update to 0.
This is the page:
<!DOCTYPE html>
<html>
<head>
<title>Territory</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<?php
require_once 'config.php';
$sql = "SELECT id, address, suburb, lat, lng, date, time FROM addresses";
$result = $conn->query($sql);
echo '<table style="margin:0 auto; max-width:320px;">
<tr>
</tr>';
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<tr>
<td><span style="font-weight:bold;">'.$row["address"].' '. $row["suburb"].'</span> <button style="float:right;" type="button">Go</button><br><br>
<div class="row">
<input type="checkbox" name="id" id="home['. $row["id"].']" value="1"/>
<label class="label" for="home['. $row["id"].']" id="home['. $row["id"].']"></label>
<span id="dropdown">
<select class="dropdown1" name="nhd1" id="'. $row["id"].'" >
<option></option>
<option>Mon</option>
<option>Tue</option>
<option>Wed</option>
<option>Thu</option>
<option>Fri</option>
<option>Sat</option>
<option>Sun</option>
</select>
<select class="dropdown2" name="nht1" id="'. $row["id"].'" >
<option></option>
<option>8:00am</option>
<option>8:30am</option>
<option>9:00am</option>
<option>9:30am</option>
<option>10:00am</option>
<option>10:30am</option>
<option>11:00am</option>
<option>11:30am</option>
<option>12:00pm</option>
<option>12:30pm</option>
<option>1:00pm</option>
<option>1:30pm</option>
<option>2:00pm</option>
<option>2:30pm</option>
<option>3:00pm</option>
<option>3:30pm</option>
<option>4:00pm</option>
<option>4:30pm</option>
<option>5:00pm</option>
<option>5:30pm</option>
<option>6:00pm</option>
<option>6:30pm</option>
<option>7:00pm</option>
<option>7:30pm</option>
</select>
<select class="dropdown1" name="nhd2" id="'. $row["id"].'" >
<option></option>
<option>Mon</option>
<option>Tue</option>
<option>Wed</option>
<option>Thu</option>
<option>Fri</option>
<option>Sat</option>
<option>Sun</option>
</select>
<select class="dropdown2" name="nht2" id="'. $row["id"].'" >
<option></option>
<option>8:00am</option>
<option>8:30am</option>
<option>9:00am</option>
<option>9:30am</option>
<option>10:00am</option>
<option>10:30am</option>
<option>11:00am</option>
<option>11:30am</option>
<option>12:00pm</option>
<option>12:30pm</option>
<option>1:00pm</option>
<option>1:30pm</option>
<option>2:00pm</option>
<option>2:30pm</option>
<option>3:00pm</option>
<option>3:30pm</option>
<option>4:00pm</option>
<option>4:30pm</option>
<option>5:00pm</option>
<option>5:30pm</option>
<option>6:00pm</option>
<option>6:30pm</option>
<option>7:00pm</option>
<option>7:30pm</option>
</select>
</span>
</div>
<input style="width:98.5%; margin-top:5px;" type="text" name="notes" placeholder="Add note">
<br><br>
</td>
<td>
</td>
</tr>';
echo '</div>';
}
} else {
echo "0 results";
}
echo '</table>';
$conn->close();
?>
<script>
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var home = 0;
if ($('input[type="checkbox"]').is(":checked")) {
var home = 1;
}
var id = $(this).val();
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:home,id:id,},
success: function(data){
alert(data);
},
});
});
});
$(document).ready(function(){
$('select[name=nhd1]').change(function(){
var nhd1 = $(this).val();
var id = $(this).attr('id');
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{nhd1:nhd1,id:id,},
});
});
});
$(document).ready(function(){
$('select[name=nhd2]').change(function(){
var nhd2 = $(this).val();
var id = $(this).attr('id');
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{nhd2:nhd2,id:id,},
});
});
});
//learn to refresh page just in case more than one group working on map
</script>
echo '<tr>
<td><span style="font-weight:bold;">'.$row["address"].' '. $row["suburb"].'</span> <button style="float:right;" type="button">Go</button><br><br>
<div class="row">
<input type="checkbox" name="home['. $row["id"].']" id="home['. $row["id"].']" value="1"/>
<label class="label" for="home['. $row["id"].']" id="home['. $row["id"].']"></label>
</div>
<input style="width:98.5%; margin-top:5px;" type="text" name="notes" placeholder="Add note">
<br><br>
</td>
<td>
</td>
</tr>';
echo '</div>';
<script>
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if ($('input[type="checkbox"]').is(":checked")) {
var home = 1;
var id = $(this).attr('id');
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:home,id:id,},
}
});
});
});
</script>
This is the query:
<?php
// Include config file
require_once 'config.php';
$id = mysqli_real_escape_string($conn, $_POST['id']);
$home = mysqli_real_escape_string($conn, $_POST['home']);
$nhd1 = mysqli_real_escape_string($conn, $_POST['nhd1']);
$nht1 = mysqli_real_escape_string($conn, $_POST['nht1']);
$nhd2 = mysqli_real_escape_string($conn, $_POST['nhd2']);
$nht1 = mysqli_real_escape_string($conn, $_POST['nht2']);
if(isset($_POST["home"])) {
$sql = "UPDATE addresses SET home='$home' WHERE id=$id";
if($conn->query($sql) === TRUE){
} else {
echo "error" . $sql . "<br>".$conn->error;
}
}
Create another input checkbox with same name and value of 0. If you don't click the checkbox, it will return the input box with same name and value of 0 or otherwise it will return value of 1.
<input type="checkbox" name="home['. $row["id"].']" id="home['. $row["id"].']" value="1"/>
<input type="hidden" name="home['. $row["id"].']" id="home['. $row["id"].']" value="0"/>
In the below code block, there was problem with your checkbox id not correctly set, as well as its value. I fixed it with:
echo '<tr>
<td><span style="font-weight:bold;">'.$row["address"].' '. $row["suburb"].'</span> <button style="float:right;" type="button">Go</button><br><br>
<div class="row">
<input type="checkbox" name="id" id="id" value="'.$row["id"].'"/>
<label class="label" for="home['. $row["id"].']" id="home['. $row["id"].']"></label>
</div>
<input style="width:98.5%; margin-top:5px;" type="text" name="notes" placeholder="Add note">
<br><br>
</td>
<td>
</td>
</tr>';
echo '</div>';
You have syntax errors in your JQuery script. They're fixed. Also you're not setting home = 0 when uncheck happens. And you don't check for status response from server. I added that as well.
Try this:
<script>
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
var home = 0;
if ($('input[type="checkbox"]').is(":checked")) {
var home = 1;
}
var id = $(this).val();
$.ajax({
url:"updateaddress.php",
method:"POST",
data:{home:home,id:id,},
success: function(data){
alert(data);
},
});
});
});
</script>
In your updateaddress.php, I added an status output to notify you of successful update.
Change to:
<?php
require_once 'config.php';
print_r( $_POST );
$id = mysqli_real_escape_string($conn, $_POST['id']);
$home = mysqli_real_escape_string($conn, $_POST['home']);
$nhd1 = mysqli_real_escape_string($conn, $_POST['nhd1']);
$nht1 = mysqli_real_escape_string($conn, $_POST['nht1']);
$nhd2 = mysqli_real_escape_string($conn, $_POST['nhd2']);
$nht1 = mysqli_real_escape_string($conn, $_POST['nht2']);
if(isset($_POST["home"])) {
$sql = "UPDATE addresses SET home='$home' WHERE id=$id";
if($conn->query($sql) === TRUE){
echo "Success";
} else {
echo "error" . $sql . "<br>".$conn->error;
}
}
?>

Updating textarea and datetime

Well, I have these input fields of date_submitted and remarks. My date_submitted is in a input type of datetime-local and my remarks is in a textarea tag. I have a function where in I can update the data I entered in it.
So here are my problems with examples:
ex. I input 03/03/2018 12:31 AM then click add for it to be added in the database, now when I am going to update it, it just shows this mm/dd/yyyy --:-- -- instead of 03/03/2018 12:31 AM
ex. For the remarks, when I input
Hello
World
then add it then update it, it shows in the textarea field this
Hello //insert br tag
World //insert br tag
so my questions are how am I gonna remove the br tags whenever I update my data? I have used nl2br in this one. and how will my inputted date still show up whenever I hit my update button? TYVM.
Below are excerpts from my code
index
<div class="col-sm-2">
<input type="datetime-local" name="date_submitted" id="date_submitted" class="form-control" placeholder="Date Submitted" style="width: 120%;"/>
</div>
<div class="col-sm-3">
<textarea name="remarks" id="remarks" class="form-control" placeholder="Remarks" rows="2" style="margin-left:13%;"></textarea>
</div>
<div class="col-sm-2">
<input type="hidden" name="id" id="docu_id" />
<button class="button add" name="action" id="action" style="margin-left: 16%;">Add</button>
</div>
<br><br>
script
<script>
$(document).ready(function(){
fetchDocu();
function fetchDocu()
{
var action = "select";
$.ajax({
url: "select.php",
method: "POST",
data: {action:action},
success: function(data){
$('#code').val('');
$('#doc_kind').val('');
$('#date_submitted').val('');
$('#remarks').val('');
$('#action').text("Add");
$('#result').html(data);
}
});
}
$('#action').click(function(){
var docCode = $('#code').val();
var docKind = $('#doc_kind').val();
var dateSubmitted = $('#date_submitted').val();
var docRemarks = $('#remarks').val();
var id = $('#docu_id').val();
var action = $('#action').text();
if(docCode != '' && docKind != '' && dateSubmitted != '')
{
$.ajax({
url : "action.php",
method:"POST",
data:{docCode:docCode, docKind:docKind, dateSubmitted:dateSubmitted, docRemarks:docRemarks, id:id, action:action},
success:function(data){
alert(data);
fetchDocu();
}
});
}
else {
alert("All Fields are Required");
}
});
$(document).on('click','.update', function(){
var id = $(this).attr("id");
$.ajax({
url: "fetch.php",
method: "POST",
data: {id:id},
dataType: "json",
success:function(data){
$('#action').text("Save");
$('#docu_id').val(id);
$('#code').val(data.code);
$('#doc_kind').val(data.doc_kind);
$('#date_submitted').val(data.date_submitted);
$('#remarks').val(data.docRemarks);
}
})
});
action.php
if($_POST["action"] == "Save")
{
$code = mysqli_real_escape_string($connect, $_POST["docCode"]);
$doc_kind = mysqli_real_escape_string($connect, $_POST["docKind"]);
$date_submitted = mysqli_real_escape_string($connect, $_POST["dateSubmitted"]);
$remarks = mysqli_real_escape_string($connect, $_POST["docRemarks"]);
$procedure = "
CREATE PROCEDURE updateDocu(IN docu_id int(11), docCode varchar(20), docKind varchar(150), dateSubmitted varchar(150), docRemarks varchar(150))
BEGIN
UPDATE officeSecTB SET code=docCode, doc_kind=docKind, date_submitted=dateSubmitted, remarks=docRemarks
WHERE id = docu_id;
END;
";
if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS updateDocu"))
{
if(mysqli_query($connect, $procedure))
{
$query = "CALL updateDocu('".$_POST["id"]."', '".$code."', '".$doc_kind."','".$date_submitted."', '".$remarks."')";
mysqli_query($connect, $query);
echo 'Data Updated';
}
}
}
and this is how I display the output
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tbody>
<tr>
<td>'.$row["code"].'</td>
<td>'.$row["doc_kind"].'</td>
<td>'.date('d M Y - H:i A', strtotime($row['date_submitted'])).'</td>
<td>'.nl2br($row["remarks"]).'</td>
<div class="row">
<td>
<div class="col-sm-6">
<button name="update" id="'.$row["id"].'" class="button update btn-xs">Update</button>
</div>
<div class="col-sm-6">
<button name="delete" id="'.$row["id"].'" class="button delete btn-xs">Delete</button>
</div>
</td>
</div>
</tr>
</tbody>
';
}
}
Sorry for the long post. Thank you in advance.
fetch.php
<?php
$connect = mysqli_connect("localhost","root", "", "ustjhsdts");
if(isset($_POST["id"]))
{
$output = array();
$procedure = "
CREATE PROCEDURE whereDocu(IN docu_id int(11))
BEGIN
SELECT * FROM officesectb WHERE id = docu_id;
END;
";
if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereDocu"))
{
if(mysqli_query($connect, $procedure))
{
$query = "CALL whereDocu(".$_POST["id"].")";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$output['code'] = $row["code"];
$output['doc_kind'] = $row["doc_kind"];
$output['date_submitted'] = $row['date_submitted'];
$output['remarks'] = nl2br($row["remarks"]);
}
echo json_encode($output);
}
}
}
?>

not able to carry the form values through post method

There is a form where the user enters a number and according to the condition applied on the number, a list of addresses are displayed. I would like to store the data that is returned through AJAX. The code on the page that has a form:
index.php
<script>
$(document).ready(function() {
$("#phone").keyup(function() {
var number = $("#phone").val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: 'number='+number,
cache: false,
}).done(function(html) {
$('#results').html(html);
});
});
});
<script>
<form action="insert_temp.php" method="POST">
<input type="text" name="phoneno" id="phone" value="" />
<div id="results"></div>
<button class="button btn btn-primary btn-large" type="submit" name="submit" value="submit">Submit</button>
</form>
code on t_fetchaddr.php page
$val = $_REQUEST['number'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0)
{ ?>
<div class="span6" >
<div class="span3">
<? while($row2 = mysqli_fetch_assoc($result2))
{ ?>
<input type="radio" name="old_address" value="<? echo $row2['address']; ?>" ><? echo $row2['address']; ?><br>
<? } ?>
</div>
</div>
<? } ?>
code on insert_temp.php page
$old_address = mysqli_real_escape_string($con, $_POST['old_address']);
echo $old_address;
Everything is working fine until displaying of the address through number, but when I submit the form it is not going to the back end. I tried to echo $old_address but got nothing.
other input values in index page inside the form are going to backend but value that is being fetched from t_fetchaddr.php page is not getting carried, Can anyone please tell where I went wrong
Try this and watch your console :
$(document).ready(function() {
$("#phone").keyup(function() {
var number = $(this).val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: {number:number},
cache: false,
success : function(html) {
$('#results').html(html);
},
error : function(err){
console.log(err);
}
});
});
});
<script>
$(document).ready(function()
{
$("#phone").keyup(function()
{
var number = $("#phone").val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: {number :number}, //modified
cache: false,
success:function(html)
{
$('#results').html(html);
}
});
});
});
</script>//Missing closing
<form action="insert_temp.php" method="POST">
<input type="text" name="phoneno" id="phone" value="" />
<div id="results"></div>
<button class="button btn btn-primary btn-large" type="submit" name="submit" value="submit" >Submit</button>
</form>
and in php
$val = $_POST['phoneno'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0)
{ ?>
<div class="span6" >
<div class="span3">
<? while($row2 = mysqli_fetch_assoc($result2))
{ ?>
<input type="radio" name="old_address" value="<? echo $row2['address']; ?>" ><? echo $row2['address']; ?><br>
<? } ?>
</div>
</div>
<? } ?>
Note:
Missing closing tag </script>
And this line changed data: 'number='+number,
just try this code on fetchaddr.php
i have just removed the in between php tags.
<?
$val = $_REQUEST['number'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0) {
echo '<div class="span6" >
<div class="span3">';
while($row2 = mysqli_fetch_assoc($result2))
{
echo '<input type="radio" name="old_address" value="'.$row2['address'].'" >'.$row2['address'].'<br>';
}
echo '</div>
</div>';
} ?>
hopefully this will solve your problem.

when try to add more field and select then its conflict first row

When i am trying to select option value form row one there's no problem but if i add more and select optional value in second row then its getting conflict first. Every time when you select optional value then only first row conflict i want first row change while changing first select option . Second row select change only second row values.
index.php
<?php
if(!empty($_POST["save"])) {
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$itemCount = count($_POST["item_name"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for($i=0;$i<$itemCount;$i++) {
if(!empty($_POST["item_name"][$i]) || !empty($_POST["item_price"][$i])) {
$itemValues++;
if($queryValue!="") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_name"][$i] . "', '" . $_POST["item_price"][$i] . "')";
}
}
$sql = $query.$queryValue;
if($itemValues!=0) {
$result = mysql_query($sql);
if(!empty($result)) $message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
function addMore() {
$("<DIV>").load("input.php", function() {
$("#product").append($(this).html());
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php if(isset($message)) { echo $message; }?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index:item_index},`
success:function(result){
alert(result);
$('#div1').html(result);
}
});
}
</script>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
<DIV class="float-left"><select name="item_index" id="item_index" class="required input-small" onchange="salesdetail(this.value);" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$result = mysql_query("select * from item");
while($row=mysql_fetch_assoc($result))
{
echo "<option>".$row['item_name']."</option>";
}
?>
</select>
</DIV>
<DIV class="float-left" id="div1"><input type="text" id="unit_price" name="unit_price" /></DIV>
</DIV>
and getsaleinfo.php
<?php
$conn = mysql_connect("localhost","root","");
mysql_select_db("ajaxphp",$conn);
$supplier= $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
if($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini" value="<?php echo $row['item_price'];?>" >
</div>
<?php }
?>
database
CREATE TABLE IF NOT EXISTS `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`item_name` varchar(255) NOT NULL,
`item_price` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `item` (`id`, `item_name`, `item_price`) VALUES
(1, 'hello', 21),
(2, 'hi', 22);
try this...
$('body').on('change','#item_index',function() { //works for ajax loaded contents
var id = $("#item_index").val();
var formid = new FormData();
formid.append('item_index',id);
$.ajax({
url : 'getsaleinfo.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formid,
type : 'post',
success : function(data){
alert(result);
$('#div1').html(result);
//document.getElementById("div1").innerHTML=data;
}
});
}
insted of onchange call this will do...
When you change the selection in the dropdown list, it sends the request to the server:
getsaleinfo.php with item_index:'hello'
That executes
select * from item where item_name='hello' (one line)
That sends
<div class="float-left">
<!--<label id="unit" ></label>-->
<input type="text" name="unit_price" id="unit_price" class="input-mini"
value="<?php echo $row['item_price'];?>" >
</div>
back to the caller.
The javascript puts that whole thing inside #div1 replacing whatever was there.
From what I'm gathering, addMore() is loading the whole of input.php every time and appending it to #product.
First of all that means you're repeated adding the jquery and function definition, but secondly (and the main problem) - each one adds a NEW div with ID=div1.
When you call
$('#div1').html(result)
in your salesdetail function, that just refers to the first one (since according to HTML you can only have one instance of each ID and the others are ignored.
/*------------------------index.php--------------------------*/
<?php
if (!empty($_POST["save"])) {
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$itemCount = count($_POST["item_index"]);
$itemValues = 0;
$query = "INSERT INTO item (item_name,item_price) VALUES ";
$queryValue = "";
for ($i = 0; $i < $itemCount; $i++) {
if (!empty($_POST["item_index"][$i]) || !empty($_POST["unit_price"][$i])) {
$itemValues++;
if ($queryValue != "") {
$queryValue .= ",";
}
$queryValue .= "('" . $_POST["item_index"][$i] . "', '" . $_POST["unit_price"][$i] . "')";
}
}
$sql = $query . $queryValue;
if ($itemValues != 0) {
$result = mysql_query($sql);
if (!empty($result))
$message = "Added Successfully.";
}
}
?>
<HTML>
<HEAD>
<TITLE>PHP jQuery Dynamic Textbox</TITLE>
<LINK href="style.css" rel="stylesheet" type="text/css" />
<SCRIPT src="http://code.jquery.com/jquery-2.1.1.js"></SCRIPT>
<SCRIPT>
var cnt = 1;
function addMore() {
$("<DIV>").load("input.php?cnt=" + cnt, function() {
$("#product").append($(this).html());
cnt++;
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item) {
jQuery(':checkbox', this).each(function() {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
</HEAD>
<BODY>
<FORM name="frmProduct" method="post" action="">
<DIV id="outer">
<DIV id="header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
<?php require_once("input.php") ?>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
<span class="success"><?php
if (isset($message)) {
echo $message;
}
?></span>
</DIV>
<DIV class="footer">
<input type="submit" name="save" value="Save" />
</DIV>
</DIV>
</form>
</BODY>
</HTML>
input.php
/*------------------------input.php--------------------------*/
<script type="text/javascript" src="js/jquery.min.js"></script>
<script>
function salesdetail(item_index, item_id)
{
alert(item_index);
$.ajax({
url: 'getsaleinfo.php',
type: 'POST',
data: {item_index: item_index, item_id: item_id},
success: function(result) {
alert(result);
$('#div_' + item_id).html(result);
}
});
}
</script>
<?php $_REQUEST['cnt'] = (isset($_REQUEST['cnt'])) ? $_REQUEST['cnt'] : 0; ?>
<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_ind[]" id="item_ind_<?php echo $_REQUEST['cnt']; ?>" /></DIV>
<DIV class="float-left"><select name="item_index[]" id="item_index_<?php echo $_REQUEST['cnt']; ?>" class="required input-small" onchange="salesdetail(this.value, '<?php echo $_REQUEST['cnt']; ?>');" >
<option>Select</option>
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$result = mysql_query("select * from item");
while ($row = mysql_fetch_assoc($result)) {
echo "<option>" . $row['item_name'] . "</option>";
}
?>
</select></DIV>
<DIV class="float-left" id="div_<?php echo $_REQUEST['cnt']; ?>"><input type="text" id="unit_price_<?php echo $_REQUEST['cnt']; ?>" name="unit_price[]" /></DIV>
</DIV>
getsaleinfo.php
/*------------------------getsaleinfo.php--------------------------*/
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("ajaxphp", $conn);
$supplier = $_POST['item_index'];
$sql = "select * from item where item_name='$supplier'";
$rs = mysql_query($sql);
?>
<?php
$_REQUEST['item_id'] = (isset($_REQUEST['item_id'])) ? $_REQUEST['item_id'] : '';
if ($row = mysql_fetch_array($rs)) {
?>
<div class="float-left">
<input type="text" name="unit_price[]" id="unit_price_<?php echo $_REQUEST['item_id']; ?>" class="input-mini" value="<?php echo $row['item_price']; ?>" >
</div>
<?php }
?>

Categories