html form, submit and stay at same place on page - javascript

I have a long form for our learners to complete. When they click the Save Progress button to submit their work so far, the page automatically jumps back to the top and they have to scroll down to find their last answer submitted.
I'd like them to be able to save their progress at any point and stay at that point on the page.
I've tried the following, the alert appears and the page stays still but the learners work isn't saved.
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$('#form1').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'Ext1SUp.php',
data: $('#form1').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
</script>
Form action:
<form action= "Ext1SUp.php" method="post" id="form1">
Save Progress button:
<button type="Submit" name="Save" class="save-progress" form="form1" value="Submit" >Save Progress</button>
PHP:
<?php
require_once 'login.php';
$connection = new mysqli($hn, $un, $pw, $db);
if ($connection -> connect_error) {
echo "Failed to connect to MySQL: " . $connection -> connect_error;
}
if(isset($_POST['Submit'])) {
$sql = "UPDATE unit1 SET
U1Q1 = '{$_POST['U1Q1']}'
,U1Q2 = '{$_POST['U1Q2']}'
,U1Q3 = '{$_POST['U1Q3']}'
,U1Q4 = '{$_POST['U1Q4']}'
,U1Q5 = '{$_POST['U1Q5']}'
,U1Q6 = '{$_POST['U1Q6']}'
,U1Q7 = '{$_POST['U1Q7']}'
,U1Q8 = '{$_POST['U1Q8']}'
,U1Q9a = '{$_POST['U1Q9a']}',U1Q9b = '{$_POST['U1Q9b']}',U1Q9c = '{$_POST['U1Q9c']}',U1Q9d = '{$_POST['U1Q9d']}'
,U1Q10 = '{$_POST['U1Q10']}'
,U1Q11a = '{$_POST['U1Q11a']}',U1Q11b = '{$_POST['U1Q11b']}',U1Q11c = '{$_POST['U1Q11c']}',U1Q11d = '{$_POST['U1Q11d']}'
,U1Q12 = '{$_POST['U1Q12']}'
,U1Q13 = '{$_POST['U1Q13']}'
,U1Q14 = '{$_POST['U1Q14']}'
,U1Q15a = '{$_POST['U1Q15a']}',U1Q15b = '{$_POST['U1Q15b']}',U1Q15c = '{$_POST['U1Q15c']}',U1Q15d = '{$_POST['U1Q15d']}',U1Q15e = '{$_POST['U1Q15e']}'
,U1Q16a = '{$_POST['U1Q16a']}',U1Q16b = '{$_POST['U1Q16b']}',U1Q16c = '{$_POST['U1Q16c']}',U1Q16d = '{$_POST['U1Q16d']}'
,U1Q17 = '{$_POST['U1Q17']}'
,U1Q18a = '{$_POST['U1Q18a']}',U1Q18b = '{$_POST['U1Q18b']}',U1Q18c = '{$_POST['U1Q18c']}'
,U1Q19 = '{$_POST['U1Q19']}'
,U1Q20a = '{$_POST['U1Q20a']}',U1Q20b = '{$_POST['U1Q20b']}',U1Q20c = '{$_POST['U1Q20c']}',U1Q20d = '{$_POST['U1Q20d']}'
,U1Q21 = '{$_POST['U1Q21']}'
,U1Q22 = '{$_POST['U1Q22']}'
,U1Q23 = '{$_POST['U1Q23']}'
,U1Q24a = '{$_POST['U1Q24a']}',U1Q24b = '{$_POST['U1Q24b']}',U1Q24c = '{$_POST['U1Q24c']}'
,U1Q25 = '{$_POST['U1Q25']}'
,U1Q26 = '{$_POST['U1Q26']}'
,U1Q27 = '{$_POST['U1Q27']}'
WHERE id = '{$_POST['id']}'";
$result = mysqli_query($connection, $sql);
}
header('Location: Ext1S.php');
?>
The process works fine, it only stops saving after adding the script to prevent the page from scrolling.
I hope someone can offer me some advice,
Thank you
Lisa

Change button type to "button" instead of "submit" to prevent executing form. You are storing data using ajax so it's not needed to submitting form using button.

Button Type should be a "button". Remove "form" attribute from button, and change your $().on('submit') to for ex. function submitForm () {}. Then as the button attribute add onclick="submitForm()". And you can remove your preventDefault(); and action attribute from form, because you sending data by Ajax, not with a classic form. Classic forms has to refresh page after submit, but with ajax you even don't need to submit anything. Just send async request in separated function. Something like this:
function submitForm(){
$.ajax({
type: 'post',
url: 'Ext1SUp.php',
data: $('#form1').serialize(),
success: function () {
alert('form was submitted');
}
});
}
<form id="form1">
<!-- Yours form -->
<button type="button" onclick="submitForm();">Submit</button>
</form>
OH! And I almost forget. You have to remove yours if(isset($_POST['Submit'])) {} from PHP in this case. And stop using mysqli for connection :) try out PDO

Related

AJAX data and text box data not storing together

