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.
Related
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>
I am using Fine Uploader (v5.0.1) with jQuery, jQuery.validate and jQuery.form plugins for a multi-field form for new events which can have zero to two file attachments.
I have it working, but I have a few questions before I go further.
My client-side code is generating one POST request for each file (including the other form elements) plus one additional POST request for only the other form elements. So, if my form has two file attachments, I am getting three POST requests. Is this normal behavior? Can I get everything in one POST request?
If multiple POST requests is normal behavior, I will have to generate some sort of unique identifier at the client prior to the first POST request, so I can avoid duplication of event records in my database and to associate each file upload with the correct event. If this is the direction I need to go, are there any examples of this type of implementation I can look at?
If no files are attached, I am getting an alert dialog: "No files to upload." The form can be submitted with no file attachments, so I don't want to imply to the user that he/she must attach files. How can I get rid of this dialog?
I am currently getting one POST response for the form data plus one POST response for each file uploaded. Is there a way to handle only the final POST response (e.g., form.onAllComplete)? What if the form has no file attachments?
I am using one server endpoint for the form, including file uploads. Should I be using two separate endpoints, one for the other form fields and one for file uploads?
Here is my form: http://www.paulrachal.com/test/fineuploader-test.htm
Here is my code:
Client:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<title>New Event</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<!-- Fine Uploader -->
<link rel="stylesheet" href="../css/custom.fineuploader-5.0.1.min.css" />
<script src="../js/custom.fineuploader-5.0.1.min.js"></script>
<!-- document.ready -->
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
<!-- event handlers -->
// hide the file upload button when the page loads
$( '#manual-fine-uploader' ).hide();
// show the file upload button on change in attachments checkbox
$("#hasattachments").change(function() {
if ($('#hasattachments:checked').length) {
$('#manual-fine-uploader').show();
}
else {
$('#manual-fine-uploader').hide();
}
})
<!-- Fine Uploader setup -->
var manualuploader = $('#manual-fine-uploader').fineUploader({
request: {
endpoint: 'fineuploader-test.php'
},
form: {
element: 'new-event'
},
template: "qq-template-manual-noedit",
validation: {
allowedExtensions: ['txt', 'pdf'],
itemLimit: 2,
sizeLimit: 256000 // 250 kB = 250 * 1024 bytes
},
autoUpload: false
});
<!-- form validation -->
// setup form validation on the form element
$("#new-event").validate({
// validation rules
rules: {
description: {
required: {
depends: function(element) {
if ( $("input[name='eventtype']:checked").val() == "3" || $("input[name='eventtype']:checked").val() == "4" || $("input[name='eventtype']:checked").val() == "5" )
return true;
}
}
},
},
// validation error messages
messages: {
description: "Please enter a description"
},
// submit handler
submitHandler: function(form) {
$("#send").attr("value", "Sending...");
$(form).ajaxSubmit({
target: "#response",
dataType: "json",
success: function processJson(response) {
if (response.success)
{
$(form).slideUp("fast");
$("#response").html("<span class='success'>" + response.success + "</span>").hide().slideDown("fast");
} // end if
else if (response.failure)
{
$("#response").empty();
$(".error").removeClass("error");
$errors = response.failure;
for ($i = 0; $i < $errors.length; $i++) {
$error = $errors[$i];
$.each($error, function(key, value) {
// append error text to div#response
$("#response").append("<li class='failure'>" + value + "</li>").hide();
// set form elements based on the error
switch(key) {
case "description-isempty":
$("#description").addClass("error");
break;
case "eventname-isempty":
$("#eventname").addClass("error");
break;
case "eventtype-isinvalid":
$("#eventtype-input").addClass("error");
break;
default:
// default statements if no cases are true
} // end switch
}); // end $.each
} // end for
$("#response").addClass("failure");
$("#response").slideDown("fast");
$("html, body").animate({ scrollTop: 0 }, "fast");
} // end else if
} // end processJson
});
return false;
}
}); // end #new-event.validate
<!-- validate individual fields on change -->
// #description
$('#description').on('change', function() {
$('#new-event').validate().element('#description');
});
}); // end document.ready
</script>
<!-- Fine Uploader Template -->
<script type="text/template" id="qq-template-manual-noedit">
<div class="qq-uploader-selector qq-uploader">
<div class="qq-upload-drop-area-selector qq-upload-drop-area" qq-hide-dropzone>
<span>Drop files here to upload</span>
</div>
<div class="qq-upload-button-selector qq-upload-button">
<div>Browse...</div>
</div>
<span class="qq-drop-processing-selector qq-drop-processing">
<span>Processing dropped files...</span>
<span class="qq-drop-processing-spinner-selector qq-drop-processing-spinner"></span>
</span>
<ul class="qq-upload-list-selector qq-upload-list">
<li>
<div class="qq-progress-bar-container-selector">
<div class="qq-progress-bar-selector qq-progress-bar"></div>
</div>
<span class="qq-upload-spinner-selector qq-upload-spinner"></span>
<span class="qq-upload-file-selector qq-upload-file"></span>
<span class="qq-upload-size-selector qq-upload-size"></span>
<a class="qq-upload-cancel-selector qq-upload-cancel" href="#">Cancel</a>
<span class="qq-upload-status-text-selector qq-upload-status-text"></span>
</li>
</ul>
</div>
</script>
<!-- styles -->
<style type="text/css">
.qq-upload-button-selector {
background: #0080FF;
}
#response {
margin-bottom: 20px;
text-align: center;
}
#response .success {
color: #08a300;
}
#response .failure {
color: #dc0000;
}
div.failure {
background-color: #FF0;
}
.error {
border: 2px solid red;
}
input.error {
border: 2px solid red;
}
select.error {
border: 2px solid red;
}
</style>
</head>
<body>
<!-- new-event-form -->
<div id="new-event-form" data-role="page">
<!-- header -->
<div data-role="header"><h1>NEW EVENT</h1></div>
<div class="content" data-role="content">
<div id="response"></div>
<form id="new-event" action="fineuploader-test.php" method="post">
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Event Type:</legend>
<div id="eventtype-input">
<input type="radio" name="eventtype" id="eventtype_1" value="1" checked="checked" />
<label for="eventtype_1">Ride</label>
<input type="radio" name="eventtype" id="eventtype_2" value="2" />
<label for="eventtype_2">Clinic</label>
<input type="radio" name="eventtype" id="eventtype_3" value="3" />
<label for="eventtype_3">Social Event</label>
<input type="radio" name="eventtype" id="eventtype_4" value="4" />
<label for="eventtype_4">Meeting</label>
<input type="radio" name="eventtype" id="eventtype_5" value="5" />
<label for="eventtype_5">Non-Club Event</label>
</div>
</fieldset>
</div>
<div data-role="fieldcontain">
<label for="eventname">Event Name:</label>
<input type="text" name="eventname" id="eventname" value="" maxlength="40" required />
</div>
<div id="descriptioninput" data-role="fieldcontain">
<label for="description">Description:</label>
<input type="text" name="description" id="description" value="" maxlength="40" />
</div>
<div id="attachments" data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Attachments:</legend>
<input type="checkbox" name="hasattachments" id="hasattachments" value="1" />
<label for="hasattachments">Attachments</label>
</fieldset>
</div>
<div id="manual-fine-uploader">Browse...</div>
<div class="ui-body ui-body-b">
<fieldset class="ui-grid-a">
<div class="ui-block-a"><input type="reset" data-theme="d" value="Cancel"></div>
<div class="ui-block-b"><input type="submit" data-theme="a" value="Submit"></div>
</fieldset>
</div>
</form>
</div> <!-- /content -->
</div> <!-- /page -->
</body>
</html>
Server:
<?php
// get values from POST request
$eventtype = $_POST['eventtype']; // eventtype field
$eventname = $_POST['eventname']; // eventname field
$description = $_POST['description']; // description field
$hasattachments = $_POST['hasattachments']; // hasattachments field
$qqfile = $_POST['qqfile']; // file upload field
$qquuid = $_POST['qquuid']; // file upload uuid
$qqfilename = $_POST['qqfilename']; // file upload filename
// include the upload handler class
require_once "handler.php";
// initialize errors array
$errors = array();
// validate elements
// eventtype
$eventtypes = array_flip(array('1', '2', '3', '4', '5'));
if (!isset($eventtypes[$eventtype])) $errors = addError("eventtype-isinvalid");
// eventname
$eventname = filter_var($eventname, FILTER_SANITIZE_STRING);
if(empty($eventname)) $errors = addError("eventname-isempty");
// description
$description = filter_var($description, FILTER_SANITIZE_STRING);
if (empty($description)) $errors = addError("description-isempty");
// file uploads
if ($hasattachments == 1) uploadFiles();
// functions
// add error
function addError($error) {
switch ($error)
{
case "description-isempty":
$errors[] = array("description-isempty" => "Please enter a description.");
break;
case "eventname-isempty":
$errors[] = array("eventname-isempty" => "Please enter an event name.");
break;
case "eventtype-isinvalid":
$errors[] = array("eventtype-isinvalid" => "Please select an event type.");
break;
} // end switch($error)
return $errors;
} // end function addError()
// file uploads
function uploadFiles() {
$uploader = new UploadHandler();
// specify the list of valid extensions
$uploader->allowedExtensions = array("txt", "pdf");
// specify max file size in bytes
$uploader->sizeLimit = 250 * 1024; // 250 kB
// specify the input name set in the javascript.
$uploader->inputName = "qqfile"; // matches Fine Uploader's default inputName value by default
// specify the folder to temporarily save parts to use the chunking/resume feature
$uploader->chunksFolder = "chunks";
$method = $_SERVER["REQUEST_METHOD"];
if ($method == "POST") {
header("Content-Type: text/plain");
// call handleUpload() with the name of the folder, relative to PHP's getcwd()
$result = $uploader->handleUpload("uploads/");
// get the name used for uploaded file
$result["uploadName"] = $uploader->getUploadName();
} // end if
} // end function uploadFiles()
// return response
if (!empty($errors)) $response = array("failure" => $errors);
else $response = array("success" => "Success! Your event has been posted.");
echo json_encode($response);
?>
Answering your questions in order:
Fine Uploader sends each file in a separate request, and there is no way to change this.
Fine Uploader already generates a unique ID (UUID) for each file. This ID is sent with the upload request. If you want to send additional data for a file, you can do so via the setParams API method. This will send additional, custom parameters of your choice along with the file. You can specify new params for all files, or a specific file.
In form mode, Fine Uploader intercepts the submit request and sends the file(s) and all form fields via ajax/XHR. Currently, it expects at least one file to be selected, as the form fields are sent as parameters for each selected file. A lack of selected files means that, in its current state, the form fields cannot be sent. Changing this will require adjustments to Fine Uploader's internal code. You can work around this by not utilizing form mode. Instead, you'll need to submit your form data in one request, and then have Fine Uploader send any selected files via the API.
Fine Uploader should intercept the form submit, so there should only be one response per file. The form fields are sent with each file.
This may be the required approach if you want to make the file field optional for your users.
I'm developing a simple login form but with advanced features in that. On submitting the form I want to validate it with AJAX and display the error message in the respective "SPAN class="error". The problem is i'm not getting the validation error when i submit the form. The following is the code i've tried. Please help..
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<link rel="shortcut icon" href="_images/Favicon.png"/>
<title>18+</title>
<link href="_css/login.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="_scripts/jquery.tools.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#username').focus(); Focus to the username field on body loads
$('#submit').click(function(){ // Create `click` event function for login
var username = $('#username'); // Get the username field
var password = $('#password'); // Get the password field
var login_result = $('.login_result'); // Get the login result div
var username = $('.username'); // Get the username error div
var password = $('.password'); // Get the password error div
if(username.val() == ''){ // Check the username values is empty or not
username.focus(); // focus to the filed
username.html('<span class="error">Enter the Username...</span>');
return false;
}
if(password.val() == ''){ // Check the password values is empty or not
password.focus();
password.html('<span class="error">Enter Your Password...</span>');
return false;
}
if(username.val() != '' && password.val() != ''){
var UrlToPass = 'action=login&username='+username.val()+'&password='+password.val();
$.ajax({ // Send the credential values to another checker.php using Ajax in POST menthod
type : 'POST',
data : UrlToPass,
url : 'checker.php',
success: function(responseText){ // Get the result and asign to each cases
if(responseText == 0){
login_result.html('<span class="error">The Username Or Password You Entered Is Incorrect...</span>');
}
else if(responseText == 1){
window.location = 'admin.php';
}
else{
alert('Problem with sql query');
}
}
});
}
return false;
});
});
</script>
</head>
<body>
<div id="logo"></div>
<div id="container">
<div id="form">
<form action="" method="post" id="user_login" name="user_login" enctype="multipart/form-data">
<p id="head">User Login</p>
<div class="row">
<span class="error" class="login_result" id="login_result"></span>
</div>
<div class="row">
<div class="input">
<input type="text" id="username" name="username" class="detail" placeholder="Username" spellcheck="false" title="Enter Your Username.."/>
<span class="error" id="username">Enter Your Username....</span>
</div>
</div>
<div class="row">
<div class="input">
<input type="password" id="password" name="password" class="detail" placeholder="Password" spellcheck="false" title="Enter Your Password.."/>
<span class="error" id="password">Enter Your Password...</span>
</div>
</div>
<p class="submit">
<button type="submit" id="submit" name="submmit" value="Register">Login</button>
</p>
</form>
</div>
</div>
</div>
</div><!--end container-->
<div id="formfooter">
<div class="input">
Copyright © CompanyName.
</div>
</div>
</body>
</html>
You should prevent the default action when you catch the event in javascript:
....
$('#submit').click(function(e){ // Create `click` event function for login
e.preventDefault(); //Prevent the default submit action of the form
var username = $('#username'); // Get the username field
var password = $('#password'); // Get the password field
var login_result = $('.login_result'); // Get the login result div
....
First, you have two same ids on your HTML form.
<input type="text" id="username" .../>
<span class="error" id="username">....
Take a look above and you can see that there are two ids username. You should change the id attribute with class attribute so it become
<span class="error" class="username">....
Second, on your javascript you have same variables assigning.
var username = $('#username');
var password = $('#password');
.....
var username = $('.username');
var password = $('.password');
Username and password are already taken. Change that into different variable name.
Third, I suggest you to use this awesome jquery form validation library http://jqueryvalidation.org/
Good luck :)
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.
?>
This is a jQuery Mobile question, but it also relates to pure jQuery.
How can I post form data without page transition to the page set into form action attribute. I am building phonegap application and I don't want to directly access server side page.
I have tried few examples but each time form forwards me to the destination php file.
Intro
This example was created using jQuery Mobile 1.2. If you want to see recent example then take a look at this article or this more complex one. You will find 2 working examples explained in great details. If you have more questions ask them in the article comments section.
Form submitting is a constant jQuery Mobile problem.
There are few ways this can be achieved. I will list few of them.
Example 1 :
This is the best possible solution in case you are using phonegap application and you don't want to directly access a server side php. This is an correct solution if you want to create an phonegap iOS app.
index.html
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<style>
#login-button {
margin-top: 30px;
}
</style>
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3></h3>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>
check.php :
<?php
//$action = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
//$formData = json_decode($_REQUEST['formData']); // Decode JSON object into readable PHP object
//$username = $formData->{'username'}; // Get username from object
//$password = $formData->{'password'}; // Get password from object
// Lets say everything is in order
echo "Username = ";
?>
index.js :
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: {action : 'login', formData : $('#check-user').serialize()}, // Convert a form to a JSON string representation
type: 'post',
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
resultObject.formSubmitionResult = result;
$.mobile.changePage("#second");
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submitting
});
});
$(document).on('pagebeforeshow', '#second', function(){
$('#second [data-role="content"]').append('This is a result of form submition: ' + resultObject.formSubmitionResult);
});
var resultObject = {
formSubmitionResult : null
}
I have run into same issue where I am calling another .php page from my index.html.
The .php page was saving and retrieving data and drawing a piechart. However I found that when piechart drawing logic was added, the page will not load at all.
The culprit was the line that calls the .php page from my index.html:
<form action="store.php" method="post">
If I change this to:
<form action="store.php" method="post" data-ajax="false">
, it will work fine.
On using PHP and posting data
Use
data-ajax = "false" is the best option on <form> tag.
Problem is that JQuery Mobile uses ajax to submit the form. The simple solution to this is to disable the ajax and submit form as a normal form.
Simple solution: form action="" method="post" data-ajax="false"