I'm currently working on a Project with Phaser.js and I'm running into a problem when working on my Highscore. When the game goes into the last state called "end", it opens a Bootstrap Modal Dialog with the achieved Score and an input where you can put your name. When I hit "send" it should put the value of both inputs into the ajaxcall and send it to "/". But the inputs end up being empty, a console.log(input1 + " and " + input2); brings out nothing but the "and". I have not a clue what the problem could be since I'm not getting ANY errors. Any help is appreciated.
index.ejs:
<div class="col-md-12" id="popup">
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<label for="score">Your Score:</label>
<input value="" class="form-control" id="score"><br>
<label for="name">Your Name:</label>
<input value="" class="form-control" id="name" placeholder="Choose a name for the leaderboards...">
</div>
<div class="modal-footer">
<button type="button" id="send" class="btn btn-success">Send</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
ajaxcalls.js
var input1 = $('#name').val();
var input2 = $('#score').val();
$('#send').click(function(){
console.log(input1 + 'x' + input2);
$.ajax({
method: "POST",
url: "/",
data: {
Name: input1,
HScore: input2
},
success: function(data){
console.log('success');
$('#myModal').modal('hide');
}
});
});
index.js
router.post('/', function (req, res) {
var Name = req.body.Name;
var HScore = req.body.HScore;
mongoose.model('hs').create(
{
player: Name,
score: HScore
},
function (err,player) {
if(err){
res.send('Errortext!');
}
console.log('POST creating new Player: ' + player);
res.redirect('/');
});
});
mongo.js
var mongoose = require('mongoose');
var highScore = new mongoose.Schema({
player: String,
score: Number
});
mongoose.model('hs', highScore);
You just need to read values inside of click listener
$('#send').click(function(){
var input1 = $('#name').val();
var input2 = $('#score').val();
console.log(input1 + 'x' + input2);
$.ajax({
method: "POST",
url: "/",
data: {
Name: input1,
HScore: input2
},
success: function(data){
console.log('success');
$('#myModal').modal('hide');
}
});
});
Related
I am working on submitting a form via jQuery AJAX. The form also has basic validation, that I am doing myself.
The HTML (index.html file):
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<form action="/process" class="modal-dialog" id="order_form">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Pre-order</h5>
<button type="submit" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="#validation" class="d-none alert alert-danger">
All fields are mandatory
</div>
<div id="#status" class="d-none alert alert-dismissible">
×
<p class="m-0"></p>
</div>
<div class="form-group">
<label for="first_name">First name:</label>
<input type="first_name" class="form-control" id="first_name" placeholder="First name" name="first_name">
</div>
<div class="form-group">
<label for="last_name">Last name:</label>
<input type="last_name" class="form-control" id="last_name" placeholder="Last name" name="last_name">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" placeholder="Enter email" id="email">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary btn-sm btn-block">Send</button>
</div>
</div>
</form>
</div>
The script:
function isEmail(mail){
return /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+([^<>()\.,;:\s#\"]{2,}|[\d\.]+))$/.test(mail);
}
function submitOrder(e) {
e.preventDefault();
var form = $(this),
submitUrl = form.attr('action'),
firstName = $('#first_name').val(),
lastName = $('#last_name').val(),
emailAddress = $('#email').val()
// Are there any empty fields?
isEmpty = firstName == ''
|| lastName == ''
|| emailAddress == '';
console.log('Empty filds: ', isEmpty);
console.log('Valid email: ', isEmail(emailAddress));
if (isEmpty) {
$('#validation').removeClass('d-none');
} else {
if (!isEmail(emailAddress)) {
$('#validation').removeClass('d-none').text('Choose a valid email');
} else {
$('#validation').addClass('d-none');
$.ajax({
type: "POST",
url: submitUrl,
data: form.serialize(),
dataType: "json",
success: function(response) {
if (response == 'successful') {
$('#status').addClass('alert-success').find('p').text("Your order was send");
}
else {
$('#status').addClass('alert-danger').find('p').text("We've failed to send your order");
}
$('#status').removeClass('d-none');
}
});
}
}
}
$(document).ready(function(){
// Submit Order Form
$('#order_form').on('submit', submitOrder);
});
The problem:
Evan though the form is not valid, and the console shows Empty filds: true and Valid email: false, the calass 'd-none' is not removed from <div id="#validation" class="d-none alert alert-danger"> and the alert, of course, is not displayed.
What is my mistake?
I've found a mistake in your code but I don't know if it will resolve your problem:
if (isEmpty) {
$(' #validation').removeClass('d-none');
}
should be (space before #validation)
if (isEmpty) {
$('#validation').removeClass('d-none');
}
Here is what worked for me, in case it might help others:
function isEmail(mail){
return /^(([^<>()\[\]\.,;:\s#\"]+(\.[^<>()\[\]\.,;:\s#\"]+)*)|(\".+\"))#(([^<>()\.,;\s#\"]+\.{0,1})+([^<>()\.,;:\s#\"]{2,}|[\d\.]+))$/.test(mail);
}
function submitOrder(e) {
e.preventDefault();
var form = $(this),
submitUrl = form.attr('action'),
firstName = $('#first_name').val(),
lastName = $('#last_name').val(),
emailAddress = $('#email').val()
// Are there any empty fields?
isEmpty = firstName == ''
|| lastName == ''
|| emailAddress == '';
if (isEmpty) {
$('#validation').removeClass('d-none');
} else {
if (!isEmail(emailAddress)) {
$('#validation').removeClass('d-none').text('Choose a valid email');
} else {
$('#validation').addClass('d-none');
var req = $.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize()
});
req.done(function(data) {
if (data == 'success') {
$('#status').addClass('alert-success').find('p').text("Your order was send");
}
else {
$('#status').addClass('alert-danger').find('p').text("We've failed to send your order");
}
$('#status').removeClass('d-none');
});
}
}
}
$(document).ready(function(){
// Submit Order Form
$('#order_form').on('submit', submitOrder);
});
I have been trying for some time to get this working. I am struggling to take user input from a modal and insert it into a my database in phpmyadmin. Any help would be greatly appreciated.
1) Using the select callback I bring up a modal:
select: function(start, end, allDay)
{
$('#myModal').modal('show');
},
2) The modal itself in the HTML:
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Add Event</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="FormControlInput1">Task Title</label>
<input type="text" class="form-control" id="title" placeholder="Enter Task Title">
</div>
<div class="form-group">
<label for="FormControlInput2">Task Number</label>
<input type="text" class="form-control" id="number" placeholder="Enter Task Number>
</div>
<div class="form-group">
<label for="FormControlInput3">Location</label>
<input type="text" class="form-control" id="location" placeholder="Enter Location">
</div>
<div class="form-group">
<label for="FormControlTextarea1">Tooling Required</label>
<textarea class="form-control" id="tooling" placeholder="Enter the tools required for the task here" rows="3"></textarea>
</div>
<div class="form-group">
<label for="FormControlTextarea2">Consumables</label>
<textarea class="form-control" id="consumables" placeholder="Enter the consumables required for the task here" rows="3"></textarea>
</div>
<div class="form-group">
<label for="FormControlSelect1">Safety Condition</label>
<select class="form-control" id="safety">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
</select>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="buttonAddEvent">Add Event</button>
</div>
</div>
</div>
</div>
3) At this point I would like to use my insert.php file I have made, which works for other functions in the code:
<?php
//insert.php
$connect = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');
if(isset($_POST["title"]))
{
$query = "
INSERT INTO events
(title, number, location, tooling, consumables, safety, start_event, end_event)
VALUES (:title, :number, :location, :tooling, :consumables, :safety, :start_event, :end_event)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':title' => $_POST['title'],
':number' => $_POST['number'],
':location' => $_POST['location'],
':tooling' => $_POST['tooling'],
':consumables' => $_POST['consumables'],
':safety' => $_POST['safety'],
':start_event' => $_POST['start'],
':end_event' => $_POST['end']
)
);
}
?>
I have typically inserted data using the following code however this uses prompts() which I want to replace with the modal inputs:
select: function(start, end, allDay)
{
var title = prompt("Enter Task Title");
if(title)
{
var number = prompt("Enter Task Number");
var location = prompt("Enter Train Location");
var tooling = prompt("Enter Tooling Required");
var consumables = prompt("Enter Consumables Required");
var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
$.ajax({
url:"insert.php",
type:"POST",
data:{title:title, number:number, location:location, tooling:tooling, consumables:consumables, start:start, end:end},
success:function()
{
calendar.fullCalendar('refetchEvents');
}
})
}
},
Needed to make use of .on() to pass data from modal input to variables
select: function(start, end, allDay)
{
var start = $.fullCalendar.formatDate(start, "Y-MM-DD HH:mm:ss");
var end = $.fullCalendar.formatDate(end, "Y-MM-DD HH:mm:ss");
$('#myModal').modal('show')
$('#buttonAddEvent').on('click', function (){
var title = $("#myModal #title").val().trim();
var number = $("#myModal #number").val().trim();
var location = $("#myModal #location").val().trim();
var tooling = $("#myModal #tooling").val().trim();
var consumables = $("#myModal #consumables").val().trim();
var safety = $("#myModal #safety").val().trim();
var mockEvent = {title:title, number:number, location:location, tooling:tooling, consumables:consumables, safety:safety, start:start, end:end};
$('#calendar').fullCalendar('renderEvent', mockEvent);
$('#buttonAddEvent').unbind('click');
$('#myModal').modal('hide');
$.ajax({
url:"insert.php",
type:"POST",
data:{title:title, number:number, location:location, tooling:tooling, consumables:consumables, safety:safety, start:start, end:end},
success:function()
{
calendar.fullCalendar('refetchEvents');
}
});
});
},
Thanks to #ADyson for pointing in the right direction.
i 'm not seeing any return data from your php code (which is generally get newly updated record and returns as json_encode),
and then the Ajax Success Function should process the response data and fetch it to calendar
I am trying to make a bootstrap 4 modal that opens when a button is pressed inside a dynamically created element which makes an Ajax request to a form pre-populated with the data from the associated id, and then a button to save the updated information into the database.
Currently, the edit button opens a new page "editData" with the prepopulated data associated with the passed id, which then can be used to update the information upon pressing a button, and then returns to the previous page.
What are the methods that I can use to make the button open a modal on the current page that can provide the same function?
function populateData(dataInput) {
var row = $('<tr id=' + dataInput.id + '/>');
$('#table').append(row);
row.append($('<td>' + dataInput.name + '</td>'));
row.append($('<td>' + dataInput.description + '</td>'));
row.append($(
'<td><input type="submit" class="btn btn-warning" value="edit" onclick="edit(' +
dataInput.id + ')"/>'));
}
function edit(id) {
$.ajax({
type: 'GET',
url: '/getData?id=' + id,
success: function(data) {
var dataInput = JSON.parse(data)[0];
window.location = '/editData?id=' + dataInput.id;
}
})
}
Here is the getData that dynamically populates the table
app.get('/getData', function(req, res) {
var content = {};
mysql.pool.query('SELECT * FROM dataTable WHERE id=?', [req.query.id],
function(err, rows, fields) {
if (err) {
next(err);
return;
}
content.results = JSON.stringify(rows);
res.send(content.results);
});
});
And here is the editData.handler content
<div>
<form id="form">
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="">
<label for="description">Description:</label>
<textarea id="description" name="description" rows="4" cols="50"></textarea>
</form>
<div class="centerButton">
<input id="submit" class="btn btn-primary" type="submit" value="Save" onclick="save()" />
</div>
</div>
This is a simple bootstrap modal.
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Now JavaScript part to make ajax request and embed data into modal.
function populateData(dataInput) {
var row = $('<tr id=' + dataInput.id + '/>');
$('#table').append(row);
row.append($('<td>' + dataInput.name + '</td>'));
row.append($('<td>' + dataInput.description + '</td>'));
//check that I have added attributes data-toggle and data-target to point example modal
row.append($(
'<td><input type="submit" data-toggle="modal" data-target="#exampleModal" class="btn btn-warning" value="edit" onclick="edit(' +
dataInput.id + ')"/>'));
}
function edit(id) {
$.ajax({
type: 'GET',
url: '/getData?id=' + id,
success: function(data) {
var dataInput = JSON.parse(data)[0];
//commented following line and adding code to embed data into modal
//window.location = '/editData?id=' + dataInput.id;
$('.modal-body').html('html that you want to show');
}
})
}
It works and here is a demo on Codepen.
Please make sure that you have include bootstrap and jquery.
I'm currently using spring boot, and my ajax function keeps running into error function without any error log.
my view :
<div id ="EditModal" class="modal fade" role="dialog">
<form class="modal-dialog" th:action="#{/EditPhoneNumber}" th:object="${phoneNumber}" method="POST" id="PhoneEditForm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<div class="modal-body">
<input type="text" class="hidden" id="edit-modal-phone-number-id" name="id" value=""/>
<input type="text" placeholder="Number" id="edit-modal-phone-number-number" name="number" value=""/>
<input type="text" class="hidden" id="edit-modal-person-id" name="personID" th:value="${personID}"/>
<p id="EditFormError"></p>
</div>
<div class="modal-footer">
<button type="submit" id="SubmitEdit" class="btn btn-default" >Submit</button>
<button type="button" class = "btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</form>
</div>
<script>
$(document).ready(function(){
$("#SubmitEdit").click(function(e){
e.preventDefault();
console.log("it ran here");
var inputID = $("#edit-modal-phone-number-id").val();
var inputNumber = $("#edit-modal-phone-number-number").val();
var inputPersonID = $("#edit-modal-person-id").val();
$.ajax({
type: "POST",
url : "/ValidateEditPhoneNumber",
dataType : "json",
data : JSON.stringify({"id" : inputID, "number" : inputNumber, "personID" : inputPersonID}),
contentType: "application/json",
success : function(result){
alert("Success "+result.responseText);
$("#PhoneEditForm").submit();
},
error : function(result){
alert("Error "+result.responseText);
}
});
});
});
</script>
my controller :
#RequestMapping(value = "/ValidateEditPhoneNumber",method = RequestMethod.POST, produces = "application/json")
public #ResponseBody String ValidatePhoneNumber(#Validated #RequestBody PhoneNumberRequest phoneNumber, BindingResult result) {
System.out.println(phoneNumber.getId());
System.out.println(phoneNumber.getNumber());
System.out.println(phoneNumber.getPersonID());
if(result.hasErrors()) {
return "Something happened";
}
else return "SUCCESS";
}
The string i got from the controller is always "SUCCESS" so i guess the problem isnt in the controller. But what causes the problem?
Please help.
I want to make jquery plugin to process form submit before ajax.
This is my jquery script
;(function($,window,document,undefined){
"use strict";
$.modalLoad = function(element, options){
var plugin = this;
var $element = $(element),
element = element,
url = $element.attr('href'),
target = $element.data('target');
var defaults = {
form: $(this).serializeArray(),
};
plugin.init = function(context){
plugin.settings = $.extend({},defaults, options);
plugin.add_bindings();
plugin.create_ajax(context);
}
plugin.create_ajax = function(context){
$('form',context).addClass('modal-form');
$('.modal-form',context).on('submit',function(e){
e.preventDefault();
plugin.post_data($(this),context);
});
}
plugin.post_data = function(form,context){
var loaded = false;
var throbbed = false;
var _fd = new FormData();
var password = hex_sha512($('input[type="password"]',context).val());
_fd.append('password',password);
function checkComplete(){
if(loaded && throbbed){
$('.ajax-loader').remove();
}
}
function requestComplete(){
loaded = true;
checkComplete();
}
$.ajax({
url:form.attr('action'),
type: form.attr('method'),
data: _fd,
contentType: false,
cache: false,
processData: false,
success: function(data){
requestComplete();
console.log(data);
},
beforeSend: function(){
var loading = "<img src='images/loader.gif' class='ajax-loader'>";
$('.modal-footer',context).append(loading);
$('.ajax-loader').css({
height: '15px',
'vertical-align': 'middle',
margin: '0px 5px'
});
setTimeout(function(){
throbbed = true;
checkComplete();
},2000);
},
complete: requestComplete()
});
console.log(plugin.settings.form);
}
plugin.init();
}
$.fn.modalLoad = function(options){
return this.each(function(){
if(undefined == $(this).data('modalLoad')){
var plugin = new $.modalLoad(this, options);
$(this).data('modalLoad', plugin);
}
});
}
})(jQuery);
HTML
<div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false">
<div class="modal-dialog">
<div class="modal-content">
<form action="<?php echo 'http://'.base_url('authentication.php');?>" method="POST">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Login</h4>
</div>
<div class="modal-body">
<div class="modal-space">
<label class="email">
<input type="text" name="email" value="" placeholder="Email*" data-constraints="#Required #Email" id="regula-generated-387495">
</label>
</div>
<div class="modal-space">
<label class="password">
<input type="password" name="password" value="" placeholder="Password*" data-constraints="#Required #Email" id="regula-generated-387495">
</label>
</div>
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-primary btn-1 btn-1__mod-1" value="LOGIN">
</div>
</form>
</div>
</div>
</div>
Now, i want to encrypt password field with sha512 before it send with ajax which follow this instruction.
Actually, i serialize form data to array and i want to override password array that sets in defaults.form objects.
But even i can't fetch data from defaults.form where form data should be stored in.
Is possible if i print defaults.form in console.log? Could everyone tell me which part that i must fix? Also please tell me how to tidy up my code?
Thanks for advance
make sure in your html code, all input inside tag form. Otherwise you will get missing value from form data serialize in defaults.form. Can you show your html code here?