I am using Ajax to send information about the screenwidth to a PHP page and I am also wanting the user to type a value into a text box however this is currently not working as only the textbox value is passed and I am told that the other value is an undefined index. Any help would be appreciated.
HTML/JS page
<form method="post" action = "insert.php">
<input type = "text" name ="carName" id ="carName"/>
<div id ="screenWidth" name = "screenWidth" method="post"></div>
<input type="submit" id= "submit" name="submit" value="submit"/>
<script type="text/javascript">
var screenWidth = screen.width + "px";
document.getElementById("screenWidth").innerHTML = screenWidth;
console.log(screenWidth)
var TestVal = ("test");
$.ajax({
type: 'POST',
url: 'insert.php',
data: {'screenWidth': screenWidth},
success: function(data){
console.log(data);
}
});
PHP Page
<?php
include 'db.php';
$screenWidth = $_POST['screenWidth'];
$screenHeight = $_POST['screenHeight'];
if(isset($_POST['submit']))
{
$screenWidth = $_POST['screenWidth'];
$phoneType = $_POST['carName'];
echo 'hello';
$sql = "INSERT INTO deviceInfo (screenWidth, carType, )
VALUES ('$screenWidth','$carType',)";
if (sqlsrv_query($conn, $sql)) {
echo "New record has been added successfully !";
} else {
echo "Error: " . $sql . ":-" . sqlsrv_errors($conn);
}
sqlsrv_close($conn);
}
?>
There are several issues with your setup.
1) only form inputs are submitted with the form. When you click the submit button, the form will submit through a browser HTML post and your JS will not be run. The form submit will only submit the carName variable in the post data as the screenWidth is not in a form input.
2) the JS you have written will only submit the screenWidth over ajax - and that will run as soon as the page is loaded (assuming this is only an extract and that this JS is in side a jQuery(document).ready(function($){ }) block.
3) your carName becomes carType and then phoneName in your code, so $carType is not set when you insert your SQL.
You have 2 options here..
1) change you div containing the screenWidth to a text input that is readonly. This way you can populate your screenWidth on page load and then have the user submit the form over HTML post when they are finished updating the carName. This will not use AJAX, or
2) get rid of the form and create a "click" function for submitting your AJAX that includes both vars... something like this (not tested).
jQuery(document).ready(function($){
$("#submit").click(function(){
e.preventDefault(); // stop the button from posting
$.ajax({
type: 'POST',
url: 'insert.php',
data: {'screenWidth': $("#screenWidth").text(),
'carName': $("#carName").val()},
success: function(data){
console.log(data);
}
});
});
});

Trying to activate PHP function using button click with AJAX

I am trying to call a PHP script/file that will read data off of an HTML table. I want to press a button so that the PHP script/file will activate and read the data off of the HTML table into a database using MySQL.
My AJAX script is not activating the PHP file.
The HTML button code:
<button type="submit" class="btn btn-md btn-primary btn-block" id="save">Save Workout</button>
The AJAX code:
$(document).ready(function(){
$("#save").click(function(){
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
}
});
});
});
The incomplete PHP code (does not contain DB code) - based off of https://brennanhm.ca/knowledgebase/2015/11/import-html-table-into-mysql-table/
<?php
require_once ('simple_html_dom.php');
$table = file_get_html('addWorkout.php');
$db = mysqli_connect('localhost', 'root', '', 'workoutLogger');
foreach($table ->find('tr') as $tr) {
$exercise = $tr->find('td', 0)->plaintext;
$weight = $tr->find('td', 1)->plaintext;
$sets = $tr->find('td', 2)->plaintext;
$reps = $tr->find('td', 3)->plaintext;
$exercise_c = mysqli_real_escape_string($db, $exercise);
$weight_c = mysqli_real_escape_string($db, $weight);
$sets_c = mysqli_real_escape_string($db, $sets);
$reps_c = mysqli_real_escape_string($db, $reps);
}
?>
I can't get a success message to pop up.
What I ended up doing was keeping the and wrapping the button around a form with the action "addWorkoutTEST.php", that did it perfectly.
<form action="addWorkoutTEST.php">
<button type="submit" class="btn btn-md btn-primary btn-block" name="save">Save Workout</button>
</form>
To prevent the default Form Submit action you just need to add in the event.preventDefault();
Something like this...
$(document).ready(function(){
$("#save").click(function(event){ // must include event here to match the object in the next line. It can be called anything.
event.preventDefault(); // Prevent Default Submit
$.ajax({
type: 'POST',
url: 'addWorkoutTEST.php',
success: function() {
alert("hello");
},
error: function (request, status, error) {
alert("ERROR: " + request.responseText);
}
});
});
});
If javascript is disabled for whatever reason, you need to decide what action to take. With what you have so far in your answer to your form with the added action, that would be the fallback in such a case. It's something you need to think out and decide upon.

Disable submit button when javascript triggered

