Disable submit button when javascript triggered - javascript

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

Related

Passing the data for ajax validation before submitting the form

This is my first question here so apologies for any logic errors, etc. I'm working on budget manager webapp, allowing the user to save his incomes and expenses data. Here specifically is an area for the user to create a custom category for either of those two. I'm trying to validate input data before submitting it, using ajax and php, the function is not working however. My aim was to check whether the category already exists in database. Please find my code below:
options.html
<div class="row gap-2 mt-3 mx-3" id="addCategory">
<button class="btn btn-success" onclick="addCategoryHandler('income')"
id="addIncomeCategory">Add new category</button>
</div>
<form id="editForm" action="javascript:addCategory()">
<label id="cattegoryNameLabel" for="categoryName">Category Name</label>
<input class="form-control inputBox errorCategory" type="text" id="categoryName" name="categoryName" aria-label="Nazwa kategorii"
aria-describedby="cattegoryNameLabel">
</form>
jquery validation:
$(document).ready(function() {
$('#editForm').validate({
rules: {
categoryName: {
required: true,
minlength: 3,
maxlength: 20,
categoryRegex: true,
remote: '/settings/validate-category'
},
},
});
After pressing the button the code is being handled via Javascript and then an according modal is being displayed:
settings.js
function addCategoryHandler(newCategoryType) {
categoryType = newCategoryType;
//Set proper modal title
$('#editModalLabel').text(addCategoryModalTitle);
//Reset category name & limit input
$('#categoryName').val('');
$('#limit').val(parseFloat(0).toFixed(2));
$('#limitCheck').prop( "checked", false );
//Set proper button function
$('#editForm').attr('action', "javascript:addCategory()");
switchLimitForm();
$('#editModal').modal('show');
}
function addCategory() {
categoryName = $('#categoryName').val();
categoryLimit = $('#limit').val();
categoryLimitState = $('#limitCheck').is(':checked');
$.ajax({
type: 'POST',
url: '/settings/addCategory',
dataType: 'json',
data: {
postCategoryType: categoryType,
postCategoryName: categoryName,
postCategoryLimitState: categoryLimitState,
postCategoryLimit: categoryLimit
},
success: function(result) {
addCategoryRow(categoryName, result);
},
error: function(xhr){
console.log(xhr);
}
});
}
The data is later passed to the controller, Settings.php:
public function validateCategoryAction()
{
$isEqual = ! $this->validateNewIncomeCategory($_GET['categoryName'], $_GET['ignore_id'] ?? null);
header('Content-Type: application/json');
echo json_encode($isEqual);
}
public function validateNewIncomeCategoryAction($name, $ignore_id = null)
{
$categories = Finance::getUserIncomeCategories();
$name = 'Inne';
if($categories)
{
$isEqual = true;
foreach ($categories as $category)
{
if (strtolower($category['name']) == strtolower($name)) {
$isEqual = false;
}
}
return $isEqual;
}
}
Database is being checked in the model, Finance.php:
public static function getUserIncomeCategories()
{
$db = static::getDB();
$query = $db->prepare('SELECT id, name FROM incomes_category_assigned_to_users WHERE user_id = :user_id');
$query->bindValue(':user_id', $_SESSION['user_id'], PDO::PARAM_INT);
$query->execute();
return $query->fetchAll();
}
My biggest concern for now is that the categoryName is not being passed to the Controller (as the form has not been submitted yet). The validation process on server side is fine but I want to set it for client's side as well. I was thinking about passing the data using Cookies, I do not know how to do it properly however. Also, sorry for such a long post, there are just lots of things going on here and it's been bugging me for a while. I'd appreciate any help.

html form, submit and stay at same place on page

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

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

jQuery / ajax data container + organization

My dad and I are working on a project where we'd like to create a script that calls in data when a number is submitted into a form. For example, when you type in your ID number then press ENTER or SUBMIT, the form will print/display information. This is a project for school, so when a student submits their ID number it will read their first period class, for example.
I have the following script code to set up the form:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
My question is, what would be the best way to organize the data? An array, HTML, etc.? There are quite a lot of ID numbers and are currently set up in an HTML table, but that doesn't seem to work in calling the information. And I'd like for the data to be specific. So when a specific ID number is typed in, it reads a specific answer. Right now my problem is when I type in a number it reads several classes.
If there are any suggestions/advice/other posts that could help me, I'd be grateful. I have solid HTML, CSS experience but I'm still learning JS and jQuery so this is a little new for me. Thanks!
Edit, Updated
Note, added value attribute to input type="text" element
<input type="text" name="studentNo" value="" />
substituted .submit() for .on("click") at input type="submit" element
Two possible approaches could be 1) using HTML to store data, .load() to retrieve fragment identifier within html file; or 2) storing data using JSON, retrieving file using php
html at firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}

Add a record to the database without refreshing

