Textbox not clears when clicks the submit button - javascript

I am trying to clear the txtSubTotal text box after clicking the PROCEED button. It's not working though I tried some code examples, even in SO.
btnProceed/HTML
<input type="submit" name="btnProceed" id="btnProceed" value="PROCEED" onclick="clearSubTotal();"/>
clearSubTotal()/JS
function clearSubTotal() {
$('#txtSubTotal').val('');
}
txtSubTotal
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="<?php
$sql=mysqli_query($connection,"select sum(amount) from sales_temp");
$row = mysqli_fetch_array($sql);
echo $row[0];
?>"/>
form/HTML
<form id="manageSalesForm" name="manageSalesForm" method="post" action="<?php echo BASE_URL?>includes/functions/sales_functions.php">
Appreciate your help on this.
NOTE: Found that on the second button press, the text box clears. How to set this correctly for the first button perss?
ADD button/JS
function submitdata() {
var listItemName = document.getElementById("listItemName").value;
var listStock = document.getElementById("listStock").value;
var txtUnitPrice = document.getElementById("txtUnitPrice").value;
var txtQuantity = document.getElementById("txtQuantity").value;
var listCustomer = document.getElementById("listCustomer").value;
var txtReceiptNo = document.getElementById("txtReceiptNo").value;
var TheDate = document.getElementById("TheDate").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = {listItemName:listItemName, listStock: listStock, txtUnitPrice: txtUnitPrice, txtQuantity: txtQuantity, listCustomer: listCustomer, txtReceiptNo: txtReceiptNo};
if (listItemName == '' || listStock == ''|| txtUnitPrice == ''|| txtQuantity == ''|| listCustomer == ''|| txtReceiptNo == ''|| TheDate == '') {
salesitemsAddFail();
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "/pms/includes/functions/sales_temp_functions.php",
data: dataString,
cache: false,
success: function(html) {
//reload the sales datagrid once add the item details to temporary table (sales_temp)
$('#list').trigger("reloadGrid",[{page:1}]);
window.location.reload();
}
});
}
}
$('#btnProceed').click(function(event) {
event.preventDefault(); // stops form submission
$('#txtSubTotal').val('');
});
ADD button/HTML
<td width="46"><button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
sales_functions.php
<?php
//Start the Session
if(!isset($_SESSION))
{
session_start();
}
include ("/../../pages/sales.php");
include("/../../dbutil.php");
if(isset($_POST['listCustomer'])){ $customer = $_POST['listCustomer'];}
if(isset($_POST['staff'])){ $user = $_POST['staff']; }
if(isset($_POST['btnProceed'])){
$result=mysqli_query($connection,
"INSERT INTO sales(cus_id,item_id,stock_id,receipt_no,qty,unit_price,amount,user_id,purchase_id)
SELECT C.cus_id, I.item_id, S.stock_id, $receipt_no, ST.qty, ST.unit_price, ST.amount, U.id, P.purchase_id
FROM customers C, items I, stock S, sales_temp ST, users U, purchase_items P
WHERE ST.staff='$user'
AND C.customer_name='$customer'
AND I.item_name=ST.item_name
AND S.stock_code=ST.stock_code
AND ST.purchase_id=P.purchase_id");
//Update available qty from purchase_items relevant only to the logged in user(sales_temp table may have records from multiple users)
$resultUpdate=mysqli_query($connection, "UPDATE purchase_items P INNER JOIN sales_temp ST ON (P.purchase_id = ST.purchase_id) SET P.avail_qty = (P.avail_qty - ST.qty) WHERE ST.staff='$user'");
//Delete records relevant only to current user. Here 'WHERE' clause use to prevent deleting other user's records.
$resultDelete=mysqli_query($connection, "DELETE FROM sales_temp WHERE staff='$user'");
if (!$result) {
printf("Errormessage: %s\n", mysqli_error($connection));
}
// use exec() because no results are returned
if ($result) {
}
else
{
echo '<script type="text/javascript">',
'salesAddFail();',
'</script>';
}}
?>

After clicking on the submit button, the form is being submitted and your custom function is not being executed.
Delete the onclick from your input element and edit your jQuery code:
$('#btnProceed').click(function(event) {
event.preventDefault(); // stops form submission
$('#txtSubTotal').val('');
});
You can try it in your browser: https://jsfiddle.net/hy7jwg8m/1/

It is working perfect for me. And after clicking on submit it might be working for you but with the same time page will be redirected to new action

I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);

