Dynamic HTML form input depending on SQL query results - javascript

I have an HTML form that allows users to enter a nickname and choose a gender to connect.
Code
<form class="form-horizontal" role="form" action="start" method="post">
<fieldset>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="nickname">Nickname</label>
<div class="col-sm-10">
<input id="nickname" name="nickname" type="text" class="form-control" required="required">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label" for="gender">Gender</label>
<div class="col-sm-10">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default btn-lg">
<input type="radio" name="username" value="Female" id="username"> <i class="fa fa-female"></i> Female
</label>
<label class="btn btn-default btn-lg">
<input type="radio" name="username" value="Male" id="username"> <i class="fa fa-male"></i> Male
</label>
</div>
</div>
</div>
<!-- Button -->
<div class="form-group">
<label class="col-sm-2 control-label" for="button"></label>
<div class="col-sm-offset-2 col-sm-10">
<button id="button" class="btn btn-lg btn-primary" type="submit">Enter</button>
</div>
</div>
</fieldset>
</form>
Screenshot
Question
Once the nickname input field has been completed by the user, I want to run a SQL query:
SELECT COUNT(u.id) FROM users u WHERE u.nickname = **value_of_input_field**
if the SQL result is >0:
then a password input field should magically appear between the nickname and gender fields.
How on earth can I accomplish this?
I have no idea where to even start looking or what to look for, so any pointers, suggestions etc. are very welcome but code examples would be even better.

Disclaimer: I didnt test this but I think if it doesnt work, it is close enough to get you going.
You would have a css class
.hiding{
display: none;
}
Your html snippet would look something like this:
<form method="post">
<input name="nickname" type="text" id="nickname">
<input name="password" type="text" id="password" class="hiding">
<input> <!-- other buttons and form elements -->
</form>
The js would look something like this (assuming you have included jquery)
<script type="text/javascript">
$(document).ready(function(){
//other jquery/js stuff
$("#nickname").change(function(){
var nick = $(this).val();
$.ajax({
type: "POST",
data: {
nickname: nick
},
url: "actions/validate.php",
dataType: "text",
success: function(data){
if(data>0){
$("#password").removeClass("hiding");
}
}
});
});
});
</script>
and the php would look something like this
<?php
//connect to db
$nickname= $_POST["nickname"];
$sql = "SELECT COUNT(u.id) FROM users u WHERE u.nickname = '".$nickname."'";
$result = mysql_query($sql);
$numRows = mysql_num_rows($result);
echo $numRows;
//disconnect to db
?>

Related

How to validate a form in a bootstrap modal using PHP?

As soon as the form is submitted, the form is not validated and the modal is closed because the page is refreshed. I want the modal to stay open on submitting the form. The php is given below:
<?php
$nameerror = $studentiderror = $emailerror = "";
$subject = "Thank you for voting!";
$body = "Dear $_POST["name"], Thank you for voting for this sustainable initiative. Your vote is appreciated! Lots of love from the Beefarm Committee of the Erasmus Sustainability Hub!";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["submit"]) {
if (empty(($_POST["name"])) {
$nameerror = "Please enter your name" }
if (empty($_POST["studentID"])) {
$studentiderror .= "Please enter your student ID";
} else {
$result = "Thank you for voting!";
mail($_POST["email"], $subject, $body);
}
};
}
Here is the HTML of the modal, the PHP is embedded in the HTML, where the error messages should be shown when the form is validated after submission:
<div class="container">
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">x</button>
<h4 class="modal-title">Vote!</h4>
</div>
<div class="modal-body">
<p>
Let us know what you think! <br/>
By voting, you as a student can have a say in the realisation of this project. Even if you vote
against having bees on campus, your vote is appreciated! <br/>
Thank you!
</p>
<form id="votingscreen" method="POST">
<?php echo $result ?>
<div class="form-group">
<label for="name">Name</label>
<?php echo $nameerror ?>
<input style="width: 180px" type="text" id="name" name="name" class="form-control" placeholder="Your name">
</div>
<div class="form-group">
<label for="studentID">Student ID</label>
<?php echo $studentiderror ?>
<input style="width: 180px" type="text" id="studentID" name="studentID" class="form-control" placeholder="123456AB">
</div>
<div class="form-group">
<label for="email">E-mail</label>
<?php echo $emailerror ?>
<input style="width: 180px" type="email" id="email" name="email" class="form-control" placeholder="E-mail">
</div>
<hr />
<div class="radiogroup">
<label for="radiogroup"> Bees on campus? </label>
<label class="radio-inline">
<input type="radio" name="vote" id="voteyesradio" value="yes" checked>
Yes
</label>
<label class="radio-inline">
<input type="radio" name="vote" id="votenoradio" value="no">
No
</label>
</div>
<div class="form-group">
<input type="submit" name="submit" id="submitButton" class="btn btn-success btn-block" value="Vote!"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
This is the JS code:
$(".contentContainer").css("min-height", $(window).height());
$("#image").css("min-height", $("#beeweek").height());
$(document).ready(function () {
$("#submitButton").click(function () {
$("#myModal").modal('show');
})
});
$(".video-container").css("min-height", $(window).height());
If you don't want the page being refreshed, you should submit your form using Ajax, this link should help you, jQuery Ajax POST example with PHP

