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.
Related
I am trying to save a ViewModel object from a partial view in a modal, and I get a 404 error when I try to post it. The url is being called, but the ViewModel data isn't being sent. I have been reading similar questions on here and on MSN for hours and nothing I've tried fixes the problem. I took out the repetitive days of the week code for brevity, but I can
add them back in if anyone wants a complete working example. Here is the code
EmployeeViewModel
public class EmployeeViewModel
{
public bool Monday { get; set; } = false;
//...bool properties for Tuesday through Sunday
public Employee Employee { get; set; }
}
Employee/ _AddEmployeeModalPartial
#model JSarad_C868_Capstone.ViewModels.EmployeeViewModel
#Html.AntiForgeryToken()
<div class="modal modal-fade" id="addEmployee">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="addEmpoyeeLabel">Add Employee</h4>
<button type=button class="close" data-bs-dismiss="modal">
<span>x</span>
</button>
</div>
<div class="modal-body">
<form action="Add">
<div class="form-group">
<input asp-for="Employee.Id" class="form-control" />
<input asp-for="Employee.Availability" class="form-control" />
<label asp-for="Employee.Role"></label>
<select asp-for="Employee.Role" class="form-control">
<option value="Bartender">Bartender</option>
<option value="Server">Server</option>
</select>
<span asp-validation-for="Employee.Role" class="text-danger"></span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Name"></label>
<input asp-for="Employee.Name" class="form-control" />
<span asp-validation-for="Employee.Name" class="text-danger"></span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Phone"></label>
<input asp-for="Employee.Phone" class="form-control" />
<span asp-validation-for="Employee.Phone" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Email"></label>
<input asp-for="Employee.Email" class="form-control" />
<span asp-validation-for="Employee.Email" class="text-danger">
</span>
</div>
#*<div class="mb-3">*#
<div class="form-group">
<label asp-for="Employee.Address"></label>
<input asp-for="Employee.Address" class="form-control" />
<span asp-validation-for="Employee.Address" class="text-danger">
</span>
</div>
#* <div class="mb-3">*#
<div class="form-group">
<label>Availabiliy</label>
</div>
<div class="row pb-4">
<div class="col">
<div class="form-check">
<input asp-for="Monday" class="form-check-input"
type="checkbox" />
<label asp-for="Monday" class="form-check-label"></label>
</div>
<!--...//form check boxes for Tuesday trough Sunday -->
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary"
data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary"
data-bs-save="modal">Save</button>
</div>
</div>
</div>
</div>
EmployeeController.cs
[HttpGet]
public IActionResult Add()
{
EmployeeViewModel viewModel = new EmployeeViewModel();
return PartialView("_AddEmployeeModalPartial", viewModel); ;
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Add(EmployeeViewModel viewModel) //code never reaches this Action
{
viewModel.Employee.Availability = ConvertDaysToChar(viewModel.Employee.Availability)
if (ModelState.IsValid)
{
_db.Employees.Add(viewModel.Employee);
_db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return PartialView("_AddEmployeeModelPartial", viewModel);
}
}
site.js
$(function () {
var PlaceHolderElement = $('#PlaceHolderHere');
$('button[data-bs-toggle="ajax-modal"]').click(function (event) {
/* event.preventDefault();*/
var url = $(this).data('url');
console.log(url)
$.get(url).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
})
})
PlaceHolderElement.on('click', '[data-bs-save="modal"]', function (event) {
event.preventDefault();
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
console.log(actionUrl);
var sendViewModel = form.serialize();
console.log(sendViewModel);
//$.post(actionUrl, sendViewModel).done(function (data) {
// PlaceHolderElement.find('.modal').modal('hide');
/*above is the code from a tutorial for modals. It also doesn't send the object to
post action*/
$.ajax({
type: 'POST',
url: actionUrl,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(sendViewModel),
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
})
})
When I click the save button on the model, the console.log(sendViewModel) returns the correct Serialization with all of the properties and their correct names. And the properties change correctly when there is input.
Employee.Id=&Employee.Availability=&Employee.Role=Bartender&Employee.Name=&Employee.Phone=&Employee.Email=&Employee.Address=&Monday=false&Tuesday=false&Wednesday=false&Thursday=false&Friday=false&Saturday=false&Sunday=false
But I get an error "Failed to load resource: the server responded with a status of 404 ()"
and when I check it the page says "No webpage was found for the web address: https://localhost:44313/Add HTTP ERROR 404" as if it's trying to get a post. It is also missing the controller, but if I change my form action to "Employee/Add" in the _Partial view it still doesn't send the data along with the url, which is causing an entirely different problem. I would greatly appreciate any help or guess or input of any kind. I'm about five seconds away from throwing my laptop out the window on this one. Thanks.
1.Remove the #Html.AntiForgeryToken() inside your form,like below:
<form action="Add" >
#Html.AntiForgeryToken()
....
Then after you serialize the form you can get the AntiForgeryToken, like below:
Because when you don't add #Html.AntiForgeryToken()inside form, after you serialize the form you don't get the AntiForgeryToken, like below:
Besides, if you use <form asp-action="Add" > In ASP.Net Core anti forgery token is automatically added to forms, so you don't need to add #Html.AntiForgeryToken(),you can find in the below :
2.change your ajax like below:
$.ajax({
type: 'POST',
url:'/Employee/Add',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: sendViewModel,
success: function (result) {
console.log('Data received: ');
console.log(result);
}
})
result:
First, I had to change the form action from "Add" to "Employee/Add". ThenI had to remove the antiforgery token from my post action. The first code that is commented out actually works fine otherwise. In my defense I did remove the antiforgery token when I had the wrong URL, but I forgot to retest that when I had the correct one.
I create one form which includes select2 control.and i have data in database.
Now I want to fetch value of particular data value into select2 control when edit the form. My selected select value is store in one variable Now i want that value dispaly in select2 control inside the edit form and i dont know how ..
here is my edit form code:
<div id="editm" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<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">Update Rayon</h4>
</div>
<div class="modal-body">
<form id="validate1" method="POST">
<div class="form-group">
<label class="control-label">Kode Rayon</label>
<div>
<input type="text" class="form-control" id="edit_Kode_rayon" name="edit_Kode_rayon" placeholder="Kode Rayon" readonly>
</div>
</div>
<div class="form-group">
<label class="control-label">Nama Rayon</label>
<div>
<input type="text" class="form-control" id="edit_nama_rayon" name="edit_nama_rayon" placeholder="Nama Center" >
</div>
</div>
<div class="form-group">
<label class="control-label">Nama Region</label>
<div>
<!-- HERE IS THE SELECT2 THAT IM TALKING ABOUT.. -->
<select class="form-control kode_region" id="nRegionE" name="kode_region" style="width: 100%;">
<option value=""></option>
</select>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="update" class="btn btn-primary">Update</button>
</div>
</div>
</div>
here is jquery code for edit button:
$(document).on("click", "#edit", function(e){
e.preventDefault();
var editid = $(this).attr("value");
$.ajax({
url: "<?php echo base_url();?>Rayon/editdata",
type: "POST",
dataType: "json",
data:{editid: editid},
success: function(data){
if(data.responce == "success"){
$('#editm').modal('show');
$("#edit_Kode_rayon").val(data.posts.kode_rayon);
$("#edit_nama_rayon").val(data.posts.nama_rayon);
//$("#nRegionE").val(data.posts.kode_region);<-- I TRIED LIKE THIS .. NOT WORK -->
//$("#nRegionE").select2().select2('val',data.posts.kode_region);<-- I TRIED LIKE THIS . NOT WORK-->
$('#nRegionE').val(data.posts.kode_region).trigger("change");<-- EVEN THIS ONE IS NOT WORK -->
}else{
toastr["error"](data.message);}
}
});
});
and here is my Select2 script that im using it for inssert and my edit form:
$(function () {$('.kode_region').select2({
//placeholder: "Please select region",allowClear: true,
ajax: {
dataType: 'json',
url: '<?=site_url('Bonus/nregion')?>',
type: "post",
delay: 250,
data: function(params) {
return {search: params.term}},
processResults: function (data, page) {
return {results: data};
},
}
})});
just to make it clear i took a screenshot of my edit form:
all what i want is to fetch the value of data into select2 form control of Edit Form .. can anyone help me to do that ? n i'll be so thankful.
You are fetching options list correctly in data.posts.kode_region,
then update this line
$("#nRegionE").val(data.posts.kode_region);
to this
$("#nRegionE").html('<option value = "'+data.posts.kode_region+'" selected >'+data.posts.kode_region+'</option>');
and don't forget to comment this line
$('#nRegionE').val(data.posts.kode_region).trigger("change");
I am dam sure this will work for you
$("select#nRegionE option").val("hello"); //Change hello string to your record Id
$("select#nRegionE option").html(data.posts.kode_region);
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');
}
});
});
I Have a change password form which I have tried to code so that it gets submitted through ajax.
I needed to do validation too.
Below is the code that I've written. Is there anyway so that we can use this js ajax function for multiple modal forms?
Or will we need to create a seperate function for submitting each modal form?
Also I wanted to make the parent page reload after user closes the modal so I have added this code:
$('#edit').on('hidden.bs.modal', function() {
location.reload();
});
but it reloads the page when someone clicks cancel button too. Is there any way to prevent reloading when clicking cancel button and only do reloading only by clicking "x".
Here is the code
index.php file where the modal is
<p data-placement="top" data-toggle="tooltip" title="Edit" data-original-title="Edit">
<button class="btn btn-primary btn-xs" data-title="Edit" data-toggle="modal" data-target="#edit" data-backdrop="static" data-keyboard="false">
<span class="glyphicon glyphicon-pencil"> Edit</span>
</button>
</p>
<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<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">Edit Your Detail</h4>
</div>
<!--/.modal-header-->
<div class="modal-body">
<form method="post" id="updateForm" action="update-info.php">
<input type="hidden" name="userID" value="<?php echo $_SESSION['user']; ?>" />
<div class="form-group">
<label for="customer_name">Customer Name :</label>
<input class="form-control" type="text" name="customer_name" id="customer_name" value="<?php echo $userRow['fullName']; ?>" />
</div>
<h4><u><strong>Change Password</strong></u></h4>
<div class="form-group" id="currentPass-group">
<label for="current_pass">Current Password :</label>
<input class="form-control" type="password" name="current_pass" id="current_pass">
</div>
<div class="form-group">
<label for="new_pass">New Password :</label>
<input class="form-control" type="password" name="new_pass" id="new_pass">
</div>
<div class="form-group">
<label for="confirm_pass">Confirm Password :</label>
<input class="form-control" type="password" name="confirm_pass" id="confirm_pass">
</div>
<div class="modal-footer">
<!-- <input type="submit" name="submit" class="btn btn-block btn-warning" value="Save changes" /> -->
<button type="submit" name="submit" class="btn btn-success" id="submitForm" value="Save changes">Save Changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!--/.modal -->
custom.js file:
$('#edit').on('hidden.bs.modal', function() {
location.reload();
});
/* must apply only after HTML has loaded */
$(document).ready(function() {
$("#updateForm").on("submit", function(e) {
$(".error").hide();
var hasError = false;
var currentpass = $("#current_pass").val();
var newpass = $("#new_pass").val();
var cnfpass = $("#confirm_pass").val();
if (currentpass == '') {
$("#current_pass").after('<span class="error text-danger"><em>Please enter your current password.</em></span>');
//$('#currentPass-group').addClass('has-error'); // add the error class to show red input
//$('#current_pass').append('<div class="help-block">Please enter your current password.</div>'); // add the actual error message under our input
hasError = true;
} else if (newpass == '') {
$("#new_pass").after('<span class="error text-danger"><em>Please enter a password.</em></span>');
hasError = true;
} else if (cnfpass == '') {
$("#confirm_pass").after('<span class="error text-danger"><em>Please re-enter your password.</em></span>');
hasError = true;
} else if (newpass != cnfpass) {
$("#confirm_pass").after('<span class="error text-danger"><em>Passwords do not match.</em></span>');
hasError = true;
}
if (hasError == true) {
return false;
}
if (hasError == false) {
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax({
url: formURL,
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#edit .modal-header .modal-title').html("Result");
$('#edit .modal-body').html(data);
$("#submitForm").remove();
//document.location.reload();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
}
});
$("#submitForm").on('click', function() {
$("#updateForm").submit();
});
});
update-info.php
To use this code for multiple form add ajax code in one function and call that function whenever you want to.
To prevent page from reloading when someone click on cancel
Instead of using
$('#edit').on('hidden.bs.modal', function () {
location.reload();
});
Add one click event on cross and then reload page by location.reload();
You can use e.preventDefault(); and instead of submit use click event
$("#submitForm").on("click", function(e) {
e.preventDefault();
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?