Related

Two submit buttons with same action and one from them with added function/action for the same form

I have one form with two submit buttons.
<form id="manageSalesForm" name="manageSalesForm" method="post" action="<?php echo BASE_URL?>includes/functions/sales_functions.php">
PROCEED button should submit data to the database (This works)
<input type="submit" name="btnProceed" id="btnProceed" value="PROCEED" onclick="document.getElementById('txtSubTotal').value = '';"/>
PRINT & PROCEED button should submit data to the database and print the page (How to do this?)
<input type="submit" name="btnPrintReceipt" id="btnPrintReceipt" value="PRINT & PROCEED" formaction="<?php echo BASE_URL?>reports/salesreceipt2.php" formtarget="_blank"/>
salesreceipt2.php has the fpdf code and should open this in a new tab/window.
Same form has another button with button type
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); resetform();">ADD</button>
function submitdata() {
var listItemName = document.getElementById("listItemName").value;
var listStock = document.getElementById("listStock").value;
var txtUnitPrice = document.getElementById("txtUnitPrice").value;
var txtQuantity = document.getElementById("txtQuantity").value;
var listCustomer = document.getElementById("listCustomer").value;
var txtReceiptNo = document.getElementById("txtReceiptNo").value;
var TheDate = document.getElementById("TheDate").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = {listItemName:listItemName, listStock: listStock, txtUnitPrice: txtUnitPrice, txtQuantity: txtQuantity, listCustomer: listCustomer, txtReceiptNo: txtReceiptNo};
if (listItemName == '' || listStock == ''|| txtUnitPrice == ''|| txtQuantity == ''|| listCustomer == ''|| txtReceiptNo == ''|| TheDate == '') {
salesitemsAddFail();
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "/pms/includes/functions/sales_temp_functions.php",
data: dataString,
cache: false,
success: function(html) {
//reload the sales datagrid once add the item details to temporary table (sales_temp)
$('#list').trigger("reloadGrid",[{page:1}]);
//window.location.reload();
//refresh/update the sub total value when adding
$("#sub_total_div").load(location.href + " #sub_total_div");
}
});
}
}
I tried several ways, but I couldn't make this work. Appreciate your help.
First of all change all of your submits to button. Like this :
<input type="button" value="Proceed" onclick="proceed(false)" />
<input type="button" value="Proceed & Print" onclick="proceed(true)" />
Now add this Javascript :
function print(recordId){
window.open( 'baseurl/salesreceipt2.php?id='+recordId , '_blank');
}
function proceed(printIt){
// your ajax operations..
$.ajax({
//your ajax configs..
success:function(response){
//your ajax success things..
if(printIt == true){
print(response.lastId); // Pass last Id of record to print function if your salesreceipt2.php always prints last record that's unnecessary.
}
}
});
}
It works easy. If printIt ( your first parameter ) is true it calls print with LastRecordId ( if your salesreceipt2.php always prints last record passing it is unnecessary as i said. ) if not you should return a JSON Response that contains inserted ID. So this inserted id will be passed to salesreceipt2.php file by ?id

AJAX data, understanding as to what this actually does