I have this form:
<form action = "" method = "post">
<input type = "text" name = "tbox_phone" placeholder = "phone" onkeyup="checker_phone(this.value)">
<div id = "msg"></div>
<input type = "submit" name = "button_submit" value = "submit">
</form>
The checker_phone is connected to a JavaScript that runs through another PHP page.
The script:
<script>
function checker_phone(val)
{
$.ajax ({
type:"POST",
url:"check_phone.php",
data:'phone='+val,
success: function(data){
$("#msg").html(data);
}
});
}
</script>
The PHP page:
$phone = htmlentities($_POST['tbox_phone']);
$var_phone= mysqli_real_escape_string($connect,$phone);
$search= "SELECT * FROM users WHERE phone= '$var_phone' ";
$exec= mysqli_query($connect,$search);
$count = mysqli_num_rows($exec);
if($count==1) {
echo "that phone number is already registered";
}
The above code worked. Now I want to disable the submit button whenever the result from the php's count returns 1. Is there any way I could this?
Javascript is good, but I prefer simple ones, rather than long and complicated scripts.
Fist I'd suggest avoiding inline JS in this case just for better code maintenance
second give your field and button some identifiers
<form action = "" method = "post">
<input id="userPhone" type = "text" name = "tbox_phone" placeholder = "phone">
<div id = "msg"></div>
<input id="submitAction" type = "submit" name = "button_submit" value = "submit">
</form>
Keep the JS code separate for reasons mentions above.
<script>
$( document ).ready(function() {
// Event handler
$('body').on("keyup", '#userPhone', function () {
$('#submitAction').removeAttr('disabled'); // user is typing, reactivate the submit button
checker_phone($('#userPhone').val());
});
// Ajax handler
function checker_phone(val)
{
$.ajax ({
type:"POST",
url:"check_phone.php",
cache: false,
data:{'phone':val}, // do not include parts of sql query in your JS!!!
success: function(data){
if(data.msg){
$("#msg").html(data.msg);
}
if(!data.phoneIsUnique){
$('#submitAction').attr('disabled','disabled');
}
}
});
}
});
</script>
PHP Code
// connecting to db
$mysqli = new mysqli(
$connectionData['DB_HOST'], // some array containing connection info
$connectionData['DB_USER'],
$connectionData['DB_PASSWORD'],
$connectionData['DB_NAME']
);
$mysqli->set_charset('utf8');
$resultData = ['msg'=>'','phoneIsUnique'=>true];
// parsing request
$phone = isset($_REQUEST['phone']) ? $_REQUEST['phone'] : '';
// avoid using 'SELECT *' to avoid unnecessary overhead
$stmt = $mysqli->prepare("SELECT `phone` FROM users WHERE phone=?");
$stmt->bind_param($phone); // never ever trust client input !!! so using bind.
$stmt->execute();
if($stmt->num_rows){
$resultData = [
'msg'=>'that phone number is already registered',
'phoneIsUnique'=>false
];
}
// using Json to bounce data back to client
echo json_encode($resultData);

Is it posiible to use onClick function on my form submit button?

I store multiple data in a table for enquiry basis.. which is successfully stored in my table. but now i also want to store those same data in Booking basis.
So i used onClick function for storing enquiry data. and now i want to store booking data in table from form submit button.
here is my form submit button code:
<button type="submit" class="booking-btn" onclick="btn_booking_hour();" id="btn_booking_hour">Book Now</button>
Here is my form action:
<?php echo form_open('booking/'.$product->id); ?>
And here my function:
function btn_booking_hour()
{
var date = $('#datehour').val();
var renter_id = $("#ownerid").val();
var guests_quantity = $('#no_of_guests').val();
var property_id = $('#property_id').val();
var selectedIds="";
var selectedObject = document.getElementsByClassName('hour_slots_available slot_activated');
for(var i=0;i<selectedObject.length;i++)
selectedIds+=selectedObject[i].id+",";
if(selectedIds == ""){
alert("Please select Hour-Slot(s) before Booking");
}
else{
$.ajax({
type: 'POST',
dataType:'json',
url:baseURL+'site/rentals/ajaxhourshow',
data:{'selectedHours':selectedIds,'property_id':property_id,'date':date,'guests_quantity':guests_quantity,'renter_id':renter_id},
success: function(responce){
var myJSON = JSON.stringify(responce);
var packet = $.parseJSON(myJSON);
var prd_id=packet.property_id;
var hour_slots=packet.hour_slots;
window.location.href = baseURL+'booking/'+prd_id;
}
});
}
}
Please suggest me how can i submit a form with data within their onClick function. Thanks..
Not sure if you are using a form, if you are using it you can can use onsubmit handler and return the action. In that case you wont need onclick handler in the button
<form onsubmit = "return btn_booking_hour()">
// Rest of code
</form>
You can also do like this
$('#form').on('submit',function(e){
e.preventDefault();
// rest of the code
})
you can use this code
function btn_booking_hour(){
// your other code
document.getElementById('formid').submit();
// formid = form id
}
or also use jquery
function btn_booking_hour(){
// your other code
$('#formid').submit();
// formid = form id
}
i got your point so you can also use it
$(function() {
//hang on event of form with id=myform
$("#myform").submit(function(e) {
//prevent Default functionality
e.preventDefault();
rest of your code
});
});

Textbox not clears when clicks the submit button

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

Categories