textarea.val() sends original value not edited - javascript

I have this textarea in my MVC project
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
but when I try to send this to a Json call like this
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>
I get the original value of #Model.content instead of the new value.
Edit
my script.js code
function updateComment(id, title, content) {
return $.get("/Chapter/GetJSON_Update",
{
id: id,
title: title,
content: content
},
'json');
};
the entire code from my Edit.cshtml
#model Academia_Unitate.Models.Chapter
#{
ViewBag.Title = "Edit " + Model.title;
Layout = "~/Views/Shared/_Layout.cshtml";
}
#Html.Partial("~/Views/Shared/_TinyMCE.cshtml")
<div id="edit">
<h1>
Edit #Model.type.name
</h1>
<div class="" role="form">
<div class="form-group">
<label class="sr-only" for="title">Title</label>
<input class="form-control" type="text" id="edit-title" placeholder="Enter a title" value="#Model.title" required="required" />
</div>
<div class="form-group">
<label class="sr-only" for="content">Content</label>
<textarea id="edit-content" name="content" placeholder="Text content goes here">#Model.content</textarea>
</div>
<button type="submit" class="btn btn-success" id="save-btn" onclick="save()"><span class="glyphicon glyphicon-ok"></span> Save</button>
<span id="message-edit-loading" class="alert hidden"></span>
<span id="message-edit-error" class="alert alert-danger hidden"></span>
</div>
</div>
<input type="hidden" value="#Model.id" id="edit-id"/>
<script type="text/javascript">
function save() {
var $title = $('#edit-title'),
$content = $('#edit-content'),
$messageLoading = $('#message-edit-loading'),
$messageError = $('#message-edit-error'),
$id = $('#edit-id');
updateComment($id.val(), $title.val(), $content.val())
.done(function (data) {
if (data.IsValid()) {
$messageError.html('');
$messageError.removeClass('hidden');
$messageLoading.removeClass('hidden');
$messageLoading.html('The text is saved');
} else {
$messageError.removeClass('hidden');
$messageError.html(data.Message);
}
})
.fail(function (xhr, message) {
$messageError.removeClass('hidden');
$messageError.html('Registration failed: ' + message);
})
};
</script>

You most likely have more than one on your page, either make their id attributes unique or target the index in your jQuery.

Related

Edit function in datatables and laravel