How to make a second submit button?

I have a classic form that submits data to a controller. Nothing special until here.
The thing is I want a second button, let's say "Save and Exit" that I want to also submit and redirect to home page.
How could I do that? I guess this includes a little javascript for checking?
I just can't wrap my head around it. Thank you!
<form method="POST" action="link/here" id="main_form" class="form-horizontal">
<input name="_token" value="JDtRMqc4aRFlK4QFzDPRTxKvNxIj5EnoLOceOUBT" type="hidden">
<div class="box-body">
<div class="form-group">
<label for="url" class="col-sm-3 control-label">Figura</label>
<div class="col-sm-9">
<input class="form-control" id="Figura" name="figura" placeholder="Figura" value="" type="text">
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-3 control-label">Parcela</label>
<div class="col-sm-9">
<input class="form-control" id="Parcela" name="parcela" placeholder="Parcela" value="" type="text">
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-3 control-label">Rand</label>
<div class="col-sm-9">
<input class="form-control" id="Rand" name="rand" placeholder="Rand" value="" type="text">
</div>
</div>
<div class="form-group">
<label for="url" class="col-sm-3 control-label">Nr. Locuri</label>
<div class="col-sm-9">
<input class="form-control" id="Locuri" name="locuri" placeholder="Locuri" value="" type="text">
</div>
</div>
<div id="locuri_div" class="col-sm-offset-1"></div>
<div class="pull-right">
<button type="submit" class="btn btn-success">Salveaza</button>
</div>
<div class="pull-left">
Inapoi
</div>
</div>
<!-- /.box-body -->
</form>
your current button :
<button type="submit" name="check" value="0" class="btn btn-success">Save</button>
add a new one:
<button type="submit" name="check" value="1" class="btn btn-success">Save and Exit</button>
then in your save.php do:
if($_POST['check'] == 0){
//redirect to page
}
else{
//redirect to home
}
Give each button a name and a value. In your controller (client-side JS is the wrong tool for this), test the name and then redirect based on that.
For example:
<button name="action" value="save">Save</button>
<button name="action" value="save_and_go_home">Save & Go Home</button>
And then (to use expressjs as an example):
app.post('/here', function (req, res) {
// Do everything else you want to do with the data
// Then
var action = req.body.action;
if (action === "save_and_go_home") {
res.redirect("/");
} else {
res.send('Whatever you were sending before')
}
});

Data From Svc Not Modeling Into View Elements AngularJS

