I am working on a project where I allow the user to create enter one/many work experience details by dynamically adding form fields on click using a Bootstrap form. But am not sure of how to retrieve the values from these forms.
$(function()
{
$(document).on('click', '.btn-add', function(e)
{
e.preventDefault();
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.entry:not(:last) .btn-add')
.removeClass('btn-add').addClass('btn-remove')
.removeClass('btn-success').addClass('btn-danger')
.html('<span class="glyphicon glyphicon-minus"></span>');
}).on('click', '.btn-remove', function(e)
{
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="controls">
<li>
<form role="form" autocomplete="off" method="post" action="<?php echo site_url('studentDashboardController/saveUserResumeDetails')?>">
<div class="entry input-group col-xs-5">
<input class="form-control" name="fields0[]" type="text" placeholder="Work Experience Title" />
<input class="form-control" name="fields1[]" type="text" placeholder="Work Description" />
<input class="col-md-6" name="fields21[]" type="text" placeholder="From(Year)" />
<input class="col-md-6" name="fields22[]" type="text" placeholder="From(Month)" />
<input class="col-md-6" name="fields31[]" type="text" placeholder="To(Year)" />
<input class="col-md-6" name="fields32[]" type="text" placeholder="To(Month)" />
<span class="input-group-btn">
<button class="btn btn-success btn-add" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button>
</span>
</div>
</form>
</li>
<br>
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<!-- <a href="--><?php //echo base_url("/index.php/studentDashboardController/saveUserResumeDetails"); ?><!--" >-->
<button id="submit" name="submit" type="submit" class="btn btn-primary">Save Changes</button>
<!-- </a>-->
</div>
</div>
</div>
I'm working with the
CodeIgniter framework
PHP
MVC Architectureand
And the form above will basically be a part of my form and on submitting I call my controller studentDashboardController's saveUserResumeDetails method. From here, I'll be calling the userModel's saveUserResumeDetails method to store the user entered work experience detils into my studentprofile database table column.
The work experiences entered by the student will be stored in the following format inside the database table field.
work experience title - work description - 2015-08 - 2016-04,
another work experience title - work description - 2016-03 - 2016-09,
another work experience title - work description - 2014-10 - 2016-02,
Database studentprofile Table
Any suggestions in this regard will be highly appreciated.
In your Controller, post all data to your model:
$this->load->model('userModel');
$user = new userModel();
//print your post to debug, if necessary:
//print_r($this->input->post());
$user->saveUserResumeDetails($this->input->post());
In your model, You've got an array of each field:
public function saveUserResumeDetails($formData){
foreach ($formData["fields0"] as $value) {
echo "Filds0: $value<br />\n";
}
}
Related
I am using "Send Email from a Static HTML Form using Google Apps Mail" on my static site. But when I submit a form i have to refresh the whole page to submit another mail. If I don't reload the page success text don't vanish and send button don't work. So i am asking is there any way to refresh my form section without refreshing the whole page? please help me how to do it.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.0/dist/css/bootstrap.min.css"
integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
<div class="container mail text-center justify-content-center mt-5">
<div class="row">
<div class="col-12">
<h3>Contact Me Now!</h3>
<hr>
</div>
<div class="col-md-12 col-xs-12 form">
<form method="post" role="form"
action="https://script.google.com/macros/s/AKfycbwtLbTgUDGQxi9FY8Jks6bJs3TnYPBNU7rvO8b8_zrdyD4Pa6g/exec"
method="post" role="form" class="gform " data-email="">
<div class="form-row">
<div class="col form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name"
data-rule="minlen:4 " data-msg="Please enter at least 4 chars " required="true" />
</div>
<div class="col form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email"
data-rule="email " data-msg="Please enter a valid email " required="true" />
</div>
</div>
<div class="form-group">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject"
data-rule="minlen:4 " data-msg="Please enter at least 8 chars of subject "
required="true" />
</div>
<div class="form-group">
<textarea class="form-control" name="message" rows="5" data-rule="required"
data-msg="Please write something for me " placeholder="Message " required="true"></textarea>
</div>
<div class="text-center">
<button type="submit" class="btn btn-success w-100 submit">Send Message</button>
</div>
<div style="display:none" class="thankyou_message">
<div class="alert" role="alert"> <em>Thanks</em> for contacting me!
I will get back to you soon!<br>
<i class="fas fa-sync fa-spin"></i>
</div>
</div>
</form>
</div>
</div>
</div>
<script data-cfasync="false" type="text/javascript"
src="https://cdn.rawgit.com/dwyl/html-form-send-email-via-google-script-without-server/master/form-submission-handler.js"></script>
If the form is refreshing the page, you'll need to use preventDefault to cancel its default behaviour then use reset() to reset the form.
const form = document.querySelector('form');
form.addEventListener('submit', e => {
e.preventDefault();
[...form.elements].forEach(input => console.log(`${input.name}: ${input.value}`)); // Not Important
form.reset();
});
<form method="POST">
<input type="text" name="name" placeholder="name">
<input type="password" name="password" placeholder="password">
<button type="submit">Submit</button>
</form>
In JavaScript there is a function for forms which will reset the form clearing all the data in it, ready for another submit. This can be accomplished by running a JavaScript function on submit. This requires a couple changes in your code.
Firstly, we need to change this:
<button type="submit" class="btn btn-success w-100 submit">Send Message</button>
to this:
<button type="button" onclick="submitForm1()" class="btn btn-success w-100 submit">Send Message</button>
Once done, we can add some JavaScript to your page. If you have a JavaScript file linked to the page already, you can just add this code to that.
function submitForm1() {
let form = document.getElementsByClassName("gform");
form.submit();
form.reset();
}
You can also use document.getElementById("[id]"); and add an ID to your form. This is also preferable.
The first thing that comes to mind it's do all this on js so you can through ajax request send what you want. But I think it's not what you're looking for. You can't send data from page without refreshing, that's how it's work, php or html with some functional. You can change ...
<button type="button" class="btn btn-success w-100">Send Message</button>
... and collect all data by JavaScript and send it through ajax.
I am trying to use bootstrap spinner to load upon button click while flask is processing the request but it's not working.
When I click the button, the request is sent to flask and it never gets to the javascript part for some reason.
To confirm that, I tried the same HTML code below on a separate HTML page and it worked.
So my question is: how to make the javascript code work in conjunction with the request being sent to flask as well.
the HTML and Javascript part goes this way:
<div class="container-fluid mt-3">
<p class="font-weight-bold">Deactivate User</p>
<br>
<form action="{{ url_for('deactivate_user')}}" method='POST'>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">#</span>
</div>
<input type="text" class="form-control" placeholder="Username" id="username" name="username" required>
</div>
<button type="submit" id="submit" class="btn btn-info btn-primary">Submit</button>
</form>
</div>
<script>
$('#submit').click(function () {
this.form.submit();
this.disabled = true;
this.html = '<button class="btn btn-primary" type="button" disabled> <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span><span class="sr-only">Loading...</span></button>'
});
</script>
Am I doing something wrong? I am pretty new to HTML so excuse my ignorance in advance.
You can use ajax
<div class="container-fluid mt-3">
<p class="font-weight-bold">Deactivate User</p>
<br />
<div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">#</span>
</div>
<input
type="text"
class="form-control"
placeholder="Username"
id="username"
name="username"
required
/>
</div>
<button id="submit" class="btn btn-info btn-primary">
Submit
</button>
</div>
</div>
Then
<script>
$('#submit').click(function (d) {
let username = $('#username').val();
$.post(
"url_for_deactivate_user",
{
username: username,
},
function (data, status) {
// if (data) { // validate response data here
this.disabled = true;
this.html = `<button class="btn btn-primary" type="button" disabled> <span class="spinner-grow spinner-grow-sm" role="status" aria-hidden="true"></span><span class="sr-only">Loading...</span></button>
`;
// }
}
);
});
</script>
NOTE: Make sure you replace url_for_deactivate_user properly and also that your server gives a response.
Is it possible that an added dynamic fields will still visible after refresh.
I found a related topic but its complicated.
related topic
I want to implement it in my work.
fiddle
https://jsfiddle.net/jqj1h4vb/
Thanks
SCRIPT
$(function()
{
$(document).on('click', '.btn-add', function(e)
{
e.preventDefault();
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.voca:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
controlForm.find('.btn-add:not(:last)')
.removeClass('btn-default').addClass('btn-danger')
.removeClass('btn-add').addClass('btn-remove')
.html('<span class="glyphicon glyphicon-minus" aria-hidden="true"></span> Remove ');
}).on('click', '.btn-remove', function(e)
{
$(this).parents('.voca:first').remove();
e.preventDefault();
return false;
});
});
HTML
<div class="container">
<div class="control-group" id="fields">
<div class="controls">
<form role="form" autocomplete="off">
<div class="row">
<div class="voca">
<div class="col-md-3">
<input class="form-control" placeholder="Name this snippet" name="voca" type="text" value="Dynamic Form Fields - Add & Remove BS3">
</div>
<div class="col-md-3">
<input class="form-control" placeholder="Name this snippet" name="vocatrans" type="text" value="Dynamic Form Fields - Add & Remove BS3">
</div>
<div class="col-md-1">
<select class="form-control">
<option>1</option>
<option>2</option>
</select>
</div>
<button type="button" class="btn btn-success btn-add" >
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span> Add more
</button>
</div>
</div>
</form>
<br>
</div>
</div>
</div>
In your fiddle, the fields gets removed when the script is run again. I don't see the problem. And if the problem persist on your browser. Please use Ctrl + F5 to refresh.
You can archive this by two ways ..
Store value and data in session.
Store value and data in database.
And then after page load, you just fetch data from database or session
I want to do is to keep the email and password in the modal dialog login page if I click the checkbox button and if I refresh the same page and click the modal dialog again the email and password should be still there.
My problem is if I sign in in my login modal dialoge box and checked the keep me logged checkbox and click the button and refreshed the page again the email and password I've typed are gone it wasn't there anymore.
Does anyone here know how to keep what I typed in the email and password in my modal dialog box if I checked the checkbox keep me logged in button?
Whole html code:
<?php
session_start();
$unm=isset($_SESSION['email'])?$_SESSION['email']:'default_username';
$pwd=isset($_SESSION['password'])?$_SESSION['password']:'default_password';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="bootstrap/css/bootstrap.css" />
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="bootstrap/js/jquery-1.11.0.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript"> <!--submit form script-->
$(document).ready(function(){
$('#sumbit').on('click', function(){
window.location.replace("profile.php");
$('.modal').modal('hide');
});
$('[name="chkbox"]').on('click', function(){
$.post( "savestate.php", { email: $('[name="email"]').val(), email: $('[name="password"]').val() }).done(function( data ) {
alert( "Data Loaded: " + data );
});
});
});
</script>
</head>
<body>
<a data-toggle="modal" href="#myModal"><span class="glyphicon glyphicon-user"></span> Login</a>
<div class="container">
<div class="row">
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h5 class="modal-title">PLEASE ENTER YOUR EMAIL ADDRESS AND PASSWORD TO LOG IN.</h5>
</div>
<div class="modal-body">
<form class="form-horizontal">
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-envelope-o fa-fw"></i></span>
<input type="text" name="email" value="<?php echo $unm; ?>" class="form-control" placeholder="Enter Email Address..." />
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-md-9">
<div class="input-group">
<span class="input-group-addon"><i class="fa fa-key fa-fw"></i></span>
<input type="password" name="password" value="<?php echo $pwd; ?>"" class="form-control" placeholder="Enter Password..." />
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="checkbox" name="chkbox" value="staylogged" class="checkbox-inline" />
<label> Keep me logged in</label> <b>|</b>
Forgot your password?
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" id="submit" name="login" class="btn btn-primary" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-user"></span> Login</button>
<button type="button" id="show_signup_md" class="btn btn-info" data-dismiss="modal" aria-hidden="true"><span class="glyphicon glyphicon-list-alt"></span> Register</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
savestate.php
<?php
session_start();
$_SESSION['email']=$_POST['email'];
$_SESSION['password']=$_POST['password'];
$unm=isset($_SESSION['email'])?$_SESSION['email']:'default_username';
$pwd=isset($_SESSION['password'])?$_SESSION['password']:'default_password';
?>
You set variables in server side when user clicks check button.Probably by using AJAX.
And then use them in your page when you display the page.
Here is jquery:
$(document).ready(function(){
$('#sumbit').on('click', function(){
window.location.replace("profile.php");
$('.modal').modal('hide');
});
$('[name="chkbox"]').on('click', function(){
if(!$(this).attr('checked'))return;
$.post( "/savestate.php", { email: $('[name="email"]').val(), password: $('[name="password"]').val() }).done(function( data ) {
// alert( "Data Loaded: " + data );
});
});
});
Here is savestate.php
session_start();
$_SESSION['email']=$_POST['email'];
$_SESSION['password']=$_POST['password'];
You can reuse in your php page as
$unm=isset($_SESSION['email'])?$_SESSION['email']:'default_username';
$pwd=isset($_SESSION['password'])?$_SESSION['password']:'default_password';
Why don't use instead jQuery's plugin for cookies?
http://plugins.jquery.com/cookie/
In general terms, it is a really bad practice to store the password in the cookie but if you wan't to do it, I'm no one to tell you not to do it.
Another better solution will be store the information in the session of PHP. Here is a good tutorial of this. Although a still better solution will be store the session in database, so your app is stateless.
Using jQuery's plugin will be as easy as:
jQuery(function () {
$("#email").val($.cookie("unm"));
$("#password").val($.cookie("pwd"));
});
In this way, if there is something in the cookie, the value will be that, otherwise, will be blank. Or you can do
$("#email").val($.cookie("unm") || "Default value for usermane");
To set a default value if the return of that cookie is null (or empty).
You can also use local storage (http://www.w3schools.com/html/html5_webstorage.asp) but I recommend using a server side option.
I have a form which i validate via php. this is how i do it:(example is for one 1 field)
elseif (ctype_alpha($firstname) != true)
{
$err_alpha_firstname = "First Name cannot contain numbers";
}
If in case the user does use an alpha numeric firstname, i display the error as :
<p><input type="text" class="span2" maxlength = "20" name="firstname" required id="firstname" placeholder="First Name"></p>
<?php if (isset($err_alpha_firstname)) {echo $err_alpha_firstname;}?>
It all works fine. however since this validation is server side via php, inorder for the errors to show up, i have to submit the form, which then reloads( since the form submits to the page itself) and then the errors are displayed. Now I want those errors which are stored in a php variable ex:$err_alpha_firstname , to be displayed instantaneously via javascript or ajax (i dont know anything about either of the languages so pardon me please). Is there a simple script that would let me display those errors on the fly? I know php is server side and javascript is client side so there might be an issue.
html file:
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../docs-assets/ico/favicon.png">
<title>Fantasy Football</title>
<!-- Bootstrap core CSS -->
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="bootstrap/css/jumbo.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="jumbotron.css" rel="stylesheet">
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Fantasy Football</a>
</div>
<div class="navbar-collapse collapse">
<form class="navbar-form navbar-right" method="post" action="checkuser.php" name="check_form">
<div class="form-group">
<input type="text" placeholder="Username" name ="username" id="username" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" name="password" id="password" class="form-control">
</div>
<input type="hidden" name="action" value="submit" />
<button type="submit" class="btn btn-success">Sign in</button>
Forgot Password?
</form>
</div>
</div>
</div>
<div class="jumbotron">
<div class="container">
<h1>Fantasy Football</h1>
<p>Bring out the football manager in you!</p>
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Register »
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">New User Registration</h4>
</div>
<div class="modal-body">
<form class="form-inline" method="post" action="<?php echo $_SERVER['PHP_SELF']?>" name="login_form">
<span id="formerror" class="error"></span>
<p><input type="text" class="span2" maxlength = "20" name="firstname" required id="firstname" placeholder="First Name"></p>
<?php if (isset($err_alpha_firstname)) {echo $err_alpha_firstname;}?>
<p><input type="text" class="span2" maxlength = "20" name="lastname" required id="lastame" placeholder="Last Name"></p>
<?php if (isset($err_alpha_lastname)) {echo $err_alpha_lastname;}?>
<p><input type="text" class="span2" maxlength = "20" name="username" required id="username" placeholder="Username"></p>
<?php if (isset($err_ln_username)) {echo $err_ln_username;}?>
<?php if (isset($err_empty_username)) {echo $err_empty_username;}?>
<?php if (isset($err_alnum_username)) {echo $err_alnum_username;}?>
<?php if (isset($err_unp)) {echo $err_unp;}?>
<p class="help-block" style="font-size:12px"> Username should be between 4-20 characters long.</p>
<p><input type="password" class="span2" name="password" placeholder="Password"></p>
<?php if (isset($err_unp)) {echo $err_unp;}?>
<?php if (isset($err_ln_password)) {echo $err_ln_password;}?>
<?php if (isset($err_alnum_password)) {echo $err_alnum_password;}?>
<p class="help-block" style="font-size:12px"> Password must be between 4-20 characters long. Must be alpha-numeric</p>
<p><input type="password" class="span2" name="password_conf" placeholder="Re - Enter Password"></p>
<?php if (isset($err_passwordconf)) {echo $err_passwordconf;}?>
<p><input type="email" class="span4" name="emailid" required id="emailid" placeholder="Email ID"></p>
<p><input type="text" class="span2" name="team_name" required id="team_name" placeholder="Team name"></p>
<p class="help-block" style="font-size:12px"> Select your Unique team name.</p>
<p>
<select class="secret_question">
<option>Select one of the below ....</option>
<option value ="0">The name of the city where you were born</option>
<option value ="1">The name of your first pet</option>
<option value ="2">What is your mother's maiden name</option>
</select>
</p>
<p><input type="text" class="span2" name="secret_answer" required id="secret_answer" placeholder="Secret Answer"></p>
<p><input type="hidden" value="submit" /><br />
<button type="submit" name="action" value = "submit" class="btn btn-primary">Register</button></p>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<h2>Rules</h2>
<p>Rules of the Game </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Meet The Developers</h2>
<p>Everyones name get mentioned here </p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
<div class="col-md-4">
<h2>Contact Us</h2>
<p>have an issue with the game. Click here to contact us.</p>
<p><a class="btn btn-default" href="#" role="button">View details »</a></p>
</div>
</div>
<hr>
<footer>
<p>© B561 Project Fall 2013</p>
</footer>
</div>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<?php include('newuseradd.php');?>
</body>
</html>
You could either use straight JavaScript or AJAX to PHP.
I'm going to show you the straight JS method.
You'd do something like this for each input.
var hint = $("#fname-hint");
var fname = $("#firstname");
fname.on("change", function(){
if (!this.value.match(/\d+/g)) { // dosen't contain numbers
hint.html("");
fname.removeClass("error");
}
else {
fname.addClass("error");
hint.html("Your name can't contain numbers!");
}
});
Now when the form is submitted, make sure there are no errors:
var form = $("#form");
form.submit(function(e) {
var inputs = form.children("input");
inputs.each(function(){
var input = $(this);
if (!input.hasClass("error")) {
alert("Errors in form!");
input.select();
e.preventDefault();
break;
}
});
});
I use the jQuery $.post() function and return json from my php code:
function fail ($message){
die(json_encode(array('status'=>'fail', 'message'=>$message)));
}
function success ($message){
die(json_encode(array('status'=>'success', 'message'=>$message)));
}