I want to add a record dynamically.
When I insert action = "add.php" for my form, the addition is accomplished by displaying a message after refreshing.
I want to add this addition without refreshing dynamically.
Also, for the ID of my games, I want that when I delete a record, for the ID to be decremented or removed. So that, when I add a game again, it uses the next ID available, not keeps on incrementing, like it is happeneing with me now.
If I take off add.php from action, nothing happens and the game isn't added.
My question is, where is this script broken? Or if add.php is not functioning right?
Here is my index.php and add.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
</head>
<body>
<?php
include("dbconfig.php");
$sql = "SELECT * FROM games";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)){
echo "<p class=\"p" .$record['ID']. "\"></br> Game ID: " .$record['ID']. "</br> Game Name: " .$record['Name'].
"<br /> Game Type: ".$record['Type']. "<br /> Rating: ".$record['Rating']."<br /> Year Released: ".$record['Release Year']."<br /> <br />" ?>
<img src="trash.png" alt="delete"/> </p>
<?php
}
?>
<form name="add" id ="add" action="" method="post">
<input class ="gameID" type="hidden" id="ID" name="ID" value = " ' .$record['ID'] . ' " />
<b>Game Name: </b> <input type="text" id="name" name="name" size=70>
<b>Game Type:</b> <input type="text" id="type" name="type" size=40>
<b>Rating: </b> <input type="number" id="score" name="score" min="1.0" max="10.0" step ="0.1"/>
<b>Year Released: </b> <input type="number" min="1900" max="2011" id="Yreleased" name="Yreleased" value="1985" size=4>
<p><input type="submit" name="Submit" id = "Submit" value="Add Game" class = "add games"></p>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#add").submit(function(){
var name = this['name'].value;
var type = this['type'].value;
var rating = this['score'].value;
var release = this['Yreleased'].value;
var dataString = 'name='+ name + '&type=' + type + '&rating=' + rating + '&release=' + release;
if (name == '' || type == '' || rating == '' || release == ''){
alert("please enter some valid data for your game entry");
}else
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(){
window.location.reload(true);
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
}
)});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("a.deletebutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var parent = $(this).parent();
if(confirm("Sure you want to delete this game? !..There is no Undo")){
$.ajax({
type: "get",
url: "delete.php?" + info,
context: document.body,
success: function(){
$('.p'+del_id).html('deleted');
$('.success').fadeIn(200).show();
}
});
}
return false;
});
});
</script>
</body>
</html>
add.php
<?php
require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include
if(isset($_POST['name']))
{
$name=addslashes($_POST['name']);
$type=addslashes(($_POST['type']));
$rating=addslashes($_POST['rating']);
$release=addslashes($_POST['release']);
$sql = 'INSERT INTO `games` (`Name`,`Type`,`Rating`,`Release Year`) VALUES ("'.$name.'", "'.$type.'", "'.$rating.'", "'.$release.'")';
mysql_query( $sql);
if(!mysql_errno())
echo " your game has been added to the list of games. ";
}
?>
What your code is currently trying to do is the right principle: you are trying to trap the submit event on the form, make your Ajax request instead, and then cancel the default submit.
The reason it doesn't work is this line:
$("add games").Submit(function(){
".submit()" should have a lowercase "s", and the selector you are using, "add games", is not going to return any elements because it looks for elements with the tag name "games" that are descendents of elements with tag name "add".
What you want to do is fix the case of the "s", and select your element by id, which you do with "#yourid". Your form name has the id "add", so do this:
$("#add").submit(function(){
Also both your document.ready and your submit handler functions have an extra pair of {} curly braces around their bodies so you should delete those:
$("#add").submit(function(){
{ // <- delete this {
/*function body code*/
} // <- delete this }
});
Also you are including the jquery.js script twice - once is enough. And you don't need two document.ready handlers, you can combine them into a single one (though you can have more than one and that shouldn't cause a problem).
(There may be some other issues, but try this first and get back to us.)
UPDATE: After the other fixes, I suspect the problem is now in your PHP, in the line:
if(isset($_POST['Submit']))
I don't know PHP, but I assume this is checking for a request parameter called 'Submit' that you are not setting in your JS (it was the name of your submit button and would've been set for a "standard", non-Ajax submit, but it won't be included in your Ajax request). Try changing that line to use a request parameter that you are setting, like:
if(isset($_POST['name']))
Then, even if you don't seem to get a response in the browser, check your database to see if records are being added.
Make a few changes:
$("add games").submit(function(){ }); -> $(".add games").Submit(function(){});
or
$("#add").submit(function(){}); or $("#add").click(function(){ //run your ajax script here});
as for the id issue, MySQl will keep incrementing the id and if you delete one, it won't decrement it. May I know why you want the ids in order?
Editing again: (Use json.js)
here is another workaround:
var postdata = new Object();
postdata.name = value;
postdata.type = value;
postdata.rating = value;
//and so on
$.ajax({
url: 'your url',
type: "POST",
contentType: "application/json; charset=utf-8", //add this
data: JSON.stringify(postdata), //another change
dataType: "json",
success: function(data, st) {
if (st == "success") {
alert('Data Added');
}
},
error: function() {
alert("Failed!");
}
});
Aside from the problems everyone else helped with, your form is still submitting because of this line:
if (id =='' || name == '' || type == '' || rating == '' || release == ''){
You did not define id in the code above it. This is causing the function to throw an exception before return false is called. You need to either remove id =='' || from your if-statement or define it in your function.
As a side note, I see that you are pulling data from the form using the following:
var name = $("#name").val();
var type = $("#type").val();
Inside the submit handler, this is the form object, meaning you can access form fields by name. I would recommend using the following properties:
var name = this['name'].value,
type = this['type'].value;
This way, you don't need IDs on your form fields and you could if necessary insert the same form multiple times in the document.
Also, you should be validating your form input. A user could enter "); DROP TABLE games;// or <script src='http://evil.com/bad.js'></script> in any of your fields and really ruin your life.

Categories