I have a view that is modeled to functions which pass data through to a database. This is all working and I see the data coming back when called, but it is not pre-populating the fields in my view when it comes back. I've been banging my head for a while on this. Everything is modeled (from what I can tell) properly.
I have stepped through the JS code below in Chrome and see the data being assigned to my $scope variables from the data.XXX return.
But, after load finishes, it's not preselecting my radio button or populating the fields with the data. Any help greatly appreciated.
Here is the View:
<div class="notification-container">
<form name="notificationForm" class="form-horizontal" ng-submit="saveQrNotifications()">
<div class="list-unstyled">
<input id="text" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="text" type="radio" ng-value="1001"> Text Message<br>
<input id="email" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="email" type="radio" ng-value="6"> Email<br>
<input id="voice" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="voice" type="radio" ng-value="1003"> Voice<br>
<input id="nocontact" ng-model="NotificationMethods.NotificationMethodId" ng-change="notifyVisible()" name="nocontact" type="radio" ng-value="1000"> Do Not Contact<br>
</div>
<div class="col-md-12 notification-fields" ng-show="notifyFieldVisibility == true">
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '1001'">
<label class="notication-input">Text Number</label>
<span class="clearfix"></span>
<input class="form-control area-code" type="text" ng-model="NotificationMethods.NotificationTextAreaCode" placeholder="(555)" required>
<input class="form-control phone-number" type="text" ng-model="NotificationMethods.NotificationTextPhoneNumber" placeholder="555-5555" required>
</div>
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '6'">
<label class="notification-input" for="email">E-mail Address
<input class="form-control" id="email" name="email" type="text" ng-model="NotificationMethods.NotificationEmailAddress" placeholder="ex.me#example.com" required>
</label>
</div>
<div class="col-md-12" ng-if="NotificationMethods.NotificationMethodId == '1003'">
<label class="notication-input">Voice Number </label>
<span class="clearfix"></span>
<input class="form-control area-code" type="text" ng-model="NotificationMethods.NotificationVoiceAreaCode" placeholder="(555)" required>
<input class="form-control phone-number" type="text" ng-model="NotificationMethods.NotificationVoicePhoneNumber" placeholder="555.5555" required>
<label class="small">Ext.</label>
<input class="form-control extension" type="text" ng-model="NotificationMethods.NotificationVoiceExtension" placeholder="555">
</div>
<span class="clearfix"></span>
<div ng-show="notifyLoading" class="text-center" style="margin-top: 10px;">
<i class="fa fa-spinner fa-spin"></i> Saving...
</div>
<div class="col-md-12">
<button type="submit" class="btn btn-primary notification-btn">Save Notifications</button>
</div>
</div>
</form>
</div>
Here is my controller:
DATA COMING FROM DB:
if (data.StatusCode == "SUCCESS") {
$scope.refill = data;
//$scope.deliverTypes = data.DeliveryTypes;
$scope.showError = false;
$scope.submitRefill = true;
$scope.findRefillStatus = userMessageService.QuickRefillMessage(data.Prescriptions[0]);
$scope.isRefillable = data.Prescriptions[0].IsRefillable;
$scope.prescription.noPrescription.$valid = true;
$scope.loading = false;
$scope.NotificationMethods.NotificationEmailAddress = data.NotificationEmailAddress;
$scope.NotificationMethods.NotificationMethodId = data.NotificationMethodId;
$scope.NotificationMethods.NotificationTextAreaCode = data.NotificationTextAreaCode;
$scope.NotificationMethods.NotificationTextPhoneNumber = data.NotificationTextPhoneNumber;
$scope.NotificationMethods.NotificationVoiceAreaCode = data.NotificationVoiceAreaCode;
$scope.NotificationMethods.NotificationVoicePhoneNumber = data.NotificationVoicePhoneNumber;
$scope.NotificationMethods.NotificationVoiceExtension = data.NotificationVoiceExtension;
}
Figured it out. I was declaring the controller on the view used in ng-include. Removing that and letting the view inherit controller from surrounding view solved issue.

fileupload is not working in twitter bootstrap

I am using twitter bootstrap file upload, i want to store the image on databese and also i want to move in one folder,i spent lot of times, i can't get the file name value. see here enter firstname and select one image after submit the form ,now i got first name value but i cant get photo upload value...
<form class="form-horizontal form-bordered" method="POST" id="newUserForm" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-3 control-label">First Name<span class="star_mark"> *</span></label>
<div class="col-sm-6">
<input type="text" class="form-control" id="fname" name="fname" value="" aria-required="true" required="" data-msg-required="Please enter your firstname" placeholder="Enter your firstname">
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Photo Upload<span class="star_mark"> *</span></label>
<div class="col-md-6">
<div class="fileupload fileupload-new" data-provides="fileupload">
<div class="input-append">
<div class="uneditable-input">
<i class="fa fa-file fileupload-exists"></i>
<span class="fileupload-preview"></span>
</div>
<span class="btn btn-default btn-file">
<span class="fileupload-exists">Change</span>
<span class="fileupload-new">Select file</span>
<input type="file" id="file" name="file">
</span>
Remove
</div>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-6">
<button class="btn btn-info btn-block" type="submit" id="user-submit">Submit</button>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#user-submit').click(function(event){
event.preventDefault();
if($('#newUserForm').valid()){
//console.log('success');
$.ajax({
type:'POST',
url :"php/register-newuser.php",
data: $('form#newUserForm').serialize(),
success: function(data) {
//var res=jQuery.parseJSON(data);// convert the json
console.log(data);
},
error:function(exception){
alert('Exeption:'+exception);
}
});
}
else{
console.log('please select all fields');
}
});
});
</script>
register-newuser.php
$fstname=$_POST['fname'];// i got ans here
$filename = basename($_FILES['file']['name']);
$newuser = array("fstName" => $fstname,'photoname' => $filename);
echo json_encode($newuser);
print_r($_FILES)//means nothing will happen, i didn't get any value like filename,size,extension....
To make an upload with AJAX you can use a jQUery plugin, for example this one. Bootstrap has nothing to do with upload.

Ajax callback only applying to top div in list of jquery form groups

