I have this query
$tww_update_sql = "UPDATE `telesales_anc` SET
`Ime` = '".$_POST['Ime'];
and I have a form with submit button as follows:
<form id="contact" method="post" action="ANC_pozivanje_test.php">
<div class="col-md-2 col-sm-12 col-xs-12 form-group">
<small>Ime</small>
<input id="contact_name" type="text" name="Ime" placeholder="Ime" class="form-control" value="<?php echo $values['Ime']?>">
</div>
<div class="form-group">
<div id="contact_submit" class="col-md-9 col-sm-9 col-xs-12">
<button type="submit" class="btn btn-success" value="Save">Save</button>
</div>
</div>
Script that I used for checking in field is populated is as follows:
<script>
$(document).ready(function() {
<!-- Real-time Validation -->
<!--Name can't be blank-->
$('#contact_name').on('input', function() {
var input=$(this);
var is_name=input.val();
if(is_name){input.removeClass("invalid").addClass("valid");}
else{input.removeClass("valid").addClass("invalid");}
});
<!-- After Form Submitted Validation-->
$("#contact_submit button").click(function(event){
var form_data=$("#contact_name").serializeArray();
var error_free=true;
for (var input in form_data){
var element=$("#contact_name"+form_data[input]['']);
var valid=element.hasClass("valid");
var error_element=$("span", element.parent());
if (!valid){
error_element.removeClass("error").addClass("error_show");
error_free=false;
}
else{
error_element.removeClass("error_show").addClass("error");
}
}
if (!error_free){
event.preventDefault();
}
else{
alert('Status nije popunjen');
}
});
});
</script>
Problem is when button is submitted (if field is not populated) I got message "Status nije popunjen" but form is submited regard message.
Is it necessary to use script for this?
It seems you check whether error_free is false, in which case you prevent for submission, however, if it is true (so if the field is populated), you only give an alert. Shouldn't event.preventDefault() be inside else?
You should not listen to button.click, but to form.submit.
<!-- After Form Submitted Validation-->
$("#contact").on('submit', function(event) {
The method event.preventDefault() will prevent the form from submitting, and should be in the same block as the alert()
if (!error_free) {
event.preventDefault();
alert('Status nije popunjen');
}
all you want to do is to validate the data on the client side, making sure that a valid name is supplied. i will recreate this here.
You can simply make changes to it. but i believe this solves your need. Also note that you should validate data on the server. dont just rely on client side validation
$update_sql = "UPDATE " . $table_name . " SET Ime = '" . $_POST['txt-name'] . "'";
'use strict';
$(document).ready(function() {
//bind click event on the button
var form = document.forms['frm-contact'];
$('#btn-contact').bind('click', function(event) {
event.preventDefault(); //this will prevent the form from getting submitted, so that we can validate the user name.
var field = form.elements['txt-name'],
name = field.value,
len = name.length,
error = '';
if (len === 0) {
error = 'Enter your name';
}
else if (len < 2) {
error = 'name should not be less than 2 characters';
}
else if (len > 36) {
error = 'name should not exceed 36 characters';
}
else if (/^[^a-z]+/i.test(name)) {
error = 'name must start with letters';
}
else if (!/^['.a-z\- ]+$/i.test(name)) {
error = 'invalid characters found'; // name should contain only alphabets, dash character, space character and dot character only
}
//done validating. show error now or submit the form.
if (error) {
alert(error);
$(field).addClass('error');
}
else {
$(field).removeClass('error');
form.submit();
}
});
});
.error {
background-color: red;
color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="frm-contact" id="frm-contact" method="post" action="example.php">
<div class="form-group">
<label for="txt-name">Name:</label>
<input type="text" name="txt-name" id="txt-name" placeholder="enter your name" value="" />
</div>
<div class="text-center">
<button type="submit" class="btn btn-success" name="btn-contact" id="btn-contact" value="contact us">SEND</button>
</div>
</form>
Related
these are the javascript functions i'm using
function addFac() {
$("<div>").load("includes/facility.php", function() {
$("#fac").append($(this).html());
});
}
function deleteFac() {
$('div.facility-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
here is the HTML code:
<div class="facility-item well" style="clear:both;">
<div class="row">
<div class="col-lg-1 col-sm-1 col-xs-3 padder-col">
<input type="checkbox" class="chk-lg">
</div>
<div class="col-lg-10 col-lg-offset-1 col-md-9 col-md-offset-2 col-sm-11 col-xs-9">
<input class="form-control" type="text" placeholder="Describe facility" name="faci[]" >
</div>
</div>
</div>
This code of html is written in a file named facilities.php and the file is included into the index.php. This is how i'm able to add and remove the dynamic input fields. But
when I wrote the PHP file:
$facilities = "0";
$faci = $_POST["faci"];
var_dump($faci);
even after having multiple facilities, it showed only one value in array.
Here is the working code Paste and run.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><img src="remove-icon.png"/>remove</div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<form name="karan" action="" method="post">
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value="">
add
</div>
</div>
<input type="submit" name="submit" value="SUBMIT">
</form>
<?php
print '<pre>';
print_r($_REQUEST['field_name']);
print '</pre>';
//output
?>
<?php
$field_values_array = $_REQUEST['field_name'];
foreach($field_values_array as $value){
//your database query goes here
}
?>
This is embarrassing but I cant seem to figure out why my form wont repost after changing the values.
To be clearer, I have this password recovery form in which user enters the email address. The form is processed in PHP through AJAX and a validation/success message is displayed on the form page.
The issue here is that if the user has entered an invalid email address, it displays the error message but if the user then corrects the email address and tries to submit again, it doesn't process the input unless if the page is explicitly refreshed (in which case it shows the resubmission warning which is very annoying). Is there some property that sets the form and needs to be 'un-set' through code? How can I improve this experience? I have posted the code below.
<form id="pwd_rec_form" method="post" action="">
<div class="row">
<div class="large-6 columns">
<input type="email" required placeholder="Email ID" name="email"/>
</div>
</div>
<div id="val_msg" class="row"></div>
<div class="row">
<div class="large-6 columns">
<input id="submit_button" type="submit" value="Send" class="button"/>
</div>
</div>
<div class="row">
<div class="large-6 columns">
Back to login page
</div>
</div>
</form>
<script>
$(function()
{
$("#pwd_rec_form").submit(function()
{
var formdata = $(this).serializeArray();
var hideMsg = function() {$("#val_msg").hide()};
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "recover-password.php",
data: formdata,
success: function(res)
{
$('#val_msg').html(res);
setTimeout(hideMsg, 5000);
}
});
$("#pwd_rec_form").trigger("reset");
return false;
});
});
</script>
PHP :
<?php
include 'db-connect.php';
if($_SERVER["REQUEST_METHOD"] == "POST")
{
$conn = getDBConnection();
// Check connection
if (mysqli_connect_errno())
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_connect_error() . '
</div>'
);
exit();
}
$eID = mysqli_real_escape_string($conn, trim(strip_tags($_POST['email'])));
$query = 'SELECT password FROM member_login WHERE email_id = "' . $eID . '";';
$result = mysqli_query($conn, $query);
if($result == FALSE)
{
echo(' <div data-alert class="alert-box secondary">' . mysqli_error($conn) . '
</div>'
);
}
else
{
if(mysqli_num_rows($result) == 0) // User not found.
{
echo('<small class="error">This email address is not registered with us.</small>');
}
else
{
$pswd = mysqli_fetch_assoc($result);
//mail the pswd
echo(' <div data-alert class="alert-box success">
Your password has been successfully sent to your registered email address.
</div>'
);
/* free result set */
mysqli_free_result($result);
}
}
mysqli_close($conn);
}
?>
I think your problem is that you have a submit button, which automatically submits the form and refreshes the page, so your javascript doesn't get used. Try making your submit button a type="button" and then changing your jQuery to $("#pwd_rec_form").click(function() and see if that works.
You could hook the form submit, or if you wanted you can hook the click event of the submit button, prevent the default action and instead do your javascript code. Here is an example hooking the "submit_button" click event:
$(document).ready(function() {
$("#submit_button").click(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
Alternative you can do this:
$(document).ready(function() {
$(form).submit(function(e) {
e.preventDefault();
// Do your ajax stuff
});
});
The code above just hooks the form on the submit request, prevents the default action, and then you slap your ajax code in there.
I appreciate your help guys. I knew it was something silly. Turns out the form was getting processed but the validation/success messages were not being displayed as the div element that I was hiding using javascript during the first submission needed to be shown again for the second attempt!
Could you try this :
<script>
$(document).ready(function(){
$('#pwd_rec_form').on('submit', function(e){
e.preventDefault();
// insert AJAX call
});
It worked for me, the event is trigged on each click.
Best regards,
I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>
The contact form it´s working, if you fill it all it sends the message. The problem if you don´t fill in the email box, the form doesn´t alert you about it, is there anyway that I can show a word or somekind of alert to the user?
this is my markup:
<div class="form">
<h2>ESCRIBENOS</h2>
<form method="post" action="process.php">
<div class="element">
<label>Nombre (obligatorio):</label><br/>
<input type="text" name="name" class="text" />
</div>
<div class="element">
<label>Email (obligatorio):</label><br/>
<input type="text" name="email" class="text" />
</div>
<div class="element">
<label>Telefono:</label><br/>
<input type="text" name="website" class="text" />
</div>
<div class="element">
<label>Mensaje:</label><br/>
<textarea name="comment" class="text textarea" /></textarea>
</div>
<div class="element">
<input type="submit" id="submit"/>
<div class="loading"></div>
</div>
</form>
</div>
And this is my script:
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (email.val()=='') {
email.addClass('hightlight');
return false;
} else email.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&email=' + email.val() + '&website=' +
website.val() + '&comment=' + encodeURIComponent(comment.val());
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "../process.php",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
//hide the form
$('.form').fadeOut('slow');
//show the success message
$('.done').fadeIn('slow');
//if process.php returned 0/false (send mail failed)
} else alert('Sorry, unexpected error. Please try again later.');
}
});
//cancel the submit button default behaviours
return false;
});
});
Can someone help me out please?
Try this:
var name = $('input[name=name]');
var email = $('input[name=email]');
var website = $('input[name=website]');
var comment = $('textarea[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
$('input[type=text]').each(function(){
if($(this).val().length == 0){
$(this).addClass('hightlight');
alert('Empty input field')
return false;
}
});
.... rest of your code
Note: This does not work for textarea but I think you can figure that out yourself!
EDIT:
var valid = false;
$('input[type=text]').each(function(){
if($(this).val().length == 0){
$(this).addClass('hightlight');
alert('Empty input field')
valid = false;
}else{
valid = true;
}
});
if(valid == false) return;
console.log('All input fields are filled in..');
... rest of your code. You can remove al the if else statements for input fields. For checking the textarea you could give all fields the same class and do:
$('form.classofallelements').each(function(){
I have a mobile website and everything is working fine except for the validation. Basically I'm looking to take values from the user and then process them on a separate page (process.php). However, before doing so I need to check to make sure the fields have been populated. I have looked at several ways to do this but none seem to be working. I have the below code at the moment. When I press the process button it brings me through to the process.php splash screen even though the item field is empty. It doesn't write to the database but I would rather it didn't bring the user to the process.php screen until all mandatory fields have been filled in. Any ideas?
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#formL").validate(); });
</script>
<div data-role="content">
<form id="formL" action="/website/process.php" method="post">
<div data-role="fieldcontain">
<label for="item">
<em>* </em> <b>Item:</b> </label>
<input type="text" id="item" name="item" class="required" />
</div>
<div class="ui-body ui-body-b">
<button class="buttonL" type="submit" data-theme="a">Process</button>
</div>
</form>
</div>
For a small form like that, I wouldn't bother using a plugin - is it even compatible with jQuery Mobile? Anyway, to get you started, here's a simple way to prevent submission when there are empty fields:
$("#formL").submit(function() {
// get a collection of all empty fields
var emptyFields = $(":input.required").filter(function() {
// $.trim to prevent whitespace-only values being counted as 'filled'
return !$.trim(this.value).length;
});
// if there are one or more empty fields
if(emptyFields.length) {
// do stuff; return false prevents submission
emptyFields.css("border", "1px solid red");
alert("You must fill all fields!");
return false;
}
});
You can try it/mess with it here.
I have ran across the same problem you have, I have my form validating correctly now.
The following is what I have done with Jquery Mobile -->
<link rel="stylesheet" href="css/jquery.mobile-1.0a4.1.css" />
<link rel="stylesheet" href="css/colors.css">
<link rel="stylesheet" href="css/list.css">
<!--For Icon to bookmark on phones-->
<link rel="apple-touch-icon-precomposed" href=""/>
<script>
var hdrMainvar = null;
var contentMainVar = null;
var ftrMainVar = null;
var contentTransitionVar = null;
var stateLabelVar = null;
var whatLabelVar = null;
var stateVar = null;
var whatVar = null;
var form1var = null;
var confirmationVar = null;
var contentDialogVar = null;
var hdrConfirmationVar = null;
var contentConfirmationVar = null;
var ftrConfirmationVar = null;
var inputMapVar = null;
// Constants
var MISSING = "missing";
var EMPTY = "";
var NO_STATE = "ZZ";
</script>
<div data-role="header" id="hdrMain" name="hdrMain" data-nobackbtn="true">
</div>
<div data-role="content" id="logo" align="center">
<img src="img/sam_mobile.png">
</div>
<div data-role="content" id="contentMain" name="contentMain">
<form id="form1">
<div id="userDiv" data-role="fieldcontain">
<label for="userName">User Name*</label>
<input id="userName" name="userName_r" type="text" />
</div>
<div id="passwordDiv" data-role="fieldcontain">
<label for="password" id="passwordLabel" name="passwordLabel">Password*</label>
<input id="password" name="password_r" type="password" />
</div>
<div id="submitDiv" data-role="fieldcontain">
<input type="submit" value="Login" data-inline="true"/>
</div>
</form>
</div><!-- contentMain -->
<div data-role="footer" id="ftrMain" name="ftrMain"></div>
<div align="CENTER" data-role="content" id="contentDialog" name="contentDialog">
<div>You must fill in both a user name and password to be granted access.</div>
<a id="buttonOK" name="buttonOK" href="#page1" data-role="button" data-inline="true">OK</a>
</div> <!-- contentDialog -->
<!-- contentTransition is displayed after the form is submitted until a response is received back. -->
<div data-role="content" id="contentTransition" name="contentTransition">
<div align="CENTER"><h4>Login information has been sent. Please wait.</h4></div>
<div align="CENTER"><img id="spin" name="spin" src="img/wait.gif"/></div>
</div> <!-- contentTransition -->
<div data-role="footer" id="ftrConfirmation" name="ftrConfirmation"></div>
<script>
$(document).ready(function() {
//Assign global variables from top of page
hdrMainVar = $('#hdrMain');
contentMainVar = $('#contentMain');
ftrMainVar = $('#ftrMain');
contentTransitionVar = $('#contentTransition');
stateLabelVar = $('#stateLabel');
whatLabelVar = $('#whatLabel');
stateVar = $('#state');
whatVar = $('#what');
form1Var = $('#form1');
confirmationVar = $('#confirmation');
contentDialogVar = $('#contentDialog');
hdrConfirmationVar = $('#hdrConfirmation');
contentConfirmationVar = $('#contentConfirmation');
ftrConfirmationVar = $('#ftrConfirmation');
inputMapVar = $('input[name*="_r"]');
hideContentDialog();
hideContentTransition();
hideConfirmation();
});
$('#buttonOK').click(function() {
hideContentDialog();
showMain();
return false;
});
$('#form1').submit(function() {
//Start with false to hide specific div tags
var err = false;
// Hide the Main content
hideMain();
// Reset the previously highlighted form elements
stateLabelVar.removeClass(MISSING);
whatLabelVar.removeClass(MISSING);
inputMapVar.each(function(index){
$(this).prev().removeClass(MISSING);
});
// Perform form validation
inputMapVar.each(function(index){
if($(this).val()==null || $(this).val()==EMPTY){
$(this).prev().addClass(MISSING);
err = true;
}
});
if(stateVar.val()==NO_STATE){
stateLabelVar.addClass(MISSING);
err = true;
}
// If validation fails, show Dialog content
if(err == true){
showContentDialog();
return false;
}
// If validation passes, show Transition content
showContentTransition();
// Submit the form
$.post("requestProcessor.php", form1Var.serialize(), function(data){
//DB Validation goes here when we link to the Db
confirmationVar.text(data);
hideContentTransition();
window.location="access.php";
});
return false;
});
function hideMain(){
hdrMainVar.hide();
contentMainVar.hide();
ftrMainVar.hide();
}
function showMain(){
hdrMainVar.show();
contentMainVar.show();
ftrMainVar.show();
}
function hideContentTransition(){
contentTransitionVar.hide();
}
function showContentTransition(){
contentTransitionVar.show();
}
function hideContentDialog(){
contentDialogVar.hide();
}
function showContentDialog(){
contentDialogVar.show();
}
function hideConfirmation(){
hdrConfirmationVar.hide();
contentConfirmationVar.hide();
ftrConfirmationVar.hide();
}
function showConfirmation(){
hdrConfirmationVar.show();
contentConfirmationVar.show();
ftrConfirmationVar.show();
}
</script>
This will not allow the form to be submitted if there is empty fields. Feel free to take this code and manipulate and play with it as much as you like. As you can see I used a .php file, just like you, to handle the validation of the user.