I found some old code which I am trying to understand and unfortunately I did not leave comments which leads to my difficulties. Even with the jQuery documentation, I can't wrap my head around it; I really have looked, but I still don't understand. This program is basically a chat where you type your name and your message and click submit. Then it displays your message in a chat box similar to Facebook. Here is the working code:
My JS
$(document).ready(function() {
$('#submit').on('click', function() {
var name = $('#name').val();
var shout = $('#shout').val();
var outText = 'name=' + name + '&shout=' + shout;
if (name == '' || shout == '') {
alert("Please fill in your name and shout");
} else {
$.ajax({
type: "POST",
url: "database.php",
data: outText,
cache: false,
success: function(html) {
$('#shouts ul').prepend(html);
}
});
}
return false;
});
});
and my PHP
<?php
$connection = mysqli_connect('localhost','root','','muntasirshoutbox');
if(isset($_POST['name']) && isset($_POST['shout']))
{
$name = mysqli_real_escape_string($connection,$_POST['name']);
$shout = mysqli_real_escape_string($connection,$_POST['shout']);
$query = "INSERT INTO shouts(name,shout) ";
$query.= "VALUES ('$name','$shout')";
$result = mysqli_query($connection,$query);
if(!$result)
{
echo "doesent work".mysqli_error($connection);
}
else
{
echo '<li>'.$name.': '.$shout.'</li>';
}
}
?>
So I am confused as to what outText is actuallly doing, the reason I am confused is because, I was under the impression that my PHP was printing the text inside the chat box when I do this echo '<li>'.$name.': '.$shout.'</li>';, but after experimenting with outText, I noticed that if I change some stuff with outText the message I type in wont appear at all in the chat box, or it will appear with whatever string I added to it. What exactly is this doing?!

Button to go through array one value at a time without page refresh

I have a function that generates 10 random and unique numbers between 1-20.
function contain($prevItems, $number) {
for ($k=0; $k<sizeof($prevItems); $k++) {
if ($prevItems[$k] == $number)
return true;
}
return false;
}
$num[0] = rand(1,20);
$prevItems[0] = $num[0];
for ($i=1; $i<=10; $i++) {
$num[$i] = rand(1,10);
while (contain($prevItems, $num[$i])) {
$num[$i] = rand (1,20);
}
$prevItems[$i] = $num[$i];
}
sort($num);
I then have a button that fetches the first number from the array and echoes a text from database based on the number.
<form action="koe.php" method="POST">
<input id="myform" type="submit" class="btn btn-primary" name="submit" value="new question">
</form
if(isset($_POST['submit'])) {
if($result = $my->query("SELECT * FROM questions ORDER BY OID DESC LIMIT 1")) {
if($result = $my->query('SELECT * FROM questions WHERE OID="'.$prevItems[0].'"')) {
while($t = $result->fetch_object()) {
echo '<h2>'.$t->text.'</h2>';
}
}
}
}
My problem is this: I want the button to echo the next value from the previously. Like I want to echo prevItems[1] and then prevItems[2] without the page refresh because at the moment every time I press the button, the page refreshes and the function makes new 10 numbers so they're not unique anymore.
I've tried to stop page refresh with javascript
var frm = $('#myform');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('ok');
}
});
ev.preventDefault();
});
I figured it can't work like this though but I'm not sure how to fix it.
To clarify: My problem is to go through array on a button click without page refresh. Everytime a button is pressed, the next number from array would show up. array[0] -> array[1] -> array[2] -> array[3]
I would change your php page to expect a post variable "num"
if(isset($_POST['num'])) {
if($result = $my->query("SELECT * FROM questions ORDER BY OID DESC LIMIT 1")) {
if($result = $my->query('SELECT * FROM questions WHERE OID="'.$_POST['num'].'"')) {
while($t = $result->fetch_object()) {
echo '<h2>'.$t->text.'</h2>';
}
}
}
}
//you probably want to google "mysql prevent injection" right after you get this working
Then in your ajax call you can pass in the "num"
$(function(){
$("mybutton").on("click", function() {
$.ajax({
type: "POST",
url: "myURL",
data: { num:myNums[0] },
success: function (data) {
$("#output").innerHTML += data;
myNums.splice(0,1); //take out the first num
}
});
});
});

How to use jQuery AJAX with PHP to submit a form into a mySQL database with using an <a> tag?

