I have a bootstrap form the info from which I am saving to a json file using an ajax call.
My problem is that when I press the Submit button the page seems to refresh after the call(executed after the submit button is clicked), which is something i'd definitely like to avoid.
I tried to investigate the problem, but my knowledge is insufficient for that as I don't have an indepth understanding of any of these concepts.
Here is my BS form :
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Full Name:</label>
<div class="col-sm-2">
<input type="name" class="form-control" id="nameFull">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="phone">Phone:</label>
<div class="col-sm-2">
<input type="phone" class="form-control" id="phoneApp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-2">
<input type="email" class="form-control" id="emailApp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date">Date:</label>
<div class="col-sm-2">
<input type="date" class="form-control" id="date">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Hour:</label>
<div class="col-sm-2">
<select class="form-control" id="time">
<option value="Time" class="">Time</option>
<option value="10am" class="">10:00-10:30</option>
<option value="1030am" class="">10:30-11:00</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="reason">Reason:</label>
<div class="col-lg-3">
<textarea class="form-control" id="reason" name="comments" placeholder="Describe the reason to make an appointment here. Please, include symptoms and any historical data that may help us determine your case." rows="5"></textarea><br>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="saveAppt" class="btn btn-default">Submit</button>
</div>
</div>
</form>
And here is the ajax call :
$(document).ready(function() {
$("#saveAppt").click(function(){
var fullName = $("#nameFull").val();
var userName = $("#cpr").val();
var phone = $("#phoneApp").val();
var email = $("#emailApp").val();
var date = $("#date").val();
var time = $("#time").val();
var reason = $("#reason").val();
console.log(time);
console.log(date);
console.log(reason);
var jAppointment= {};
jAppointment.fullName = fullName;
jAppointment.userName = userName;
jAppointment.phone = phone;
jAppointment.email = email;
jAppointment.date = date;
jAppointment.time = time;
jAppointment.reason = reason;
console.log(JSON.stringify(jAppointment));
$.ajax
({
type: "GET",
dataType : 'json',
async: false,
url: 'save-appointments.php',
data: { data: JSON.stringify(jAppointment) },
success: function () {console.log("Thanks!"); },
failure: function() {console.log("Error!");}
});
});
});
Now what the submit action refresh your page the click event will never be raised since the <button> tag has type='submit' by defaul just add type='button' type to avoid submit/refresh :
<button type="button" id="saveAppt" class="btn btn-default">Submit</button>
Hope this helps.
$(document).ready(function() {
$("#saveAppt").click(function(){
var fullName = $("#nameFull").val();
var userName = $("#cpr").val();
var phone = $("#phoneApp").val();
var email = $("#emailApp").val();
var date = $("#date").val();
var time = $("#time").val();
var reason = $("#reason").val();
console.log(time);
console.log(date);
console.log(reason);
var jAppointment= {};
jAppointment.fullName = fullName;
jAppointment.userName = userName;
jAppointment.phone = phone;
jAppointment.email = email;
jAppointment.date = date;
jAppointment.time = time;
jAppointment.reason = reason;
console.log(JSON.stringify(jAppointment));
$.ajax
({
type: "GET",
dataType : 'json',
async: false,
url: 'save-appointments.php',
data: { data: JSON.stringify(jAppointment) },
success: function () {console.log("Thanks!"); },
failure: function() {console.log("Error!");}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="name">Full Name:</label>
<div class="col-sm-2">
<input type="name" class="form-control" id="nameFull">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="phone">Phone:</label>
<div class="col-sm-2">
<input type="phone" class="form-control" id="phoneApp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="email">Email:</label>
<div class="col-sm-2">
<input type="email" class="form-control" id="emailApp">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date">Date:</label>
<div class="col-sm-2">
<input type="date" class="form-control" id="date">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Hour:</label>
<div class="col-sm-2">
<select class="form-control" id="time">
<option value="Time" class="">Time</option>
<option value="10am" class="">10:00-10:30</option>
<option value="1030am" class="">10:30-11:00</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-lg-2" for="reason">Reason:</label>
<div class="col-lg-3">
<textarea class="form-control" id="reason" name="comments" placeholder="Describe the reason to make an appointment here. Please, include symptoms and any historical data that may help us determine your case." rows="5"></textarea><br>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type='button' id="saveAppt" class="btn btn-default">Submit</button>
</div>
</div>
</form>
<br><br><br><br><br><br>
Crate a reference to your event in your click handler.
$("#saveAppt").click(function(e){
then call the preventDefault function on that event after your AJAX call.
$.ajax
({
type: "GET",
dataType : 'json',
async: false,
url: 'save-appointments.php',
data: { data: JSON.stringify(jAppointment) },
success: function () {console.log("Thanks!"); },
failure: function() {console.log("Error!");}
});
e.preventDefault();
Related
I am trying to fetch the data from a form and posting it to server in JSON format. I am facing problem that values of dynamically generated input fields are not getting fetched, only the value of fields that are static and defined in HTML page is getting fetched.
Below is my HTML code of form
<form class="form-horizontal" id="product-form">
<div class="form-group">
<label class="control-label col-sm-2">Category</label>
<div class="dropdown col-sm-2">
<select class="form-control" id="categories" onchange="displaySub()">
<option value="-1">-- Select Category --</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Sub-category</label>
<div class="dropdown col-sm-2">
<select class="form-control" id="sub-categories" name="category" onchange="displayFields()">
<option value="-1">-- Select Sub-category --</option>
</select>
</div>
</div>
</form>
jQuery code that is generating dynamic input fields
function displayFields(){
var cat_dropdown = document.getElementById("sub-categories");
var cat_selected = cat_dropdown.options[cat_dropdown.selectedIndex].text;
for(d of sub_cat){
if(d.text == cat_selected){
for(e of d.fields){
$("#product-form").append(`
<div class="form-group">
<label class="control-label col-sm-2" for="${e.field}" name="${e.field}">${e.field}</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="${e.field}" placeholder="Enter ${e.field}">
</div>
</div>
`)
}
$("#product-form").append(`
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button class="btn btn-default" id="add-product">Add Product</button>
</div>
</div>
`)
}
}
}
JS code for form submission
$("#product-form").submit(function(e){
e.preventDefault();
var form = $(this);
var data = form.serializeArray();
$.ajax({
url: 'http://localhost:3000/products',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(getFormData(data)),
success: function(data){
console.log("DATA POSTED SUCCESSFULLY"+data);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
});
function getFormData(data) {
var unindexed_array = data;
var indexed_array = {};
$.map(unindexed_array, function(n, i) {
indexed_array[n['name']] = n['value'];
});
return indexed_array;
}
Now, whenever I submit form only the category field is fetched. I want all the field values that are generated dynamically.
Problem is resolved. I gave name attribute to label instead of giving it to input field getting generated dynamically.
Previous code
$("#product-form").append(`
<div class="form-group">
<label class="control-label col-sm-2" for="${e.field}" name="${e.field}">${e.field}</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="${e.field}" placeholder="Enter ${e.field}">
</div>
</div>
`)
Rectified Code
$("#product-form").append(`
<div class="form-group">
<label class="control-label col-sm-2" for="${e.field}">${e.field}</label>
<div class="col-sm-2">
<input type="text" class="form-control" id="${e.field}" name="${e.field}" placeholder="Enter ${e.field}">
</div>
</div>
`)
Here is my javascript code. The commented line works:
$("#regForm").submit(function(event) {
// event.preventDefault()
password = $("#inputPassword3")
login = $("#inputEmail3")
user_instance = 0
$.ajax({
url: "{{ url_for('get_users') }}",
method: 'POST'
}).done(function(data) {
data.forEach(function(item) {
if (item.username == login.val() || item.mail == login.val()) {
user_instance = item
}
})
pass_arr = sjcl.hash.sha256.hash(password.val())
hash = sjcl.codec.hex.fromBits(pass_arr)
console.log(hash, user_instance.passwd)
if (hash != user_instance.passwd) {
event.preventDefault()
console.log("+")
password.attr("style", "border:#f00 solid 1px")
password.attr("placeholder", "Wrong password")
}
event.preventDefault() is not working here:
<div id="regForm">
<form class="form-horizontal" method="POST" action="{{ url_for('login') }}">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Email/Login</label>
<div class="col-sm-10">
<input type="imput" class="form-control" id="inputEmail3" placeholder="Email/Login" name="email">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="inputPassword3" placeholder="Password" name="password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me"> Remember me
</label>
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default" name="sign-in">Sign in</button>
</div>
</div>
</form>
It submits form anyway, even though color of form changing, why is that? When uncommented preventDefault() is working as should be
Try this
$('body').on('submit', 'YOUR-ID' ,function(event) {}
I am trying to update information clicking on edit change button. After updating the information, I want the updated information to be shown by hiding the form, when I click on Save Changes button. My api is working and information is getting updated.But ng-if is not working after clicking Save Changes button.
info.html file
<div class="panel-body" ng-if="userEnteredInfo">
<div class="form-group">
<dl class="dl-horizontal form-info-table">
<dt>First Name:</dt>
<dd>{{user.basicInfo.firstName}}
</dd>
<dt>Last Name:</dt>
<dd>{{user.basicInfo.lastName}}</dd>
<dt>Status:</dt>
<dd>{{user.basicInfo.status}}</dd>
<dt>Work Location:</dt>
<dd>{{user.basicInfo.workLocation}}</dd>
<dt>Date of Birth:</dt>
<dd>{{user.basicInfo.dateOfBirth}}</dd>
<dt>Title:</dt>
<dd>{{user.basicInfo.title}}</dd>
</dl>
</div>
</div>
<div class="panel-body form-panel-box" ng-if="makeChanges" ng-submit="saveChanges(user)">
<form class="form-horizontal edit-changes-form">
<div class="form-group">
<label class="control-label col-sm-2" for="firstName">First Name:</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="firstName" ng-model="user.basicInfo.firstName">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="lastName">Last Name:
</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="lastName" ng-
model="user.basicInfo.lastName">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="status">Status:
</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="status" ng-
model="user.basicInfo.status">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="Work Location">Work
Location:</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="work" ng-
model="user.basicInfo.location">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="dateOfBirth">Date of
Birth</label>
<div class="col-sm-3">
<input type="text" class="form-control" id="dateOfBirth" ng-
model="user.basicInfo.dateOfBirth">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-3">
<input type="text/number" class="form-control" id="title"
ng-model="user.basicInfo.title">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-3">
<button type="submit" class="btn btn-default">Save
Changes</button>
</div>
</div>
</form>
info.js file
app.controller('info',function($scope,$localStorage,authService,$http){
$scope.user = $localStorage.userObject;
$scope.userEnteredInfo = true;
$scope.editChanges = function(){
$scope.makeChanges = true;
$scope.userEnteredInfo= false;
}
//Edit changes for updating information//
$scope.saveChanges = function(userData){
$scope.updatedInfoDetails = {
firstName: userData.basicInfo.firstName,
lastName: userData.basicInfo.lastName,
status: userData.basicInfo.status,
WorkLocation: userData.basicInfo.location,
dateOfBirth: userData.basicInfo.dateOfBirth,
title: userData.basicInfo.title
}
authService.postUpdatedInfo($scope.updatedInfoDetails)
.then(function(response){
if(response.status == 200){
$scope.updatedInfo = "You have successfully updated the changes";
};
});
$scope.userEnteredInfo = false;
$scope.makeChanges = true;
console.log("success");
};
});
authService.js file
app.service('authService', function($localStorage,$http) {
this.postUpdatedInfo = function(userChangedInfo){
console.log('the user data is: ', userChangedInfo);
var urlForChangingInfo = "/api/users/" + $localStorage.getUserId;
return $http({
method:'PUT',
url:urlForChangingInfo,
data:userChangedInfo,
headers:{"x-access-token":$localStorage.authToken}
});
};
});
makeChanges is never made to false,
try this,
authService.postUpdatedInfo($scope.updatedInfoDetails)
.then(function(response){
if(response.status == 200){
$scope.updatedInfo = "You have successfully updated the changes";
};
});
$scope.userEnteredInfo = false;
$scope.makeChanges = false;
console.log("success");
};
you are never setting $scope.userEnteredInfo to true , can you try code given below :
authService.postUpdatedInfo($scope.updatedInfoDetails)
.then(function(response){
if(response.status == 200){
$scope.updatedInfo = "You have successfully updated the changes";
$scope.userEnteredInfo = true;//set true here
$scope.makeChanges = true;
console.log("success");
}
else
{
// error if response status other than 200
$scope.userEnteredInfo = false;
$scope.makeChanges = false;
console.log("error");
};
});
};
I have two forms on a page the "top form" searches for movies and I'm trying to get the data found from the top form and pass it as a value to the bottom form so it can get entered into a database.
I am unable to do this but, I can get the results to be displayed on the page. Here is my code:
TOP FORM DATA
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<?php
$squery="";
if(isset($_GET["squery"]))
{
$squery=$_GET["squery"];
}
?>
<div class="col-xs-8 col-xs-offset-2">
<form action="#" method="GET" class="form-horizontal">
<div class="form-group">
<label for="newMovieName" class="col-sm-3 control-label">Search what movie?</label>
<div class="col-sm-9"> <input type="text" name="squery" class="form-control"><br />
<input type="submit" value="Submit" class="btn btn-success"></div></div>
</form>
<script type="text/javascript" charset="utf-8">
var api_key = '6969696969696969696969696969696';
$(document).ready(function(){
$.ajax({
url: 'http://api.themoviedb.org/3/search/movie?api_key=' + api_key + '&query=<?php echo $squery; ?>',
dataType: 'jsonp',
jsonpCallback: 'testing'
}).error(function() {
console.log('error')
}).done(function(response) {
var i=0;
// for (var i = 0; i < response.results.length; i++) {
$('#search_results').append('<li>' + response.results[i].title + '</li>');
// }
$('#search_results_title').append(response.results[i].title);
$('#search_results_release').append(response.results[i].release_date);
$('#search_results_overview').append(response.results[i].overview);
$('#search_results_poster').append('https://image.tmdb.org/t/p/w185' + response.results[i].poster_path);
$('#search_results_votes').append(response.results[i].vote_count);
});
});
</script>
TOP FORM RESULTS
Here is where the results are displayed from the form above BUT, I would like these results to be displayed as a value in the form below.
<h3>Results</h3>
<p id="error"></p>
<ul id="search_results_title"></ul>
<ul id="search_results_release"></ul>
<ul id="search_results_overview"></ul>
<ul id="search_results_poster"></ul>
<ul id="search_results_votes"></ul>
BOTTOM FORM DATA
Here is the bottom form that SHOULD get submitted to the database with the "Results" that are above as the value.
<form class="form-horizontal" role="form" action="processmovie.php" method="get" enctype="text/plain">
<div class="form-group">
<label for="newMovieName" class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="newMovieName" name="movie_name" placeholder="Movie Title" required value="">
</div>
</div>
<div class="form-group">
<label for="movieYear" class="col-sm-3 control-label">Year</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="movieYear" name="movie_year" placeholder="Year" required>
</div>
</div>
<div class="form-group">
<label for="movieBio" class="col-sm-3 control-label">Storyline</label>
<div class="col-sm-9">
<textarea type="email" class="form-control" id="movieBio" name="movie_bio" rows="4" placeholder="Enter Storyline" required></textarea>
</div>
</div>
<div class="form-group">
<label for="newImage" class="col-sm-3 control-label">Movie Cover URL</label>
<div class="col-sm-9">
<input type="text" id="newImage" class="form-control" name="movie_img" placeholder="Enter URL" required>
</div>
</div>
<div class="form-group">
<label for="movieRating" class="col-sm-3 control-label">Rating</label>
<div class="col-sm-9">
<select id="movieRating" name="movie_rating" class="form-control" required>
<option value="G">G</option>
<option value="PG">PG</option>
<option value="PG-13">PG-13</option>
<option value="R">R</option>
<option value="NR">NR (Not Rated)</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<button type="submit" class="btn btn-success">Add Movie</button>
</div>
</div>
</form>
I tried to use a variaty of code to try and get the value here is an example: <?php echo $_GET['search_results_title'];?>
I've also found examples like this: How to pass the value of a form to another form? but, my forms are on the same page and not different ones.
As I said in my comment, you would just want to change your ajax call to something like this:
$.ajax({
url: 'http://api.themoviedb.org/3/search/movie?api_key=' + api_key + '&query=<?php echo $squery; ?>',
dataType: 'jsonp',
jsonpCallback: 'testing'
}).error(function() {
console.log('error')
}).done(function(response) {
var i=0;
$('#newMovieName').val(response.results[i].title);
$('#movieYear').val(response.results[i].release_date);
$('#movieBio').val(response.results[i].overview);
$('#newImage').val('https://image.tmdb.org/t/p/w185' + response.results[i].poster_path);
});
(I'm not sure about the relationship you have between response.results[i].vote_count and movieRating)
Here is a fiddle sort of showing the result, though I can't exactly replicate your code there because of the ajax calls
I'm need to create a form that sends an ajax request everytime a form element is changed using the jQuery change event. I was able to get the form input values to show up in spans by doing this:
<form id="TestForm" class="form-horizontal">
<div class="form-group">
<label for="namefirst" class="col-sm-2 control-label">First Name</label>
<div class="col-sm-6">
<input id="firstname" type="text" name="firstname" class="form-control" placeholder="Enter your first name" /><span id="spanfirstname"></span>
</div>
</div>
<div class="form-group">
<label for="namelast" class="col-sm-2 control-label">Last Name</label>
<div class="col-sm-6">
<input id="lastname" type="text" name="lastname" class="form-control" placeholder="Enter your last name" /><span id="spanlastname"></span>
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">Email</label>
<div class="col-sm-6">
<div class="left-inner-addon"> <i class="glyphicon glyphicon-envelope"></i>
<input id="email" type="text" name="email" class="form-control" placeholder="Enter your email" /><span id="spanemail"></span>
</div>
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-6">
<div class="left-inner-addon"> <i class="glyphicon glyphicon-phone-alt"></i>
<input id="phone" type="text" name="phone" class="form-control" placeholder="Enter your phone number" /><span id="spanphone"></span>
</div>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label">Password</label>
<div class="col-sm-6">
<input id="password" type="password" name="password" class="form-control" placeholder="Enter a password" /><span id="spanphone"></span>
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-2 control-label"></label>
<div class="col-sm-6">
<button class="button green major beeboop" name="button" type="submit">This is a test</button>
</div>
</div>
</form>
<div id="result"></div>
<div class="row spacer"></div>
</div>
<!-- /container -->
<script src="//code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#firstname').change(function() {
$('#output_firstname').val($(this).val());
$('#spanfirstname').html('<b> TestForm: firstname:' + $(this).val() + '</b>');
});
$('#lastname').change(function() {
$('#output_lastname').val($(this).val());
$('#spanlastname').html('<b>' + $(this).val() + '</b>');
});
$('#email').change(function() {
$('#output_email').val($(this).val());
$('#spanemail').html('<b>' + $(this).val() + '</b>');
});
$('#phone').change(function() {
$('#output_phone').val($(this).val());
$('#spanphone').html('<b>' + $(this).val() + '</b>');
});
$('#password').change(function() {
$('#output_password').val($(this).val());
$('#spanpassword').html('<b>' + $(this).val() + '</b>');
});
});
</script>
I tried the wrap the ajax request in the change event function with no success:
<script>
$(document).ready(function() {
$('#firstname').change(function() {
jQuery.post("ajax-process.cfm", {
firstname: jQuery('#firstname').val()
}, function(data) {
});
return false;
});
});
</script>
#omar-ali #Anil Namde Updated the code. But now I'm only getting the first value in the console:
$("input[type='text']").change(function() {
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
$.ajax({
url : "ajax-process.cfm",
type: "POST",
data: {
firstname: firstname,
lastname: lastname,
email: email
},
success: function(data) {
$("#simple-msg").html('<pre><code>' + data + '</code></pre>');
}
});
});
I tried your code, but instead of calling any ajax request, I just put a console.log('testing');
It works.
I guess what you don't realize (my feeling) is that.. the change is called not as you type..but once you lose focus from the text-box.
Also, it's better to use
var getallyourvalshere = $('#firstname').val();
$.post('linktoyourscript.php',{ firstname: getallyourvalshere }, function(data) {
//do stuff, console.log(data);
});
Why are you using return false;