Hello smarter people,
So as the title conveys, i'm having some difficulties, and I've wasted a good 8 hours trying to figure it out :)
I posted a Question earlier, to which I got no answers. I was having difficulties with my ajax, and it's interaction with a form. This form is in an admin panel, and is for dynamically creating and editing navigation links on the front end of my (hopefully) soon-too-be site.
My problem specifically is: I am unable to, via ajax, have the text-content of the anchor tag (which causes the form to dropdown), to immediately reflect on screen...
http://i1379.photobucket.com/albums/ah126/conchairtoe/3_zpsb897a6a4.png
As you can see, the ajax has run, no errors, yet the label (anchor tag for enacting drop-down form) remains "test", when I typed "testing!!!!!!" in.
Everything behind the scenes worked, as the database successfully updates the corresponding data, and so does the anchor tag text once i reload the page, but that ain't very ajaxy now is it!
Here's the Javascript for when the form is submitted.
// NAV ITEM FORM - UPDATE / SUBMIT
$(".nav-form").submit(function(event) {
var navData = $(this).serializeArray(); // The serializeArray( ) method serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with.
var navLabel = $('input[name=label]').val();
var navID = $('input[name=id]').val();
$.ajax({
url: "ajax/navigation.php",
type: "POST",
data: navData
}).done(function(){
$("#label_"+navID).html(navLabel);
}); // END $.ajax
alert("navID = "+navID+" navLabel = "+navLabel);
event.preventDefault(); // will prevent form from submitting
});//END nav-form
Please note the .done callback.
I've narrowed the problem down!
The ajax works ONLY on whichever of the sortable anchors is in position 1 (the top of the list) - for when I change the "Home Page", or, again, which ever one I happen to move to the top of the list, the label updates immediately as per the ajax.
As you can see in the code, I have those alerts to verify this:
http://i1379.photobucket.com/albums/ah126/conchairtoe/final_zps7a7ddc68.png
Here is the code for the DOM environment
Navigation
<div class="row">
<div class="col-md-3">
<ul id="sort-nav" class="list-group-item">
<!--EXISTING NAV-ITEMS-->
<?php
$query = "SELECT * FROM navigation ORDER BY position ASC";
$result = mysqli_query($dbc, $query);
while ($list = mysqli_fetch_assoc($result)) { ?>
<li id="list_<?php echo $list['id']; ?>" class="list-group-item">
<a id="label_<?php echo $list['id']; ?>" data-toggle="collapse" data-target="#form_<?php echo $list['id']; ?>">
<?php echo $list['label']; ?> <i class="fa fa-chevron-down"></i>
</a>
<div id="form_<?php echo $list['id']; ?>" class="collapse">
<!--FORM-->
<form class="form-horizontal nav-form" role="form" action="index.php?page=navigation&id=<?php echo $list['id']; ?>" method="post">
<!-- ID -->
<div class="form-group">
<label class="col-sm-2 control-label" for="id">ID</label>
<div class="col-sm-10">
<input type="text" class="form-control input-sm" value="<?php echo $list['id'];?>" name="id" id="id" placeholder="ID - name" />
</div>
</div>
<!-- LABEL -->
<div class="form-group">
<label class="col-sm-2 control-label" for="label">Label</label>
<div class="col-sm-10">
<input type="text" class="form-control input-sm" value="<?php echo $list['label'];?>" name="label" id="label" placeholder="Label" />
</div>
</div>
<!--URL -->
<div class="form-group">
<label class="col-sm-2 control-label" for="value">URL</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['url'];?>" name="url" id="url" placeholder="URL"></input>
</div>
</div>
<!--POSITION -->
<div class="form-group">
<label class="col-sm-2 control-label" for="value">Position</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['position'];?>" name="position" id="position" placeholder="Position"></input>
</div>
</div>
<!-- STATUS -->
<div class="form-group">
<label class="col-sm-2 control-label" for="status">Status</label>
<div class="col-sm-10">
<input class="form-control input-sm" type="text" value="<?php echo $list['status'];?>" name="status" id="status" placeholder=""></input>
</div>
</div>
<!--Button and Hidden Input-->
<button type="submit" class="btn-btn-default">Save</button>
<input type="hidden" name="submitted" value="1" />
<input type="hidden" name="opened_id" value="<?php echo $list['id']; ?>" />
<span class="pull-right">
<a id="del_<?php echo $list['id']; ?>" class="btn btn-danger nav-item-delete" href="#" style="margin-bottom: 2px;" title="delete nav item"><i class="fa fa-trash"/></i></a>
</span>
</form> <!--END form-->
</div>
</li>
<?php } ?>
</ul>
</div>
<div class="col-md-9">
<div id="callback"><?php if(isset($message)) { echo $message; } ?></div>
</div> <!-- END col-md-12 -->
So yea, I truly apologize for my ignorance. Bare in mind that I barely could grasp css just 2 months ago or so.
THANK YOU SO MUCH FOR YOUR HELP IF YOU CAN PROVIDE IT.
Because you are not looking at the current form for the navID. The code $('input[name=id]') is using the first element it finds. You need to look at the form, use find().
var form = $(this);
var navData = form.serializeArray();
var navLabel = form.find('input[name=label]').val();
var navID = form.find('input[name=id]').val();

Categories