What I am trying to do is create a "save" button for my website which saves specific posts and comments, exactly like the "save" button on Reddit. For now I am trying to self teach jQuery AJAX and attempting to figure out how to submit data to the database without having to reload the whole page. What I am attempting to do here is save a string by submitting it to a table called "Saved" when I click on "save".
HTML
<div id="message1">
<div id="pmessage"><p><?php echo $myComment;?></p></div>
Save
Edit
Hide
</div>
<form action="ajaxexample.php" method="post" style="display: none" id="1234">
<input type="hidden" name="message" id="message" value="<?php echo $myComment; ?>">
</form>
jQuery
$('a.Save').click(function () {
if ($(this).text() == "Save") {
$("#1234").ajax({ url: 'ajaxexample.php', type: 'post', data: 'message' });
$("a.Save").text("Unsave");
} else {
$("a.Save").text("Save");
}
});
PHP5.3
$message = $_POST['message'];
$query = "INSERT INTO saved (comment) VALUES (?)";
$statement = $databaseConnection->prepare($query);
$statement->bind_param('s', $message);
$statement->execute();
$statement->store_result();
$submissionWasSuccessful = $statement->affected_rows == 1 ? true : false;
if ($submissionWasSuccessful)
{
header ("Location: index.php");
}
$myComment = "This is my message!";
As of now all I am trying to do is submit the message "This is my message!" into the database table "Saved". What is wrong with my code? Why can I not submit the data to the table and how can I fix it? Thanks in advance!
Submit form when someone clicks on a.Save
$('a.Save').click(function (e) {
e.preventDefault();
$("#1234").submit();
});
submit handler on form#1234
$("#1234").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'ajaxexample.php',
data: $("#1234").serialize(),
success: function(data)
{
// data stores the response from ajaxexample.php
// Change the html of save by using $("a.Save").html("Unsave");
}
});
});
Serialize automatically makes a query string.
$(".save").bind("click",function(e){e.preventDefault();
$.ajax({
url : $("#1234").attr("action"),
type : "POST",
data : $("#1234").serialize(),
success : function(data){},
fail : function(data){},
});
});

How to save to create table in DB

I have over the last week managed to setup a page which on click of a check box saves its data to a database directly my only issue now is how to save the new values to the right column in the database.
I have 3 checkboxes with different values and names that are posted through ajax to the other page. I'm unsure of how to proceed with this.
Here is a snippet of my code:
<script type="text/javascript">
$(function() {
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('id') : $this.attr("value");
var userid = $this.attr('name');
$.ajax({
type: "GET",
url: 'request.php?uname=' + checkVal +'&id=' + userid,
success: function(data) {
//Success
if(data == 1){
alert('Data was saved in db!');
}
//Failure
if(data == 0){
alert('Data was NOT saved in db!');
}
}
});
});
});
The Html
<form id="frm" name="frm">
<td><input name="29" type="checkbox" id="Paid" value="Waiting on Payment" checked="checked" /></td>
<td><input name="30" type="checkbox" id="Repaired" value="Waiting on Repairs" /></td>
<td><input name="31" type="checkbox" id="With Student" value="Awaiting Pickup" /></td>
</form>
Here's the database structure as well:
name: test
Paid
repair
Returned
What I am finding myself unable to do is how to tell the Mysql query which column to save the new value in because the GET function is only pulling in the value on the other page and I can't get it to separate them so that the paid check will only save in the paid column and so on..
Here is the request page so that page that gets the value:
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
// error happened
print(0);
}
mysql_select_db('test');
// sanitize the value
$value = mysql_real_escape_string($_GET['uname']);
$id = mysql_real_escape_string($_GET['id']);
// start the query
$sql = "INSERT INTO `test` VALUES ( NULL, 2, 3, '$value')";
// check if the query was executed
if(mysql_query($sql, $link)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
What you need, is to define the columns in your INSERT, like this:
INSERT INTO `test` (col1, col2, col3, ...) VALUES ( NULL, 2, 3, '$value')
Where 'col1', 'col2', etc are your columns. That way you can define the columns you need. In VALUES() you'll only put the values for the previously defined columns. For example:
INSERT INTO `person` (name) VALUES ('tom')

Categories