I have an HTML table that can be edited and saved. When saved I want it to update any changes made, to the database. Right now I have it so that whenever the table is saved, it automatically saves "23" into the "Buyer_ID" column because it is hardcoded in. However, how can I get it so that it is not hardcoded in and will read and save any values that are typed, added, or edited in the table?
HTML/PHP code:
<div id="dialog-form" title="Add Vendor">
<p class="validateTips">All form fields are required.</p>
<form>
<fieldset>
<label for="mr_name">Vendor</label>
<input type="text" name="mr_name" id="mr_name" class="text ui-widget-content ui-corner-all">
<label for="buyer_id">Buyer ID</label>
<input type="text" name="buyer_id" id="buyer_id" class="text ui-widget-content ui-corner-all">
<label for="poc_n">POC Name</label>
<input type="text" name="poc_n" id="poc_n" class="text ui-widget-content ui-corner-all">
<label for="poc_p">POC Email</label>
<input type="text" name="poc_e" id="poc_e" class="text ui-widget-content ui-corner-all">
<label for="poc_p">POC Phone</label>
<input type="text" name="poc_p" id="poc_p" class="text ui-widget-content ui-corner-all">
<!-- Allow form submission with keyboard without duplicating the dialog button -->
<input type="submit" id="submit" tabindex="-1" style="position:absolute; top:-1000px">
</fieldset>
</form>
</div>
<form method="post" action="ajaxsubmit.php">
<div id="users-contain" class="ui-widget">
<table id="html_master" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header">
<td>ID</td>
<td>Vendor</td>
<td>Buyer ID</td>
<td>POC Name</td>
<td>POC Email</td>
<td>POC Phone</td>
<td>Edit/Delete</td>
</tr>
</thead>
<tbody>
<?php
foreach ($dbh->query($sql) as $rows){
?>
<tr>
<td class="mr_id" contenteditable="false"><?php echo intval ($rows['MR_ID'])?></td>
<td class="mr_name" name="field" contenteditable="false"><?php echo $rows['MR_Name']?></td>
<td class="buyer_id" contenteditable="false"><?php echo $rows['Buyer_ID']?></td>
<td class="poc_n" contenteditable="false"><?php echo $rows['MR_POC_N']?></td>
<td class="poc_e" contenteditable="false"><?php echo $rows['MR_POC_E']?></td>
<td class="poc_p" contenteditable="false"><?php echo $rows['MR_POC_P']?></td>
<td><input type="button" class="edit" name="edit" value="Edit">
<input type="button" class="deactivate" name="deactivate" value="Deactivate"></td>
</tr>
<?php
}
?>
</tbody>
<input type="button" class="create-user" value="Add Row">
<input type="submit" value="Save Table" class="save">
</table>
</div>
<input type="button" class="create-user" value="Add Row">
<input type="submit" value="Save Table" class="save">
</form>
JavaScript save function:
// ----- Save Table -----
$(document).on("click", ".save", function () {
// ------ Confirmation box in order to deactivate/activate row -----
if (confirm('Saving will update the entire table. Are you sure you want to save?')) {
var tabledata=[];
$( "#html_master tbody tr" ).each(function( index ) {
tabledata[index] = {
mr_id: $( this ).find("td.mr_id").text(),
mr_name: $( this ).find("td.mr_name").text(),
buyer_id: $( this ).find("td.buyer_id").text(),
poc_n: $( this ).find("td.poc_n").text(),
poc_e: $( this ).find("td.poc_e").text(),
poc_p: $( this ).find("td.poc_p").text()
};
});
}
});
Ajax submit code:
<?php
$host="xxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
try {
$conn = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$qry=$conn->prepare('INSERT INTO Stage_Rebate_Master (Buyer_ID) VALUES (23)');
$qry->execute(Array("23" => $field));
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage() . " file: " . $e->getFile() . " line: " . $e->getLine();
exit;
}
?>
<form method="post">
<input type="text" name="field" value="<?php print $field; ?>">
<input type="submit" name="youraction" value="save">
</form>
Remove all of your <form> elements and use only AJAX. Change your JS on click handler to this.
$(document).on("click", ".save", function () {
if (confirm('Saving will update the entire table. Are you sure you want to save?')) {
var tabledata=[];
$( "#html_master tbody tr" ).each(function( index ) {
tabledata[index] = {
mr_id: $( this ).find("td.mr_id").text(),
mr_name: $( this ).find("td.mr_name").text(),
buyer_id: $( this ).find("td.buyer_id").text(),
poc_n: $( this ).find("td.poc_n").text(),
poc_e: $( this ).find("td.poc_e").text(),
poc_p: $( this ).find("td.poc_p").text()
}
});
$.ajax({
url: 'yourPHPfile.php', //Change this to your PHP file
data: {tableData: tabledata},
type: 'POST',
dataType: 'JSON',
error: function (request, error) {
console.log(error);
},
success: function (data) {
console.log(data);
}
});
}
});
PHP
<?php
$host="xxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$tableArray = $_POST['tableData'];
try {
$conn = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//Loop through each Array object and grab each objects value for the specified database column
foreach($tableArray as $key=>$value){
$qry=$conn->prepare('UPDATE Stage_Rebate_Master SET `Mr_Name`=?,`Buyer_ID`=?,`Poc_n`=?,`Poc_e`=?,`Poc_p`=? WHERE `Mr_Id`=?');
$qry->execute(Array($value->mr_name,$value->buyer_id,$value->poc_n,$value->poc_e,$value->poc_p,$value->mr_id));
}
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage() . " file: " . $e->getFile() . " line: " . $e->getLine();
exit;
}
?>
This passes a JSON array of objects to PHP with the AJAX post method. Change the column names in the prepare statement to match your database columns. It will update the entire database table with all the data in the HTML table once you click "confirm" in your "Save" dialog.
I suggest you do a lot more reading on PDO prepared statements as what you have currently is not even close to a prepared statement.
This is also assuming the mr_id column is your primary key. If it is not, you'll need to make those changes accordingly.
Related
Inside a table, I've created multiple forms using a loop based on data inside database.
Now I am not getting a way to implement a logic by which I wanted to identify of which form submit button is pressed so that I can update data accordingly in database.
What I did is putted an ID of that particular row as submit button id, but I am not getting how to put the same ID in javascript file (separate file) to fetch the field details, can someone help?
<?php
foreach ($get_subscribed_data as $filtered_items) { ?>
<tr>
<form id="<?php echo $filtered_items->id; ?>" method="POST">
<td><input type="text" class="form-group" id="user_account_name" value="<?php echo $filtered_items->user_account_name; ?>"><?php echo $filtered_items->user_account_name; ?></td>
<td><input type="text" class="form-group" id="user_project_name" value="<?php echo $filtered_items->user_project_name; ?>"><?php echo $filtered_items->user_project_name; ?></td>
<td><input type="text" class="form-group" id="start_date" value="<?php echo $filtered_items->start_date; ?>"><?php echo $filtered_items->start_date; ?></td>
<td><input type="text" class="form-group" id="due_date" value="<?php echo $filtered_items->due_date; ?>"><?php echo $filtered_items->due_date; ?></td>
<td><input type="submit" id="<?php echo $filtered_items->id; ?>" class="btn-primary btn-sm">Submit</button></td>
</tr></form>
<?php } ?>
UPDATE:
jQuery code I am using:
$(document).ready(function() {
$('.row-submit').on('click', e => {
alert('test');
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
type: "POST",
url: ajaxurl,
action: "send_modification_training_data",
data: {
user_account_name: $tr.find('.user_account_name').val(),
user_project_name: $tr.find('.user_project_name').val(),
start_date: $tr.find('.start_date').val(),
due_date: $tr.find('.due_date').val(),
},
success: response => {
console.log(response);
}
});
});
});
I'm presuming that you're using AJAX to send the form data, otherwise you wouldn't need to know which form was submit as the browser will collate the data for you.
To retrieve the data related to the clicked submit button you need to correct your HTML. Firstly, you need to remove all id attributes from the HTML you generate in the PHP loop as it will create duplicate values which is invalid, they must be unique. Change them to classes instead. Secondly, you cannot place a form element as a child of a tr.
In fact, given that you're using a table here you cannot use a form at all, as there's no way to make the HTML valid. You need to collate the input data on each row. To do this you can use closest() to find the tr related to the button and retrieve the input values using find(). Something like this:
<?php foreach ($get_subscribed_data as $filtered_items) { ?>
<tr>
<td>
<input type="text" class="form-group user_account_name" value="<?php echo $filtered_items->user_account_name; ?>">
<?php echo $filtered_items->user_account_name; ?>
</td>
<td>
<input type="text" class="form-group user_project_name" value="<?php echo $filtered_items->user_project_name; ?>">
<?php echo $filtered_items->user_project_name; ?>
</td>
<td>
<input type="text" class="form-group start_date" value="<?php echo $filtered_items->start_date; ?>">
<?php echo $filtered_items->start_date; ?>
</td>
<td>
<input type="text" class="form-group due_date" value="<?php echo $filtered_items->due_date; ?>">
<?php echo $filtered_items->due_date; ?>
</td>
<td>
<button type="button" class="btn-primary btn-sm row-submit">Submit</button>
</td>
</tr>
<?php } ?>
$('.row-submit').on('click', e => {
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
url: 'your-handler.php',
type: 'POST',
data: {
user_account_name: $tr.find('.user_account_name').val(),
user_project_name: $tr.find('.user_project_name').val(),
start_date: $tr.find('.start_date').val(),
due_date: $tr.find('.due_date').val(),
},
success: response => {
console.log(response);
}
});
});
EDIT
I have implemented the changes suggested and I still cant get this to work:
Form Page Follows (login.php)
<?php
$mac=$_POST['mac'];
$ip=$_POST['ip'];
$username=$_POST['username'];
$linklogin=$_POST['link-login'];
$linkorig=$_POST['link-orig'];
$error=$_POST['error'];
$chapid=$_POST['chap-id'];
$chapchallenge=$_POST['chap-challenge'];
$linkloginonly=$_POST['link-login-only'];
$linkorigesc=$_POST['link-orig-esc'];
$macesc=$_POST['mac-esc'];
if (isset($_POST['postcode'])) {
$postcode = $_POST['postcode'];
}
if (isset($_POST['email'])) {
$email = $_POST['email'];
}
?>
**SOME HTML HERE**
<script src="jquery-3.2.1.min.js"></script>
<script>
var js-postcode = document.login.getElementsByName("postcode").value;
var js-email = document.login.getElementsByName("email").value;
var formdata = {postcode:js-postcode,email:js-email};
$("button").click(function(){
$.ajax(
{
type: "POST",
url: "database.php", //Should probably echo true or false depending if it could do it
data : formdata,
success: function(feed) {
if (feed!="true") {
// DO STUFF
} else {
console.log(feed);
// WARNING THAT IT WASN'T DONE
}
}}}
</script>
</head>
<body>
<table width="100%" style="margin-top: 10%;">
<tr>
<td align="center" valign="middle">
<table width="240" height="240" style="border: 1px solid #cccccc; padding: 0px;" cellpadding="0" cellspacing="0">
<tr>
<td align="center" valign="bottom" height="175" colspan="2">
<!-- removed $(if chap-id) $(endif) around OnSubmit -->
<form name="login" action="<?php echo $linkloginonly; ?>" method="post" onSubmit="return doLogin()" >
<input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
<input type="hidden" name="popup" value="true" />
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php echo $username; ?>"/></td>
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><button><input type="submit" value="OK" /></button></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
document.login.username.focus();
//-->
</script>
</body>
</html>
and called file database.php is as follows:
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
$connect= new mysqli_connect('xx','xx','xx','xx');
if ($conn->connect_errno) {
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(postcode,email)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
//NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.
if (!$sql->bind_param("ss", $postcode, $email)) {
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
}
if (!$sql->execute()) {
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
}
} else {
echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.
}
?>
Still I get nothing fed through from the form to the database. Even if I swap the variables for strings I get nothing through to the database however if I run database.php separately it works. Surely Im close to getting this working now .. any help appreciated and thanks so much for the assistance provided so far.
*************************** ORIGINAL QUESTION FOLLOWS *******************
I have a simple form as follows:
<form name="login" action="somethingelse.php" method="post" onSubmit="return doLogin()" >
<input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
<input type="hidden" name="popup" value="true" />
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php e$
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><button><input type="submit" value="OK" /></button></td>
</tr>
</table>
</form>
Because I need to use the form action to do something else, I need to use jQuery on the click of the button to send data to a database. Specifically the postcode and email address taken from the form. The part of the code relating to the jQuery is shown below:
<script language="JavaScript" >
$(document).ready(function(){
$("button").click(function(){
mysqli_query();
});
});
</script>
The called function mysqli_query is declared via an include statement and therefore lives in a different file. The function called is shown below:
mysqli_query( $connect, "INSERT INTO visitors(postcode,email) VALUES(postcode,email)");
I have been going round in circles for days with this. I know Im close to making it work but cant quite cross the finish line. Could somebody please point out what I'm doing wrong here?
WARNING: Never ever trust user input, always sanitize the input first AND use prepared statements otherwise, you're leaving youself vulnerable to SQL INJECTION ATTACKS
You're mixing up, Javascript is a clientside language, and mysqli is a PHP based function on the serverside of things.
What you should be doing is an ajax call with the values to a different PHP file that will make the database connection and insert the data.
var dataString = "postcode="+ postcode+"&email="+email;
$.ajax({
type: "POST",
url: "file_that_does_the_work.php", //Should probably echo true or false depending if it could do it
data: dataString,
success: function(feed) {
if (feed=="true") {
// DO STUFF
} else {
console.log(feed);
// WARNING THAT IT WASN'T DONE
}
}
file_that_does_the_work.php
<?
include("config.php"); // your thing that configures the connection
$postcode = sanitizationfunction($_POST["postcode"]);
$email = sanitizationfunction($_POST["email"]);
$query = $connection->prepare('INSERT INTO visitors(postcode,email) VALUES(?,?)');
$query->bindParam(1, $postcode);
$query->bindParam(2, $email);
if ($query->execute()) {
echo "true";
} else {
echo "false";
}
?>
form.php
<table width="100" style="background-color: #ffffff">
<tr><td align="right">login</td>
<td><input style="width: 80px" name="username" type="text" value="<?php echo $username?>"/>
</tr>
<tr><td align="right">password</td>
<td><input style="width: 80px" name="password" type="password"/></td>
</tr>
<tr><td align="right">Postcode</td>
<td><input style="width: 80px" name="postcode" type="text" /></td>
</tr>
<tr><td align="right">Email</td>
<td><input style="width: 80px" name="email" type="text" /></td>
</tr>
<td><input type="submit" value="OK" /></td>
</tr>
</table>
</form>
`
somethingelse.php
<?php
foreach ($_POST as $key => $value) {
echo $key."=".$value."<br/>";
}
?>
I leave connectivity part to you :D
So, as others have pointed out, you are mixing up your client-side code and your server-side code. You need to send all the form data to a php file. The jquery ajax will send the data over to the script, and determine if this call was successful or not. If the call is not successful, you can run test logic. If it is, than you can do other logic, such as alert the user of a successful form submit.
Below is an example of the process:
ajax:
<script>
var formData = 'some data' // Get your form values and save here - postcode and email
$("button").click(function(){
$.ajax ({
method: 'POST',// you can do either post or get...
url: "page_to_handle_mysql_code.php",
data: formData
success: function( response ) {
//do something like alert("Submitted Successfully!");
}
fail: function( response) {
//Do testing such as console.log(response); NOTE: Response will be what ever your php page sends back.
}
});
)};
</script>
On your php page: page_to_handle_mysql_code.php
<?php
if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {
$postcode = $_POST['postcode'];
$email = $_POST['email'];
//connect to mysql - I prefer prepared statements as the variables are prepared for safety when sent to MySQL
$conn = new mysqli($servername, $username, $password, $dbname);//you can either put the actually values in, or I include another php page in this one that sets my variables so I can resuse my code easily.
if ($conn->connect_errno) {
echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(?,?)"))) {
echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
}
//NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.
if (!$sql->bind_param("ss", $postcode, $email)) {
echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
}
if (!$sql->execute()) {
echo "Execute failed: (" . $sql->errno . ") " . $sql->error;
}
} else {
echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.
}
?>
This should help you get your values entered to MySQL. I hope it helps!
You can submit a form with jquery
mysqli_query is a function in your PHP, your javascript doesn't have access to the function. You have to make an http call from your javascript, which your PHP will receive and run mysqli_query on its end
I created dynamic textboxes, the other one has a type of file. My problem is
that I don't know how to save the image in the database and have a copy of it inside a folder cause I'm gonna retrieve it later on. But since it's in an array form I don't have an idea how to do it. I used blob for it, but if you have better way , lets see. I know how to make a copy of inside a folder but I didn't use a foreach, this I don't know.
Here's the code:
<script type="text/javascript">
$(document).ready(function () {
$("#append").click(function (e) {
e.preventDefault();
var textboxes = $(".textbox").length;
$(".inc").append("<div class='controls'><input class='textbox form-control' type='file' name='textbox[]'><input class='textbox form-control' type='text' name='box[]' ><input class='textbox form-control' type='text' name='box1[]' ><input class='textbox form-control' type='text' name='box2[]' ><a href='#' class='remove_this btn btn-danger'>remove</a> </div>");
});
$(document).on('click', '.remove_this', function (e) {
e.preventDefault();
$(this).parent().remove();
});
});
</script>
HTML:
<form class="form-horizontal" method= "POST">
<div class="control-group">
<div class="inc">
<div class="controls">
<button style="margin-left: 50px" class="btn btn-info" type="submit" id="append" name="append">
Add Textbox</button>
<br>
<br>
</div>
</div>
<input type="submit" class="btn btn-info" name="submit" value="submit"/>
</div>
PHP:
<?php
$host = "localhost";
$dbname = "lala";
$user = "root";
$pass = "";
$conn = new PDO("mysql:host=$host; dbname=$dbname", $user, $pass);
if (isset($_POST['submit'])) {
$textboxes = $_POST['textbox'];
$textboxes1 = $_POST['box1'];
$textboxes2 = $_POST['box2'];
$boxes = $_POST['box'];
$textboxes=addslashes(file_get_contents($_FILES['textboxes']['tmp_name']));
$image_name1=addslashes($_FILES['textboxes']['name']);
$image_size1=getimagesize($_FILES['textboxes']['tmp_name']);
move_uploaded_file($_FILES['textboxes']['tmp_name'],"images/".$_FILES['textboxes']['name']);
$location1="images/".$_FILES['textboxes']['name'];
foreach ($location1 as $key => $textbox ) {
$box=$textboxes[$key];
$box1=$textboxes1[$key];
$box2=$textboxes2[$key];
$sql = "INSERT into sasa (sasa,sasa1,sasa2,sasa3) values('$textbox','$box','$box1','$box2')";
echo $sql . "<br>";
$q = $conn->query($sql);
}
}
?>
I have a div at index.php which i want to refresh as the ajax call succeeds. I tried this. But it is not refreshing the div unless i refresh the whole page.
here is the code.
Div
<div id="cartContainer">
<div id="cart">
<li style="color: #515151">
<img id="cart_img" src="images/cart.png"> Cart <span class='badge' id='comparison-count'>
<?php
if(isset($_SESSION['cart'])&& !empty($_SESSION['cart']))
{
$cart_count=count($_SESSION['cart']);
echo $cart_count;
} else {
$cart_count=0;
echo $cart_count;
}
?>
</span>
</li>
<div id="sidebar">
<?php if(isset($_SESSION[ 'cart'])&& !empty($_SESSION[ 'cart'])){ ?>
<table id="s_table">
<?php foreach($_SESSION[ 'cart'] as $id=> $value){ ?>
<form class="product" method="get" action="index.php?">
<tr id="tr_s">
<input type="hidden" name="action" value="remove">
<input type="hidden" name="id" value="<?php echo $value['id'] ?>">
<td class="s_th">
<?php echo $value[ 'name']; ?>
<input type="hidden" name="name" value="<?php echo $value['name'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'quantity'] ?>
<input type="hidden" name="quantity" value="<?php echo $value['quantity'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'color']; ?>
<input type="hidden" name="color" value="<?php echo $value['color'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'size'] ?>
<input type="hidden" name="size" value="<?php echo $value['size'] ?>">
</td>
<td>
<button type="submit" id="btn_submit">Remove</button>
</td>
</tr>
</form>
<?php } ?>
<tr>
<td class="cart_btn" colspan="2">GO TO CART
</td>
<td class="cart_btn" colspan="2">CHECK OUT
</td>
</tr>
</table>
<?php } else { ?>
<p id="p_s"><i> "Your Cart is Empty"</i>
</p>
<?php } ?>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function() {
$('#addtocart').click(function(e) {
e.preventDefault();
var page = $("#page").val(),
action = $("#action").val(),
name = $("#name").val(),
id = $("#id").val(),
color = $("#color").val(),
size = $("#size").val(),
cat_id = $("#cat_id").val(),
s_cat_id = $("#s_cat_id").val(),
category = $("#category").val();
var proceed = true;
if (proceed) {
post_data = {
'Page': page,
'Action': action,
'Name': name,
'Cat_id': cat_id,
'S_cat_id': s_cat_id,
'Category': category,
'Id': id,
'Color': color,
'Size': size
};
$.post('add_cart.php', post_data, function(response) {
//load json data from server and output message
if (response.type == 'error') {
//output=$('.alert-error').html(response.text);
} else {
output = $("#cartContainer").load();
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
If you want to update the div with the return from you AJAX you would do something like this:
$.post('add_cart.php', post_data, function(response) {
$("#cartContainer").html(response);
}
Of course this depends on many things: the kind of data you're returning, what you wish to update, etc. It is hard to tell, from what you have posted, what your intent is.
I really don't have any idea with this problem. I create new plug-in. Structure is easy:
div FreeQuotation_wrap2 (display the table), div FreeQuotation_wrap3 (insert new data). But after write new data and click submit page is refresh with old data.
When I click refresh I see information that it will resend data to database. It's ok- I prevent it with unique. Now I see new table with new record. How can I make it automatically?
I try 3 methods: onSubmit="" (doesn't work) and javascript (window.location = "...") and trick with session (i get error - headers already sent by...).
<?php
global $FreeQuotation_version;
global $wpdb;
echo $table_name;
global $today_date;
$table_name = $wpdb->prefix . 'free_quotation_kic';
?>
<div class="FreeQuotation_wrap">
<h2><div class="FreeQuotation_header"></div> FreeQuotation <?php echo $FreeQuotation_version; ?></h2><br>
</div>
<div class="FreeQuotation_wrap2">
<table class="widefat">
<?php
$FreeQuotation_table = $wpdb->get_results(
"
SELECT *
FROM $table_name
ORDER BY adding_date DESC
LIMIT 0 , 10
"
);
//nagłówek
echo '<thead><tr><th> ID </th><th> Quotation </th><th> Author </th><th> Display Date </th><th> Delete </th></tr></thead>';
//treść
foreach ( $FreeQuotation_table as $ogresults )
{
echo '<tr><td>';
echo $ogresults->id;
echo '</td><td>';
echo $ogresults->quotation;
echo '</td><td>';
echo $ogresults->author;
echo '</td><td>';
echo $ogresults->display_date;
echo '</td></tr>';
}
echo '<tfoot><tr><th> ID </td><th> Quotation </td><th> Author </td><th> Display Date </th><th> Delete </td></tr></tfoot>';
?>
</table>
</div>
<div class= "FreeQuotation_wrap3">
<form method="post" action="options.php">
<?php settings_fields('FreeQuotation_settings_filed'); ?>
<?php $options = get_option('FreeQuotation_options'); ?>
</form>
<?php
global $current_user;
$ufUserID = $current_user->ID;
$quotation = $_POST["quotation_textarea"];
$author = $_POST["autor_text"];
$display_date = $_POST["display_date"];
$url = $_SERVER['PHP_SELF'];
$adding_date = $today_date;
echo $url;
if ( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == 'updateFeedback' ) {
$FreeQuotation = $wpdb->insert( 'wp_free_quotation_kic', array( 'quotation' => $quotation, 'author' => $author, 'display_date' => $display_date, 'adding_date' => $adding_date,) );
}?>
TUTAJ
<h3 class="widget-title">Add quotation</h3>
<form id='reloader' method='post' onSubmit="<?php echo $url;?>">
<table class="widefat" >
<thead>
<tr><th>Quotation</th><th>Author</th><th>Display Date</th></tr>
</thead>
<tbody>
<tr><td>
<textarea rows="1" cols="100" name="quotation_textarea" required></textarea>
</td>
<td>
<input type="text" name="autor_text" required></input>
</td>
<td>
<input type="text" name="display_date" required></input>
</td></th>
</tbody>
<tfoot>
<tr><th>
<input class="button button-primary" type="submit" name="submit" value="submit"/>
<?php wp_nonce_field( 'updateFeedback' ); ?>
<input name="action" type="hidden" id="action" value="updateFeedback"/>
</th></td>
</tfoot>
</table>
</form><br>
</div>
<div class="FreeQuotation_wrap4">
<h3>Zmiany:</h3>
</div>
<?php
?>
Can you help me? It's my first question hire (and I believe that the last...). Usually when I try to write a question I find the answer quickly :) Now I spend few hours with this problem and I doesn't see any solution...
I find simple solution - it's very easy and it's work. Maybe it's not professional but I don't have any other idea...
I change the order on the page. First is the form to add new position, the second is now the table with output. It means that I change two order:
<div class= "FreeQuotation_wrap3">
...
</div>
<div class="FreeQuotation_wrap2">
...
</div>
And this is my first answer on stackoverflow.com ;-)