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

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');

Related

Javascript - After creating a div, Ajax is not working

I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}

laravel 422 (Unprocessable Entity) ajax file upload

I am using Laravel 6 and i would also like to say that i am not that much experienced working on Laravel.
I have searched SO and google as well but not got any solution to this problem. Below are the files and code
PordController.php
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Prod;
use App\Section;
use Illuminate\Support\Facades\Validator;
class ProdsController extends Controller
{
function __construct () {
$this->middleware('role:admin');
}
public function index(Request $request)
{
$tasks = Prod::orderBy('id', 'desc')->get();
$section = Section::all();
$arr['tasks'] = $tasks;
$arr['sections'] = $section;
return view('admin.pords',$arr);
}
public function store(Request $request)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
if ($files = $request->file('fileUpload')) {
$destinationPath = public_path('images'); // upload path
$profileImage = rand() .".". $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
}
$task = Prod::create($request->all());
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function show($id)
{
$task = Prod::find($id);
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$task = Prod::find($id);
$task->name = $request->input('name');
$task->save();
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
public function destroy($id)
{
$task = Prod::destroy($id);
return response()->json([
'error' => false,
'task' => $task,
], 200);
}
}
prods_add.blade.php
<!-- Add Task Modal Form HTML -->
<div class="modal fade" id="addTaskModal">
<div class="modal-dialog">
<div class="modal-content">
<form id="frmAddTask" enctype="multipart/form-data" method="POST">
<div class="modal-header">
<h4 class="modal-title">
add
</h4>
<button aria-hidden="true" class="close" data-dismiss="modal" type="button">
×
</button>
</div>
<div class="modal-body">
<div class="alert alert-danger" id="add-error-bag">
<ul id="add-task-errors">
</ul>
</div>
<div class="form-group">
<label>
name
</label>
<input class="form-control" id="name" name="name" required="" type="text">
</input>
</div>
<div class="form-group">
<label>
desc
</label>
<input class="form-control" id="desc" name="description" required="" type="text">
</input>
</div>
<div class="form-group">
<label>
member
</label>
<input class="form-control" id="member" name="member" required="" type="number">
</input>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>
isfiles allow
</label>
<input class="form-control" type="checkbox" id="isfile" name="isfile" value="true" checked>
</input>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>
camera allow
</label>
<input class="form-control" type="checkbox" id="isvideo" name="isvideo" value="true" checked>
</input>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>
mic allow
</label>
<input class="form-control" type="checkbox" id="ismic" name="ismic" value="true" checked>
</input>
</div>
</div>
</div>
<div class="form-group">
<label>
sections
</label>
<select id="section_id" name="section_id" class="form-control">
#foreach ($sections as $section)
<option value="{{$section->id}}">{{$section->name}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<div class="form-group">
<label for="file"> <div class="btn btn-primary btn-sm float-left">
<span>Choose file</span>
</div></label>
<input style="color:black" type="file" class="form-control-file" id="file" name="fileUpload">
</div>
</div>
</div>
<div class="modal-footer">
<input class="btn btn-default" data-dismiss="modal" type="button" value="cancel">
<button class="btn btn-info" id="btn-add" type="button" value="add">
add
</button>
</input>
</div>
</form>
</div>
</div>
</div>
pords.js
$(document).ready(function() {
$("#btn-add").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var car = 0;
var car1 = 0;
var car2 = 0;
var x = document.getElementById("isfile").checked;
if(x === true){
car = 1;
}
if(document.getElementById("isvideo").checked === true){
car1 = 1;
}
if(document.getElementById("ismic").checked === true){
car2 = 1;
}
console.log($("#file").get(0).files[0]);
var filess = $("#file").get(0).files[0];
$.ajax({
type: 'POST',
url: '/admincp/prods',
data: {
name: $("#frmAddTask input[name=name]").val(),
description: $("#frmAddTask input[name=description]").val(),
display: 1,
sessionid: 'sadasdasdasdasd',
password: 'sadasdasdasdasd',
fileUpload: filess,
img: "path",
member: $("#frmAddTask input[name=member]").val(),
isfile: car,
isvideo: car1,
ismic: car2,
section_id: $("#frmAddTask select[name=section_id]").val(),
},
processData: false,
dataType: 'json',
success: function(data) {
$('#frmAddTask').trigger("reset");
$("#frmAddTask .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#add-task-errors').html('');
$.each(errors.messages, function(key, value) {
$('#add-task-errors').append('<li>' + value + '</li>');
});
$("#add-error-bag").show();
}
});
});
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/admincp/prods/' + $("#frmEditTask input[name=id]").val(),
data: {
name: $("#frmEditTask input[name=name]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditTask').trigger("reset");
$("#frmEditTask .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-task-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-task-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
$("#btn-delete").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'DELETE',
url: '/admincp/prods/' + $("#frmDeleteTask input[name=id]").val(),
dataType: 'json',
success: function(data) {
$("#frmDeleteTask .close").click();
window.location.reload();
pushnotify('تم الحذف بنجاح ');
},
error: function(data) {
console.log(data);
}
});
});
});
function addTaskForm() {
$(document).ready(function() {
$("#add-error-bag").hide();
$('#addTaskModal').modal('show');
});
}
function editTaskForm(task_id) {
$.ajax({
type: 'GET',
url: '/admincp/prods/' + task_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditTask input[name=name]").val(data.task.name);
$("#frmEditTask input[name=id]").val(data.task.id);
$('#editTaskModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
function deleteTaskForm(task_id) {
$.ajax({
type: 'GET',
url: '/admincp/prods/' + task_id,
success: function(data) {
$("#frmDeleteTask #delete-title").html("Delete Task (" + data.task.name + ")?");
$("#frmDeleteTask input[name=id]").val(data.task.id);
$('#deleteTaskModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
The error in js file because without fetching the image value works great
When I add a value the image gets the error
The problem could be here:
$task = Prod::create($request->all());
try to make
public function store(Request $request)
{
dd($request->all());
}
and in network see the response.
also, when you make Prod::create($request->all());
it request everything like __token and so on

Select gets double options after submit form modal

I got a problem with a bootstrap modal form and dynamic select options.
When I open the modal, there is an input and two select options.
One select is populating the second after a user check an option from
the first select.
On the first load, the select options are working ok.
When I submit the form (with Save button) and I reopen the modal, the first select gets the correct options but the second got double options.
When I reload the page everything gets back to normal until I submit the form again.
$(document).ready(function () {
var table = $('table.setting-groups');
var table_permissions = $('table.settings-groups-permissions');
var table_permissions_edit = $('table.settings-groups-permissions-edit');
var permissions = [];
var dataArray = [];
$('#addGroupModal').on('shown.bs.modal', function (e) {
$('select#permission_category').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source')
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
$('select#permission_category').change(function () {
var category = $('select#permission_category').val();
if (category !== '') {
$('select#permission_category_description').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source'),
data: {category: category}
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
} else {
$('select#permission_category_description')[0].empty();
}
});
$('select#permission_category_description').change(function () {
var category = $('select#permission_category').val();
var description = $('select#permission_category_description').val();
var check = $.inArray(description, permissions) > -1;
if (!check) {
permissions.push(description);
table_permissions.DataTable().row.add({
"category": category,
"description": description
}).draw();
}
});
// Save permissions
$('form#add-group').submit(function (e) {
$('#savebtn').button('loading');
e.preventDefault();
var form = $(this);
// Push table data (permissions) to form for submit
$('<input>').attr({
type: 'hidden',
id: 'permissions',
name: 'permissions',
value: permissions
}).appendTo(form);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
$('#addGroupModal').modal('toggle');
swal(
'Επιβεβαίωση Καταχώριση',
'Η ομάδα δικαιωμάτων καταχωρήθηκε επιτυχώς',
'success'
).then(function () {
permissions = [];
dataArray = [];
form[0].reset();
$('select#permission_category_description').empty();
table_permissions.DataTable().destroy();
table.DataTable().ajax.reload();
});
},
error: function (data) {
swal(
'Αποτυχία Καταχώρισης',
data.responseText,
'error'
)
}
});
});
// Remove row when you click X
table_permissions.on('click', '.delete', function () {
table_permissions.DataTable().row('.selected').remove().draw(false);
});
});
$('#addGroupModal').on('hide.bs.modal', function (e) {
// Clean forms / select / datatables / arrays on modal close
$('select#permission_category_description').empty();
$('form')[0].reset();
table_permissions.DataTable().destroy();
permissions = [];
dataArray = [];
});
$('#editGroupModal').on('shown.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id');
$.post('../../custom/json/groups.php?view', {id: id}, function (arr) {
$('input#group_name').val(arr.description);
// Get existing permissions from groups
dataArray = arr.data.map(function (value) {
return value.description;
});
});
$('select#permission_category_edit').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source')
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
$('select#permission_category_edit').change(function () {
var category = $('select#permission_category_edit').val();
if (category !== '') {
$('select#permission_category_description_edit').each(function () {
var $select = $(this);
$select.empty().append('<option></option>');
$.ajax({
url: $select.attr('data-source'),
data: {category: category}
}).then(function (options) {
options.map(function (option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
});
});
} else {
$('select#permission_category_description_edit')[0].empty();
}
});
$('select#permission_category_description_edit').change(function () {
var category = $('select#permission_category_edit').val();
var description = $('select#permission_category_description_edit').val();
permissions = dataArray;
var check = $.inArray(description, permissions) > -1;
if (!check) {
permissions.push(description);
table_permissions_edit.DataTable().row.add({
"category": category,
"description": description
}).draw();
}
});
var settingGroupsPermissionsEdit = {
"destroy": true,
"processing": true,
"deferRender": true,
"responsive": true,
"select": true ,
"searching": false,
"paging": false,
"info": false,
"ordering": false,
"language": {
"url": "/custom/js/data-tables/Greek.json"
},
"ajax": "../../custom/json/groups.php?view&id=" + id,
"dataSrc": "data",
"columns": [
{data: "category", className: "text-center"},
{data: "description", className: "text-center"},
{
data: null, className: "text-center btn-actions", render: function (data, type, row) {
return '<a data-id="' + data.description + '" class="danger p-0 delete"><i class="ft-x font-medium-3 mr-2"></i></a>';
}
}
]
};
$('table.settings-groups-permissions-edit').DataTable($.extend(true, {}, settingGroupsPermissionsEdit, {}));
// Save permissions
$('form#edit-group').submit(function (e) {
$('#editbtn').button('loading');
e.preventDefault();
var form = $(this);
// Push table data (permissions) to form for submit
$('<input>').attr({
type: 'hidden',
id: 'permissions',
name: 'permissions',
value: permissions
}).appendTo(form);
$.ajax({
url: form.attr('action') + '&id=' + id,
type: form.attr('method'),
data: new FormData(this),
dataType: 'json',
processData: false,
contentType: false,
success: function (data) {
$('#editGroupModal').modal('toggle');
swal(
'Επιβεβαίωση Ενημέρωσης',
'Η ομάδα δικαιωμάτων ενημερώθηκε επιτυχώς',
'success'
).then(function () {
permissions = [];
dataArray = [];
form[0].reset();
$('select#permission_category_description_edit').empty();
table_permissions_edit.DataTable().destroy();
table.DataTable().ajax.reload();
});
},
error: function (data) {
swal(
'Αποτυχία Ενημέρωσης',
data.responseText,
'error'
)
}
});
});
// Remove row when you click X
table_permissions_edit.on('click', '.delete', function () {
var row_desc = table_permissions_edit.DataTable().rows('.selected').data().pluck('description')[0];
permissions = remove(permissions, row_desc); // remove element from posted permissions array
table_permissions_edit.DataTable().row('.selected').remove().draw();
});
});
$('#editGroupModal').on('hide.bs.modal', function (e) {
// Clean forms / select / datatables / arrays on modal close
$('select#permission_category_description_edit').empty();
$('form')[0].reset();
table_permissions_edit.DataTable().destroy();
permissions = [];
dataArray = [];
});
// Delete group
table.on('click', '.swal-delete', function () {
var id = $(this).data('id');
swal({
title: 'Διαγραφή',
text: 'Είστε σίγουρος/η οτι θέλετε να διαγράψετε την ομάδα δικαιωμάτων;',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#0CC27E',
cancelButtonColor: '#FF586B',
confirmButtonText: 'Ναι',
cancelButtonText: 'Όχι'
}).then(function (isConfirm) {
if (isConfirm) {
$.post("../../custom/json/groups.php?delete", {id: id}, function (data) {
swal(
'Επιβεβαίωση Διαγραφής',
'Η ομάδα δικαιωμάτων διαγράφηκε επιτυχώς',
'success'
).then(function () {
table.DataTable().ajax.reload();
});
});
}
}).catch(swal.noop);
});
// Remove element from an array
function remove(array, value) {
return array.filter(function (element) {
return element !== value;
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- BEGIN ADD GROUP MODAL-->
<div class="modal fade text-left" id="addGroupModal" role="dialog" aria-labelledby="addGroupModal" style="display: none;" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<form id="add-group" action="/custom/json/groups.php?add" method="post" class="form form-horizontal" autocomplete="off" enctype="multipart/form-data">
<div class="modal-header bg-medi white">
<h4 class="modal-title" id="addGroupModal"><i class="ft-list font-medium-3 mr-2"></i> Προσθήκη Νέας Ομάδας</h4>
</div>
<div class="modal-body mt-1">
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control mt-1" for="group_name">Όνομα Ομάδας: </label>
<div class="col-md-5">
<input type="text" id="group_name" class="form-control" name="group_name">
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category">Κατηγορία</label>
<div class="col-md-5">
<select id="permission_category" name="permission_category" class="form-control"
data-source="/custom/json/groups.php?permission-category"
data-valueKey="category"
data-displayKey="category">
</select>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_description">Πρόσβαση</label>
<div class="col-md-5">
<select id="permission_category_description" name="permission_category_description" class="form-control"
data-source="/custom/json/groups.php?permission-description"
data-valueKey="description"
data-displayKey="description">
</select>
</div>
</fieldset>
<div class="table-responsive">
<table class="table table-condensed table-bordered table-sm base-style table-hover full-width settings-groups-permissions">
<thead class="bg-medi text-white text-center">
<tr>
<th>Κατηγορία</th>
<th>Πρόσβαση</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Κλείσιμο</button>
<button type="submit" class="btn btn-medi white" id="savebtn" data-loading-text="Αποθήκευση...">Αποθήκευση</button>
</div>
</form>
</div>
</div>
</div>
<!-- END ADD GROUP MODAL-->
<!-- BEGIN EDIT GROUP MODAL-->
<div class="modal fade text-left" id="editGroupModal" role="dialog" aria-labelledby="editGroupModal" style="display: none;" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<form id="edit-group" action="/custom/json/groups.php?edit" method="post" class="form form-horizontal" autocomplete="off" enctype="multipart/form-data">
<div class="modal-header bg-medi white">
<h4 class="modal-title" id="editGroupModal"><i class="ft-list font-medium-3 mr-2"></i> Επεξεργασία Ομάδας</h4>
</div>
<div class="modal-body mt-1">
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control mt-1" for="group_name">Όνομα Ομάδας: </label>
<div class="col-md-5">
<input type="text" id="group_name" class="form-control" name="group_name" disabled>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_edit">Κατηγορία</label>
<div class="col-md-5">
<select id="permission_category_edit" name="permission_category" class="form-control"
data-source="/custom/json/groups.php?permission-category"
data-valueKey="category"
data-displayKey="category">
</select>
</div>
</fieldset>
<fieldset class="form-group floating-label-form-group row">
<label class="col-md-4 label-control" for="permission_category_description_edit">Πρόσβαση</label>
<div class="col-md-5">
<select id="permission_category_description_edit" name="permission_category_description" class="form-control"
data-source="/custom/json/groups.php?permission-description"
data-valueKey="description"
data-displayKey="description">
</select>
</div>
</fieldset>
<div class="table-responsive">
<table class="table table-condensed table-bordered table-sm base-style table-hover full-width settings-groups-permissions-edit">
<thead class="bg-medi text-white text-center">
<tr>
<th>Κατηγορία</th>
<th>Πρόσβαση</th>
<th></th>
</tr>
</thead>
</table>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Κλείσιμο</button>
<button type="submit" class="btn btn-medi white" id="editbtn" data-loading-text="Αποθήκευση...">Αποθήκευση</button>
</div>
</form>
</div>
</div>
</div>
<!-- END EDIT GROUP MODAL-->
Any suggestions ? I can't find where is the issue that causes js to run twice on select populate options.
Thank you in advance
UPDATE: The 2nd select option is doubled on modal show not on form submit.
Because you bind $('select#permission_category').change inside $('#addGroupModal').on('shown.bs.modal' handler so each time your modal show, it will bind $('select#permission_category').change another time. That's why when you open the modal second time, the 2nd select option is doubled and will be tripled on third time...
You can solve it by:
Option 1: Move $('select#permission_category').change to be outside of $('#addGroupModal').on('shown.bs.modal' handler.
Option 2: Remove $('select#permission_category') change handler using .off() when closing modal or before bind it in $('#addGroupModal').on('shown.bs.modal' handler.
Option 3: Create all options first then use .html() instead of .append() to set the html contents of select (this still bind change multiple time but the options is not multipled)

val and fadeOut not working on click

i'm creating a ajax post request that works fine. however to make it more appealing i'm trying to implement so that when the user click on #sign_in it will change the text while request is going on. if it result in error a message will appear. this message will automatically remove after a couple of seconds. however if u click .close it will force close. The issue is however that following does not work:
$(".alert a").click(function(e) {
$('.alert').fadeOut();
});
Nothing happens when i click on .close. in addition to this below does not work either.
$('#sign_in').val('Logger ind...');
Full Code
<form id="sign_in">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
</div>
<a href="#">
<small>Forgot password?</small>
</a>
<div class="form-group text-center add_top_20">
<input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
<div class="alert alert-error alert-danger" style="display: none;">
<a class="close" href="#">×</a>
Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
jquery
$("#sign_in").submit(function (event) {
// Change sign in button text
$('#sign_in').val('Logger ind...');
// post request
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "/account/login/auth/",
type: "POST",
dataType : 'json',
contentType: 'application/json',
data: {
'username': username,
'password': password
}, success: function (data) {
if (data.success) {
alert('success');
} else {
showAlert()
}
// Change sign in text back
$('#sign_in').val('Log ind');
}, error: function(error){
// Change sign in text back
$('#sign_in').val('Log ind');
}
});
});
function showAlert(){
if(!$('.alert').is(':visible'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
$(".alert a").click(function(e) {
$('.alert').fadeOut();
});
and all of this is wrapped in $(document).ready(function () {
Mmm, your event is launching but you need to use clearQueue in order to launch your fadeOut animation again interrupting the previous one.
$(".alert a").click(function(e) {
$('.alert').clearQueue();
$('.alert').fadeOut();
});
Change your form id or submit button id and change :visible to :hidden
function showAlert(){
if($('.alert').is(':hidden'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
Here I have change form 'id'
<form id="sign_in_form">
<div class="form-group">
<input type="text" name="username" id="username" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="password" name="password" id="password" class="form-control" placeholder="Kodeord">
</div>
<a href="#">
<small>Forgot password?</small>
</a>
<div class="form-group text-center add_top_20">
<input class="btn_1 medium" id="sign_in" type="submit" value="Log ind">
<input type="hidden" name="next" value="{{ next }}" />
</div>
</form>
<div class="alert alert-error alert-danger" style="display: none;">
<a class="close" href="#">×</a>
Invalid email or password. Try clicking 'Forgot Password' if you're having trouble signing in.
</div>
jQuery
$("#sign_in_form").submit(function (event) {
// Change sign in button text
$('#sign_in').val('Logger ind...');
// post request
event.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
url: "/account/login/auth/",
type: "POST",
dataType : 'json',
contentType: 'application/json',
data: {
'username': username,
'password': password
}, success: function (data) {
if (data.success) {
alert('success');
} else {
showAlert()
}
// Change sign in text back
$('#sign_in').val('Log ind');
}, error: function(error){
// Change sign in text back
$('#sign_in').val('Log ind');
}
});
});
function showAlert(){
if($('.alert').is(':hidden'))
{
$('.alert').fadeIn()
$('.alert').delay(4000).fadeOut()
}
}
$(".alert a").click(function(e) {
$('.alert').clearQueue();
$('.alert').fadeOut();
});

I'm trying to upload a file using node and ajax but the ajax call isn't working?

I'm facing error on Upload xml and upload csv am a rookie so please can you provide me a elaborate answer
I've tried debugging the code on clicking upload button till upload function is working fine on jumping to uploadxml() function the data is not sent.
My HTML code
<div class="file-upload">
<form id="file-upload-form">
<div class="upload">
<div class="col-lg-6">
<div class="input-group" id="one">
<input type="text" class="form-control" id="t1" placeholder="Select an xml file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="xmlbtn">Browse</button>
</span>
</div>
<input type="file" accept=".xml" class="hidden" id="xmlPicker" name="xmlFile"/>
</div>
<div class="col-lg-6">
<div class="input-group" id="two">
<input type="text" class="form-control" id="t2" placeholder="Select an csv file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="csvbtn">Browse</button>
</span>
</div>
<input type="file" class="hidden" accept=".csv" id="csvPicker" name="csvFile"/>
</div>
</div>
<div class="uploadfooter">
<button class="btn btn-default center" type="button" id="upload">Upload</button>
</div>
</form>
</div>
My Js
$(document).ready(function () {
$(".ts-sidebar-menu li a").each(function () {
if ($(this).next().length > 0) {
$(this).addClass("parent");
};
})
var menux = $('.ts-sidebar-menu li a.parent');
$('<div class="more"><i class="fa fa-angle-down"></i></div>').insertBefore(menux);
$('.more').click(function () {
$(this).parent('li').toggleClass('open');
});
$('.parent').click(function (e) {
e.preventDefault();
$(this).parent('li').toggleClass('open');
});
$('.menu-btn').click(function () {
$('nav.ts-sidebar').toggleClass('menu-open');
});
$('#zctb').DataTable();
$("#input-43").fileinput({
showPreview: false,
allowedFileExtensions: ["zip", "rar", "gz", "tgz"],
elErrorContainer: "#errorBlock43"
// you can configure `msgErrorClass` and `msgInvalidFileExtension` as well
});
$("#xmlbtn").bind("click", function(){
$("#xmlPicker").trigger("click");
});
$("#xmlPicker").bind("change", function(e){
$("#t1").val($("#xmlPicker")[0].files[0].name);
})
$("#csvbtn").bind("click", function () {
$("#csvPicker").trigger("click");
});
$("#csvPicker").bind("change", function (e) {
$("#t2").val($("#csvPicker")[0].files[0].name)
})
$("#upload").on("click",function () {
var firstfile = $("#t1").val();
var secondfile = $("#t2").val();
if(!firstfile || firstfile != null){
updateXml();
}
if(!secondfile || secondfile != null){
updatecsv();
}
})
function updateXml(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
function updatecsv(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
});
This line here:
var form = $("#file-upload-form").val()
A form does not have a value, its inputs have one. FormData expects a form, so you need to give it a reference to it.
var form = $("#file-upload-form");
var data = new FormData(form[0]); //expects a DOM form

Categories