Hi im doing an App with Datatables and i have a problem when i want to try to edit a record in the datatables this is my js function in app.blade.php
$(document).on('click', '.editButton', function(e) {
e.preventDefault();
var id = $(this).data("id");
var editRoute = "{{ url('admin/user/' . auth()->user()->id . '/messages') }}";
console.log(id);
token();
$.ajax({
/* url: "{{ route('admin.messages.edit', ['user' => auth()->user()->id, 'message' => ':id']) }}".replace(':id', id), */
url: editRoute + "/" + id,
type: "GET",
/* dataType: 'json', */
success: function(result) {
console.log(result)
var message = result.data;
console.log(message);
$('.id').val(message.id);
$('.text').val(message.text);
$('.url').val(message.url);
$('.note').val(message.note);
$('.tipes').val(message.tipes);
$('.start_time').val(message.start_time);
$('.end_time').val(message.end_time);
$('.active').val(message.active);
$('#modalEdit').modal('show');
$('.modal-title').text('Update Message');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
the console.log(result) is empty and console.log(message) is undefined
this is the edit function in the controller
public function edit(Request $request)
{
$result = Message::where('id', $request->id)->first();
if ($result) {
return response()->json([
'message' => "Data Found",
"code" => 200,
"data" => $result
]);
} else {
return response()->json([
'message' => "Internal Server Error",
"code" => 500
]);
}
}
i want to edit the message with a modal, but the js fuction doesnt work properly, the var message is undefined
this is my route file
Route::middleware('auth')
->namespace('Admin')
->name('admin.')
->prefix('admin')
->group(function () {
Route::get('/', 'HomeController#index')->name('home');
Route::resource('/user', 'UserController');/* ->except(['edit', 'update']); */
Route::resource('/user/{user:id}/messages', 'MessagesController');
/* Route::resource('user.messages', MessagesController::class); */
});
Route::get('messages', 'Admin\MessagesController#getMessages')->name('get.messages');
Auth::routes();
this is my table structure
enter image description here
and its my form for edit the message
<div id="modalEdit" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Modal Header</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<form id="update">
<div class="modal-body">
<div class="form-group">
<label for="text">Testo</label>
<input type="text-area" class="form-control text" id="text" name="text">
</div>
<div class="form-group">
<label for="url">URL</label>
<input type="text" class="form-control" id="url" name="url">
</div>
<div class="form-group">
<label for="note">Note</label>
<input type="text" class="form-control" id="note" name="note">
</div>
<div class="form-group">
{{-- <label for="tipes">Tipo</label>
<input type="text" class="form-control" id="tipes" name="tipes"> --}}
<label for="tipes">Tipo</label>
<select name="tipes" id="tipes">
<option value="A">A</option>
<option value="B">B</option>
</select>
</div>
<div class="form-group">
<label for="start_time">Inizio</label>
<input type="date" class="form-control" id="start_time" name="start_time">
</div>
<div class="form-group">
<label for="end_time">Fine</label>
<input type="date" class="form-control" id="end_time" name="end_time">
</div>
<div class="form-group">
<label for="active">Attivo</label>
{{-- <input type="text" class="form-control" id="active" name="active"> --}}
<label for="active">Attivo</label>
<select name="active" id="active">
<option value="1">Si</option>
<option value="0">No</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Update</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
public function edit(Request $request,$id)
{
$result = Message::where('id', $id)->get();
if ($result) {
return response()->json([
'message' => "Data Found",
"code" => 200,
"data" => $result
]);
} else {
return response()->json([
'message' => "Internal Server Error",
"code" => 500
]);
}
}
you need to pass $id parameter into function edit! try it! may be it works
$(document).ready(function() {
$('.editbutten').on('click', function(e) {
e.preventDefault();
var id = $(this).data("id");
var editRoute = "{{ url('admin/user/' . auth()->user()->id . '/messages') }}";
console.log(id);
token();
$.ajax({
/* url: "{{ route('admin.messages.edit', ['user' => auth()->user()->id, 'message' => ':id']) }}".replace(':id', id), */
url: editRoute + "/" + id,
type: "GET",
/* dataType: 'json', */
success: function(result) {
console.log(result)
var message = result.data;
console.log(message);
$('.id').val(message.id);
$('.text').val(message.text);
$('.url').val(message.url);
$('.note').val(message.note);
$('.tipes').val(message.tipes);
$('.start_time').val(message.start_time);
$('.end_time').val(message.end_time);
$('.active').val(message.active);
$('#modalEdit').modal('show');
$('.modal-title').text('Update Message');
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
});

Cannot submit form with the usage of Ajax in ASP.NET MVC

I have an issue about submitting a form via ajax and open a modal Dialog after the ajax function is completed successfully. When I click a submitButton, the process cannot be completed.
Where is the problem in an ajax method or anywhere?
How can I fix it?
Here is my form HTML part.
<form id="contactForm" role="form" class="php-email-form">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>
</div>
<div class="my-3"></div>
<div class="text-center">
<button type="submit" id="submitButton" data-bs-toggle="modal">Submit</button> <!-- data-bs-target="#modalDialog"-->
</div>
</form>
Here is my modal part.
<div class="modal fade" id="modalDialog" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
#ViewBag.Success
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-bs-dismiss="modal">Kapat</button>
</div>
</div>
</div>
</div>
Here is my javascript part.
<script type="text/javascript">
$(document).ready(function () {
$("#submitButton").click(function () {
var nameSurname = $("#nameSurname").val();
var email = $("#email").val();
var subject = $("#subject").val();
var message = $("#message").val();
var form = $('#contactForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: '/Home/Contract/',
data: {
__RequestVerificationToken: token,
nameSurname: nameSurname, email: email, subject: subject, message: message
},
type: 'POST',
success: function (data) {
$("#modalDialog").show();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('custom message. Error: ' + errorThrown);
}
});
});
})
</script>
Here is my Contract action in Home Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null)
{
if (nameSurname != null && email != null)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = message;
//Setting From , To and CC
mail.From = new MailAddress(email);
mail.To.Add(new MailAddress("gmail address"));
smtpClient.Send(mail);
ViewBag.Success = "Success";
}
else
{
ViewBag.Error = "Error";
}
return View();
}
EDIT
After I realized Ok() isn’t accessible in an MVC controller I found this solution which does essentially the same thing.
In your controller, change:
return RedirectToAction(“contract”);
To:
return new HttpStatusCodeResult(HttpStatusCode.OK);
RedirectToAction() and View() will by default load or refresh a page while a 200 (OK) response will just return a success status code.
You can do it this way:
View:
#using (Ajax.BeginForm("Contract", "ControllerName", FormMethod.Post, new AjaxOptions { HttpMethod = "POST", OnBegin = "OnBegin", OnSuccess = "OnSuccess", OnFailure = "OnFailure" }, new { #id = "ajaxForm" }))
{
<div class="card">
<div class="card-body">
#Html.AntiForgeryToken()
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="nameSurname" class="form-control" id="nameSurname" placeholder="Name Surname" required>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Email" required>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subject" required>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" id="message" rows="5" placeholder="Message" required></textarea>
</div>
<div class="my-3"></div>
<div class="text-center">
<button type="submit" id="submitButton">Submit</button> <!-- data-bs-target="#modalDialog"-->
</div>
</div>
</div>
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Contract(string nameSurname = null, string email = null, string subject = null, string message = null)
{
// do what is necessary
if (nameSurname != null && email != null)
{
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com");
smtpClient.Port = 587;
smtpClient.Credentials = new System.Net.NetworkCredential("gmail address", "gmail address password");
// smtpClient.UseDefaultCredentials = true; // uncomment if you don't want to use the network credentials
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.Subject = subject;
mail.IsBodyHtml = true;
mail.Body = message;
//Setting From , To and CC
mail.From = new MailAddress(email);
mail.To.Add(new MailAddress("gmail address"));
smtpClient.Send(mail)
return Json("Success", JsonRequestBehavior.AllowGet);
}
else // return result
{
return Json("Error", JsonRequestBehavior.AllowGet);
}
}
We have to create OnSuccess function in view to do something with result;
<script>
function OnSuccess(data) {
if (data == 'Success') {
$("#modalDialog").modal('show');
}
}
function OnFailure(data) {
//log failure
}
function OnBegin() {
// do something on begin
}
</script>

How to send ID of a row throught submit form / button?

I'm writing a code for the system administrator to be able to reset the users' passwords in their accounts in case they forget said password.
I'm currently having problems passing the target user's ID through Ajax to change said user's password, through debugging tool, the system returns an "undefined" response for "id:", although the "_token" and "password" fields were sent fine.
HTML code for the form
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
Javascript for generating the data-table where it shows the list of User accounts. On the side of the table, the admin can click a button to reset the password of said user.
$(document).ready(function() {
getRoles();
var accounts;
$('#account-management').addClass('active');
accounts = $("#table-accounts").DataTable({
ajax: {
url: "/users/get-all-users",
dataSrc: ''
},
responsive:true,
"order": [[ 7, "desc" ]],
columns: [
{ data: 'id'},
{ data: 'organization_name', defaultContent: 'n/a' },
{ data: 'first_name' },
{ data: 'last_name' },
{ data: 'email'},
{ data: 'student_number'},
{ data: 'role.name'},
{ data: 'created_at'},
{ data: null,
render: function ( data, type, row ) {
var html = "";
if (data.status == 1) {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'" checked> <label for="'+data.id+'"></label></span>';
} else {
html += '<span class="switch switch-sm"> <input type="checkbox" class="switch btn-change-status" id="'+data.id+'" data-id="'+data.id+'" data-status="'+data.status+'"> <label for="'+data.id+'"></label></span>';
}
html += "<button type='button' class='btn btn-primary btn-sm btn-edit-account mr-2' data-id='"+data.id+"' data-account='"+data.id+"'>Edit</button>";
html += "<button type='button' class='btn btn-secondary btn-sm btn-reset-password' data-id='"+data.id+"' data-account='"+data.id+"'><i class='fas fa-key'></i></button>";
return html;
}
},
],
columnDefs: [
{ className: "hidden", "targets": [0]},
{ "orderable": false, "targets": 7 }
]
});
Javascript for the random password generator and reset password
function resetPassword() {
$.ajax({
type: 'GET',
url: '/user/get-new-password',
processData: false,
success: function(data) {
$('#reset-password').val(data.password);
}
});
}
$(document).on('click', '.btn-reset-password', function() {
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
var id = $('.btn-confirmreset').attr('data-id');
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
Thank you for your help!
<form id="form-reset-password">
<div class="container my-2">
<div class="row">
<div class="col-md-12">
<div class="form-row">
<input type="hidden" id="token" name="_token" value="{{csrf_token()}}">
<input type="hidden" id="user_id" name="user_id" value=""> // initiate the hidden input here
</div>
<div class="form-group">
<label>New Password</label>
<input type="text" class="form-control" id="reset-password" name="password" readonly>
</div>
<div class="form-group text-right mt-4">
<button type="button" class="btn btn-dark" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success btn-confirmreset">Reset</button>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).on('click', '.btn-reset-password', function() {
var user_id_value = $(this).attr('data-id'); // Get the user id from attr
$('#user_id').val(user_id_value); // Assign the user id to hidden field.
$('#reset-password-modal').modal('show');
resetPassword();
});
$(document).on('submit', '#form-reset-password', function() {
var confirm_alert = confirm("Are you sure you want to reset this account's password?");
if (confirm_alert == true) {
// var id = $(this).attr('data-id');
//var id = $('.btn-confirmreset').attr('data-id'); // Remove this, it won't work , because this button doesn't contain the data-id
var id = $('#user_id').val(user_id_value); // You can get the value from hidden field
$.ajax({
url: "/auth/reset-password",
type: "POST",
data: $(this).serialize()+"&id="+id,
success: function(data) {
if (data.success === true) {
alert("Password successfully reset!");
location.reload();
}
else {
alert("Something went wrong");
}
}
});
return false;
}
});
</script>
Please refer the above code, You can pass the user id while modal pop up call and set that id to hidden value. then you can access that id from the hidden input. when you submit "form-reset-password" form.
Please look at comments on the above code
Maybe the attr() function is looking for native HTML attribute. So use the following snippet will help.
var id = $('.btn-confirmreset').data('id');

Data is updated without validation in JQuery

For some reason data validation doesn't work. Although, if I add an alert statement after valid() method inside .click(), it will alert, which means that data is considered valid anyways. I tried different approaches including making actionbutton outside form in html file, but that didn't solve the problem. What else could that be?
Currently there are no exceptions or errors.
JavaScript:
$(function () {
$("#EmployeeForm").validate({
rules: {
TextBoxTitle: { maxlength: 4, required: true, validTitle: true },
TextBoxFirstname: { maxlength: 25, required: true },
TextBoxLastname: { maxlength: 25, required: true },
TextBoxEmail: { maxlength: 40, required: true, email: true },
TextBoxPhone: { maxlength: 15, required: true }
},
errorElement: "div",
messages: {
TextBoxTitle: {
required: "required 1-4 chars.", maxlength: "required 1-4 chars.",
validTitle: "Mr. Ms. Mrs. or Dr."
},
TextBoxFirstname: {
required: "required 1-25 chars.", maxlength: "required 1-25 chars."
},
TextBoxLastname: {
required: "required 1-25 chars.", maxlength: "required 1-25 chars."
},
TextBoxPhone: {
required: "required 1-15 chars.", maxlength: "required 1-15 chars."
},
TextBoxEmail: {
required: "required 1-40 chars.", maxlength: "required 1-40 chars.",
email: "need vaild email format"
}
}
});
//custom validator
$.validator.addMethod("validTitle", function (value, element) { // custom rule
return this.optional(element) || (value == "Mr." || value == "Ms." || value == "Mrs." || value == "Dr.");
}, "");
//click event handler for the employee list
$("#employeeList").click(function (e) {
if (!e) e = window.event;
var Id = e.target.parentNode.id;
if (Id === 'employeeList' || Id === '')
Id = e.target.id;
var data = JSON.parse(localStorage.getItem('allemployees'));
clearModalFields();
//add, update or delete?
if (Id === '0') {
setupForAdd();
$('#ImageHolder').html('');
} else {
setupForUpdate(Id, data);
}
});
getAll('');
$("#srch").keyup(function () {
filterData();
});
function filterData() {
filteredData = [];
allData = JSON.parse(localStorage.getItem('allemployees'));
$.each(allData, function (n, i) {
if (~i.LastName.indexOf($("#srch").val())) {
filteredData.push(i);
}
});
buildEmployeeList(filteredData, false);
}
function loadDepartmentDDL(empdiv) {
html = '';
$('#ddlDivs').empty();
var alldepartments = JSON.parse(localStorage.getItem('alldepartments'));
$.each(alldepartments, function () {
html += '<option value="' + this['Id'] + '">' + this['DepartmentName'] + '</option>';
});
$('#ddlDivs').append(html);
$('#ddlDivs').val(empdiv);
}
$("#actionbutton").click(function () {
if ($("#EmployeeForm").valid()) {
if ($('#actionbutton').val() === 'Update') {
update();
} else {
add();
}
}
else {
$("#lblstatus").text("fix existing problems");
$("#lblstatus").css({ "color": "red" });
}
return false;
});
$('#deletebutton').click(function () {
var deleteEmployee = confirm('Really delete this employee?');
if (deleteEmployee) {
_delete();
return !deleteEmployee;
}
else {
return deleteEmployee;
}
});
function setupForUpdate(Id, data) {
$('#actionbutton').val('Update');
$('#modaltitle').html('<h4>Employee Update</h4>');
$('#deletebutton').show();
$.each(data, function (index, employee) {
if (employee.Id === parseInt(Id)) {
$('#TextBoxEmail').val(employee.Email);
$('#TextBoxTitle').val(employee.Title);
$('#TextBoxFirstname').val(employee.FirstName);
$('#TextBoxLastname').val(employee.LastName);
$('#TextBoxPhone').val(employee.Phoneno);
$('#ImageHolder').html('<img height="120" width="110" src="data:image/png;base64,' + localStorage.getItem('StaffPicture') + '"/>');
localStorage.setItem('Id', employee.Id);
localStorage.setItem('DepartmentId', employee.DepartmentId);
localStorage.setItem('Timer', employee.Timer);
loadDepartmentDDL(employee.DepartmentId);
return false;
} else {
$('#status').text('no employee found');
}
});
$('#theModal').modal('toggle');
}
function setupForAdd() {
clearModalFields();
$('#actionbutton').val('Add');
$('#modaltitle').html('<h4>Add New Employee</h4>');
$('#deletebutton').hide();
$('#theModal').modal('toggle');
}
//build the list
function buildEmployeeList(data, allemployees) {
$('#employeeList').empty();
div = $('<div class="list-group"><div>' +
'<span class="col-xs-4 h3">Title</span>' +
'<span class="col-xs-4 h3">First</span>' +
'<span class="col-xs-4 h3">Last</span>' +
'</div>');
div.appendTo($('#employeeList'))
if (allemployees) {
localStorage.setItem('allemployees', JSON.stringify(data));
}
btn = $('<button class="list-group-item" id="0">...Click to add employee</button>');
btn.appendTo(div);
$.each(data, function (index, emp) {
btn = $('<button class="list-group-item" id="' + emp.Id + '">');
btn.html(
'<span class="col-xs-4" id="employeetitle' + emp.Id + '">' + emp.Title + '</span>' +
'<span class="col-xs-4" id="employeefname' + emp.Id + '">' + emp.FirstName + '</span>' +
'<span class="col-xs-4" id="employeelastname' + emp.Id + '">' + emp.LastName + '</span>');
btn.appendTo(div);
});
}
//get all employees
function getAll(msg) {
$('#status').text('Finding employee information...');
ajaxCall('Get', 'api/employees', '')
.done(function (data) {
buildEmployeeList(data, true);
if (msg === '')
$('#status').text('Employees Loaded');
else
$('#status').text(msg + ' - Employees Loaded');
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
ajaxCall('Get', 'api/departments/', '')
.done(function (data) {
localStorage.setItem('alldepartments', JSON.stringify(data));
})
.fail(function (jqXHR, textStatus, errorThrown) {
alert('error');
});
}
function clearModalFields() {
$('#TextBoxFirstname').val('');
$('#TextBoxLastname').val('');
$('#TextBoxEmail').val('');
$('#TextBoxTitle').val('');
$('#TextBoxPhone').val('');
$('#modalStatus').text('');
localStorage.removeItem('Id');
localStorage.removeItem('DepartmentId');
localStorage.removeItem('Timer');
loadDepartmentDDL(-1);
}
function add() {
emp = new Object();
emp.Title = $("#TextBoxTitle").val();
emp.FirstName = $("#TextBoxFirstname").val();
emp.Lastname = $("#TextBoxLastname").val();
emp.Phoneno = $("#TextBoxPhone").val();
emp.Email = $("#TextBoxEmail").val();
emp.DepartmentId = $("#ddlDivs").val();
ajaxCall('post', 'api/employees/', emp)
.done(function (data) {
getAll(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
$('#theModal').modal('toggle');
return false;
}
function update() {
emp = new Object();
emp.Title = $("#TextBoxTitle").val();
emp.FirstName = $("#TextBoxFirstname").val();
emp.Lastname = $("#TextBoxLastname").val();
emp.Phoneno = $("#TextBoxPhone").val();
emp.Email = $("#TextBoxEmail").val();
emp.Id = localStorage.getItem('Id');
emp.DepartmentId = localStorage.getItem('DepartmentId');
emp.DepartmentName = $('#ddlDivs').val();
emp.Timer = localStorage.getItem('Timer');
if (localStorage.getItem('StaffPicture')) {
emp.Picture64 = localStorage.getItem('StaffPicture');
}
ajaxCall('put', 'api/employees/', emp)
.done(function (data) {
$("#status").text(data);
if (data.indexOf('not') == -1) {
$('#ImageHolder').html('<img height="120" width="110" src="data:image/png;base64,' + localStorage.getItem('StaffPicture') + '"/>')
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
$('#theModal').modal('toggle');
return false;
}
$("input:file").change(() => {
var reader = new FileReader();
var file = $('#fileUpload')[0].files[0];
if (file) {
reader.readAsBinaryString(file);
}
reader.onload = function (readerEvt) {
//get binary data then convert to encoded string
var binaryString = reader.result;
var encodedString = btoa(binaryString);
localStorage.setItem('StaffPicture', encodedString);
}
});
//delete employee
function _delete() {
ajaxCall('Delete', 'api/employees/' + localStorage.getItem('Id'), '')
.done(function (data) {
getAll(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
});
$('#theModal').modal('toggle');
}
//cal ASP.NET WEB API server
function ajaxCall(type, url, data) {
return $.ajax({
type: type,
url: url,
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processData: true
});
}
function errorRoutine(jqXHR) {
if (jqXHR.responseJSON == null) {
$('#status').text(jqXHR.responseText);
}
else {
$('#status').text(jqXHR.responseJSON.Message);
}
if (jqXHR.responseJSON === null) {
$("#lblstatus").text(jqXHR.responseText);
}
else {
$("#lblstatus").text(jqXHR.responseJSON.Message);
}
} //errrorRoutine
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>CRUD</title>
<meta charset="utf-8" />
<link href="Content/bootstrap.min.css" rel="stylesheet" />
<link href="Content/employee.css" rel="stylesheet" />
<link rel="icon" href="data:;base64,iVBORw0KGgo=" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top" style="background-color: #686868">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">#2</a>
<div class="col-xs-2"> </div>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav" id="menu">
<li>Home</li>
<li>CRUD</li>
</ul>
<div class="input-group col-xs-push-3 col-sm-2 col-xs-4 navbar navbar-brand" style="position:absolute; left:1200px;">
<span class="input-group-addon">
<span class="glyphicon glyphicon-search"></span>
</span>
<input type="text" id="srch" class="form-control form-md">
</div>
<div id="version" style="color:white; float:right;"><p>v2.0</p></div>
</div>
</nav>
<div class="container">
<div style="padding-top:15%;">
<div class="panel panel-default">
<div class="panel-heading text-center" id="status" style="font-weight:bold;"></div>
<div class="panel-body">
<div id="employeeList"></div>
</div>
</div>
</div>
</div>
<form id="EmployeeForm" name="EmployeeModalForm" method="post" action="">
<div class="modal fade" id="theModal" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">X</button>
<div id="modelTitle"></div>
<h4>Employee Update - v2.0</h4>
</div>
<div class="modal-body">
<div class="panel panel-default">
<div class="panel-heading text-center">
Employee Information
</div>
<div class="panel-body">
<div class="row">
<div class="col-xs-4">Title:</div>
<div class="col-xs-8"><input type="text" placeholder="enter title" id="TextBoxTitle" class="form-control" /></div>
</div>
<div class="row">
<div class="col-xs-4">First:</div>
<div class="col-xs-8"><input type="text" placeholder="enter first name" id="TextBoxFirstname" class="form-control" value="Joe" /></div>
</div>
<div class="row">
<div class="col-xs-4">Surname:</div>
<div class="col-xs-8"><input type="text" placeholder="enter last name" id="TextBoxLastname" class="form-control" value="Blow" /></div>
</div>
<div class="row">
<div class="col-xs-4">Phone#:</div>
<div class="col-xs-8"><input type="text" placeholder="enter phone" id="TextBoxPhone" class="form-control" value="(555)555-5555" /></div>
</div>
<div class="row">
<div class="col-xs-4">Email:</div>
<div class="col-xs-8"><input type="text" placeholder="enter email" id="TextBoxEmail" class="form-control" value="jb#ss.com" /></div>
</div>
<div class="row">
<div class="col-xs-4"><strong>Department:</strong></div>
<div class="col-xs-8">
<select id="ddlDivs" name="ddlDivs" class="form-control"></select>
</div>
</div>
<div class="row">
<div class="col-xs-4">Picture:</div>
<div class="col-xs-8" id="ImageHolder" style="padding-top:2%;" />
</div>
</div>
<div class="panel-footer"> </div>
</div>
</div>
<div class="modal-footer">
<div class="col-xs-8"><input id="fileUpload" type="file" /></div>
<div class="col-xs-4"><input type="submit" value="Update" id="actionbutton" class="btn btn-default" style="position:absolute; right:100px; z-index:100; top:30px" /></div>
<div class="col-xs-4"><input type="button" value="Delete" id="deletebutton" class="btn btn-danger" style="position:absolute; top:30px; right:5px;" /></div>
<label class="col-xs-12 text-center row" id="lblstatus" style="padding-top:10px;"></label>
<div id="status" class="text-left" style="padding-top:5%;"></div>
</div>
</div>
</div>
</div>
</form>
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script src="Scripts/jquery.validate.min.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="Scripts/employeecrud.js?newversion"></script> <!--Google Chrome does not load the newest version of the code. Adding unique string helps-->
</body>
</html>
jQuery validator works off of the name of the element not its id.
So for lets say for example on your email input you should add: name="TextBoxEmail"
Like this:
<input type="text" placeholder="enter email" id="TextBoxEmail" name="TextBoxEmail"
class="form-control" value="jb#ss.com" />

How to change the url

I want to change the URL of the update operation. The end point of the URL should be gotten from an input. How can I achieve this? The following doesn't work.
$(document).ready(function(){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return {"issue":o};
};
<form role="form">
<div class="form-group input-group">
<div class="row">
<div class="col-md-6">
<label>Issue ID * </label>
<select class="form-control selectclass" id="issueid"></select>
</div>
<div class="col-md-6">
<label>Tracker * </label>
<select class="form-control" name="tracker" id="tracker">
<option value="1">Bug</option>
<option value="2">Feature</option>
<option value="3">Support</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label>Subject </label>
<input class="form-control" placeholder="Issue Subject" name="subject" id="subject">
</div>
<div class="form-group">
<label>Description</label>
<textarea class="form-control" rows="6" name="description" id="description"></textarea>
</div>
<button type="submit" id="submit" class="btn btn-default">Submit Button</button>
<button type="reset" class="btn btn-default">Reset Button</button>
</form>
$('#submit').on('click', function(){
var x=document.getElementById('issueid').value;
$.ajax({
type : 'PUT',
url: 'http://localhost/redmine/issues'+ x +'.json',
contentType:'application/json',
data:JSON.stringify($('form').serializeObject()), // post data || get data
success : function(msg, status, jqXHR) {
console.log(msg, status, jqXHR);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
console.log(x);
});
});
Inputs are gotten from a form and sent to Redmine API. URL should look like below, http://localhost/redmine/issues/2.json
When dynamically populating your id="issueid" select make sure that you properly set the value attribute of the options:
$('.selectclass').append('<option value="' + value.id + '">' + value.id + '<option>');
Also fix the url for your next AJAX request by adding a trailing / after issues:
url: 'http://localhost/redmine/issues/' + x + '.json'

Categories