I'm trying to validate a form before posting the data. Basically the form asks for a code. After the user clicks the submit button, the javascript below checks if the code only contains numbers and has a length of 6 digit. If the code is valid, then an ajax call is made calling the page verifybkcd.php, which runs a query and checks if the input code has associated with an account. Somehow the form is always submitted no matter what code I put.It seemed the ajax call has never been made because none of the alerts inside the call had been triggered. (I'm sure the path of the file verifybkcd.php is correct). Any ideas?
$(document).ready(function(){
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
$("#recovform").submit(function(e){
alert("alert on submit");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
alert("alert inside post");
if(data !=''){
alert("alert on code exists");
e.preventDefault();
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
alert("alert on valid");
$("#err-box").text("");
}
});
});
}
else{
$("#err-box").text("Please enter a valid book code above");
e.preventDefault();
}
});
The following is taken from the php file which has the form
<div id="container">
<?php
if($_SERVER['QUERY_STRING']==''){
?>
<div class="title"><h1>Forgot your password?</h1></div>
<div class="description"><p>To reset your password, enter the book code that you used when you registered your account.</p></div>
<form id="recovform" name="recovform" method="post" action="recovery.php?verifyuser" >
<div id="bkbox">
<label for="bkcode">Book Code:</label>
<input id="bkcode" name="bkcode" type="text" />
<input id="bksubmit" name="submit" type="submit" value="Submit"/>
</div>
<div id="err-box"></div>
</form>
<?php
}
else if($_SERVER['QUERY_STRING']=='verifyuser'){
?>
<div class="title"><h1>verify user</h1></div>
<div class="description"><p>emails below</p></div>
<?php
}
else{
echo "<META HTTP-EQUIV=REFRESH CONTENT='0;URL=../err/404.php'>";
}
?>
</div>
BTW, I'm sure there's nothing wrong with verifybkcd.php file. I've tested it with different codes. It will only return a string when there're no accounts associated with the input code.
Problem solved. I replaced the name of the submit button with something else. Then it worked like magic. Also I've made a little change on the javascript as follows. It seems jquery won't submit the form if you name the submit button "submit". BTW I aslo changed the type of the submit button to "button" instead of "submit"
$(document).ready(function(){
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
if(data !=''){
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
$("#err-box").text("");
$("#recovform").trigger("submit");
}
});
}
else{
$("#err-box").text("Please enter a valid book code above");
}
});
});
First place if you dont want to submit the form then you should return false in the submit button click handler. Check if this below condition satisfied or not.
$(document).ready(function(){
//This is to prevent the form to be submitted
$("#recovform").submit(function(e){
e.preventDefault();
});
$("#bksubmit").click(function(e){
var bkcode = $("#bkcode").val();
var bkcode_format =/^\d{6}$/;
if(bkcode_format.test(bkcode)){
$("#err-box").text("");
//$("#recovform").submit(function(e){
//alert("alert on submit");
$.post("accounts/verifybkcd.php",{bcd:bkcode}, function(data){
alert("alert inside post");
if(data !=''){
//alert("alert on code exists");
//e.preventDefault();
$("#err-box").text("No account found with that book code. Please try again.");
}
else{
//alert("alert on valid");
$("#err-box").text("");
$("#recovform").unbind('submit').submit();
}
});
//});
}
else{
$("#err-box").text("Please enter a valid book code above");
return false;
}
});
in your example, you are missing:
})
at the end to close your $(document).ready in the javascript.
Related
I have a code to check email id is available or not in the database using ajax on keypress. If email Id is available then submit button will enable or email id is not available in the database then submit button will show disabled.
I have no issue in above process below code is working for above process.
My issue is some time users are getting the popup to store the username and password in the browser when the user entered the username and password. I am talking about cookies or can say auto-filed data. For example: If you enter the email id two or three times in text field then next time you clicked on the field you will automatically get your email.
Same issue I am getting. I saved the username and password on my browser and now I am selecting my username and clicking the button which is not working because I am using ajax on keypress. I f I type the email then it is working If I select the email then not working. I need if any user selects the email id than also button should active.
Hope you understand my issue .would you help me in this issue?
On keypress Getting ajax response
Auto filling the email the no response from ajax
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="" method="POST">
<input type="email" id="email" name="email" class="text_field" />
<span id="email-validation-error" class="error"></span>
<input id="submitYesNo" type="submit" name="next" value="submit" disabled="disabled">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
/*checking email id is already exist or not*/
$(document).ready(function() {
$('input[type="submit"]').attr('disabled', true);
});
$(document).ready(function()
{
var elem = $("#id"); //assign target element with id
$("input[name='email']").on('keyup',function()
{
var email = $('#email').val();
$.ajax(
{
url:'process.php',
type:'POST',
data:'email='+email,
success:function(data)
{
if (data == "success") {
$("#submitYesNo").prop('disabled', false);
$("#email-validation-error").html(data);
}
else{
$("#email-validation-error").html(data);
$("#submitYesNo").prop('disabled', true);
}
},
});
});
});
</script>
</body>
</html>
PHP
if(isset($_POST['email'])){
$email=$_POST['email'];
$_SESSION['username']=$email;
$query="SELECT Email FROM `request` WHERE Email='".$email."'";
$result = $conn->query($query);
$search_record=$result->num_rows;
if ($search_record > 0) {
echo "success";
}
else{
echo "Email does not exist, please sign up to use our services";
}
}
This function will work when the user click or focus outside of that input field otherwise it wont work
$("input[name='email']").bind('change keyup', function(){
console.log(this.value);
});
Check this once it may help on your scenario
Bind blur event with keyup event.So that when your textbox loose focus at that time your ajax can be called again
$("input[name='email']").on('keyup blur',function() // Add blur event
{
I have question regarding inserting and updating a MySQL database from a form which is loaded in a div via ajax. I have taken various examples from different websites to check if it was an error on my part but they all work when the page is loaded independently and insert or amended to the database. When the form is loaded into the div, the inputs are completed and submitted it then redirects to the home page as defined in the script file but no information is inserted into the database:
(ajax_url.length < 1) {
ajax_url = 'app/pages/home.php';
}
As I said the form works and inserts if I load the form page directly. For that reason I have also tried the following while giving the form an id of "dataforms" and the submit button an id of "sub":
$("#sub").click( function() {
$.post( $("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#dataforms").submit( function() {
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
Is there something basic I am completely missing?
This is an example I was trying to get to work:
<?php
include_once('/config.php');
$task_name = $_POST['task_name'];
if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
<span id="result"></span>
<form id="dataforms" action="" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name"><br/>
<button id="sub">Save</button>
</form>
I have also attempted to define the php in a separate file and call it on action and I end up with what looks like the post values not being carried across as I get an error showing $task_name is not defined.
The js script file is referenced in the footer and have no issues with datatables displaying and selecting data from the database so I guess it has something to do with how the form is being submitted and reloading. Do I need to treat form submissions differently when ajax is involved? I have used various insert and update scripts to test and all behave the same way.
First Page — can be .html or .php, doesn't matter:
<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name"><br/>
<button id="sub">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"
integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
crossorigin="anonymous"></script>
<script>
$("#sub").click( function() {
$.post(
$("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){
$("#result").html(info);
});
clearInput();
});
$("#dataforms").submit( function() {
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
</script>
Second page — insert-task.php:
<?php
//include_once('/config.php');
$task_name = $_POST['task_name'];
//if(mysql_query("INSERT INTO task (task_name) VALUES('$task_name')"))
// echo $task_name; die;
if(true)
echo "Successfully Inserted";
else
echo "Insertion Failed";
?>
The two pages do work in tandem. Though there are a couple of things to note, please:
The database operations aren't yet a part of the executable code.
However, if // echo $task_name; die; was uncommented, then the <span> in the first page would be populated with whatever value was keyed in the input field, which would establish that the form data is relayed properly to the backend.
EDIT:
To deal with the required fields, following change is required in the first page:
Get rid of the click function for $("#sub")
Prevent the default submit action when dataforms is submitted
So, in effect, the updated code would look like follows:
<span id="result"></span>
<form id="dataforms" action="insert-task.php" method="post">
<label id="first"> Task Name</label><br/>
<input type="text" name="task_name" required><br/>
<button id="sub">Save</button>
</form>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"
integrity="sha256-JAW99MJVpJBGcbzEuXk4Az05s/XyDdBomFqNlM3ic+I="
crossorigin="anonymous"></script>
<script>
$("#dataforms").submit( function(e) {
e.preventDefault();
$.post(
$("#dataforms").attr("action"),
$("#dataforms :input").serializeArray(),
function(info){
$("#result").html(info);
}
);
clearInput();
return false;
});
function clearInput() {
$("#dataforms :input").each( function() {
$(this).val('');
});
}
</script>
This would still show up Please fill out this field message if no data was entered in the input field and, at the same time, prevent the unexpected pop-up as a consequence of clearing the field after a successful submit.
I have a message box with a submit button, when I click the submit button the content in the box should be insert in the MYSQL database, but without going to another page. The message which i just entered in the message box should be displayed in the same page after the submission. What should I do?
Use something called AJAX..
suppose this is your code :
<form id="myform" action="something" <!--Add this part-->onsubmit='return sendData()'<!--End of added part-->>
Enter Message <textarea name="msg" id="msg"></textarea>
<input type="submit" value="submit" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
function sendData(){
var msgVal = $("#msg").val();
$.ajax({
data:"msg="+escape(msg),
url: $("#myform").attr("action"),
type: $("#myform").attr("method"),
success:function(){
alert( $("#msg").val() );
}
});
return false;
}
</script>
<script type="text/javascript">
function postData() {
var order = 'name='+$('#textBoxId').val();
$.post("Another_PHP_Page_Path.php", order, function(response,status, xhr){
if (status == "success") {
alert(response);
$('#divId').text(response);
}
else if (status == "error") {
alert('Something went wrong, we are working to fix it');
}
});
}
</script>
Note: name will be posted to PHP Page and after insterting into Database you can echo anything on php page or echo name, and on response this will showing back at same page. Use postData() on button onclick and button type should be button not submit.
i have this html and javascript program code for log in window. my html is:
<body>
<div >
<h1>Sign in to me</h1>
<form id="login" method="get" action='exercises/exercise6/DynamicMenu_createTab_json.html'>
<div>UserName<input type="text" id="username" value="admin"/></div>
<div>Password<input type="password" id="password"/></div>
<div><input type="button" id="btnLogin" value="Login"/></div>
</div>
</body>
my javascript is:
$(document).ready(function(){
$('#username').focus();
$('form#login :submit').addClass('inputSubmitBtn').click(function(){
if($('#username').val() != "jay" || $('#password').val() != "son"){
alert('username/password incorrect');
$("#username").focus();
return false;
};
});
});
there's no problem in this program. what i wanted to do is i want to log in using my username and password from a server. and if it is succesful, it will open my other exercise html on the same window. here's my current code:
$('form#login :submit').addClass('inputSubmitBtn').click(function(){
var params = {
"UserName":$("#username").val(),
"Password":$("#password").val()
};
$.getJSON(
'process.php', 'path=Login&json=' + JSON.stringify(params),
function(data) {
if ('error' in data)
{
alert('password and username incorrect');
return false;
}
else
{
$("#sessionID").html(data["result"]["SessionID"]);
}
});
});
this code doesn't function right. please, can someone help me on this...
EDIT: here's my php code:
<?php
echo(file_get_contents("http://localhost/" . $_GET["path"] . "?json=" . $_GET["json"]));
?>
First the :submit selector returns nothing, you don't have a submit button ("type=submit"), so the click listener will never be called. See :submit selector.
Second you don't stop the submit event of the form, so the "action" attribute is used and the form is submitted, canceling the click listener function. (url 'exercises/exercise6/DynamicMenu_createTab_json.html' will be loaded)
You need to stop the event, else the form "action" will fire when the form is submitted.
$('#login :submit').click(function(event){ event.preventDefault(); ... });
And last, a click event listener function on the submit button will not fire 100% of the time.
For exemple when user press "enter" key while in a field of the form, no click on the button and the form is submitted.
Bind a submit event listener on the form instead.
$('#login').submit(function(event){ ... });
I have a form using the form jQuery plug in to handel the posting of the data. In the example i am working with the data is psoted to another php file which reades a database and echos back a result which is displayed below the from.
The code works very well with one glitch. If you hit the enter button while the text filed is selected everything cleared including the result that has been written to the screen. Is it possible to disable to enter key and prevent it from doing this?
FORM:
<html>
<head>
</head>
<p>enter code here
<form name="form" action="" method="">
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name"/>
<input type="button" value="get" onclick="get();"/>
</form>
<div id="age"></div>
</p>
</body>
</html>
SCRIPT:
function get() {
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
}
Cheers.
You should consider using the jQuery Forms Plugin. It will save you from doing some of the dirty work, additionally it will intercept all ways of submitting the form - so instead of having to disable the RETURN key it will submit your form via AJAX.
If you don't want that, get rid of the button with the onclick event and replace it with a submit button and register your function as a onsubmit handöer:
$('form[name=form]').submit(function(e) {
e.preventDefault();
$.post('data.php', {name: form.name.value},
function(output) {
$('#age').hide().html(output).fadeIn(1000);
});
}
});
$(document).ready(function(){
$('form').submit(function(){
return false;
});
});
This will prevent the form from submitting, however the form will not work at all for users with javascript disabled.
A found some tuts and solved the issue.
I just put this in before my Jquery code to disable the enter button.
$(function () {
$('input').keypress(function (e) {
var code = null;
code = (e.keyCode ? e.keyCode : e.which);
return (code == 13) ? false : true;
});
});