Modal Validation with Javascript in laravel form - javascript

My code uses a modal for form display, and I want to make the modal unlock when validation is active.
but after i add some javascript function line, it still doesn't work.
My Modal
<div class="modal fade" id="passwordModal{{Auth::user()->id}}">
<div class="modal-dialog modal-lg-6">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="passwordModal">Update Password</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="{{ route('password.update') }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="content">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<input name="current_password" type="password" id="current_password" placeholder="Curent Password" class="form-control #error('current_password') is-invalid #enderror">
<span class="text-danger" id="current_passwordError"></span>
<div class="invalid-feedback">
#error('current_password')
{{ $message }}
#enderror
</div>
</div>
<div class="form-group">
<input name="password" id="password" type="password" placeholder="New Password" class="form-control #error('password') is-invalid #enderror">
<span class="text-danger" id="passwordError"></span>
<div class="invalid-feedback">
#error('password')
{{ $message }}
#enderror
</div>
</div>
<div class="form-group">
<input name="password_confirmation" type="password" id="password_confirmation" placeholder="Confirm New Password" class="form-control #error('password_confirmation') is-invalid #enderror">
<span class="text-danger" id="password_confirmationError"></span>
<div class="invalid-feedback">
#error('password_confirmation')
{{ $message }}
#enderror
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Update</button>
</div>
</div>
</form>
</div>
</div>
</div>
and my function js
<script>
function openModal() {
$('#passwordModal{{Auth::user()->id}}').modal('show')
}
function storeData() {
var CSRF_TOKEN = $('meta[name="csrf - token"]').sttr('content');
var current_password = $('#current_password').val();
var password = $('#password').val();
var password_confirmation = $('#password_confirmation').val();
$('#current_passwordError').addClass('d-none');
$('#passwordError').addClass('d-none');
$('#password_confirmationError').addClass('d-none');
$.ajax({
type: 'POST',
url: "{{ route('password.update') }}",
data: {
_token: CSRF_TOKEN,
current_password: current_password,
password: password,
password_confirmation: password_confirmation,
},
success: function(data) {
},
error: function(data) {
var errors = data.responseJSON;
if ($.isEmptyObject(errors) == false) {
$.each(errors.errors, function(key, value) {
var ErrorID = '#' + key + 'Error';
$(ErrorID).removeClass("d-none");
$(ErrorID).text(value)
})
}
}
});
}
is my script correct, or is there another way that is more effective.
before I could use ?
is my script correct, or is there another way that is more effective.
before i was able to handle this case in ci-3, but when i used that code in laravel it didn't work, that's why i tried another way and this is the result.

Related

HTML required attribute not working with AJAX submission

HTML required attribute not working with AJAX submission
I have created a model Form and set its input field to require attribute but its not working with ajax
<div class="modal fade hide" id="ajax-book-model" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="ajaxBookModel">Add New Machine</h5>
<!-- <button type="reset" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> -->
<button type="button" class="btn-close" data-dismiss="modal" aria-label="Close" onClick="window.location.reload();">
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="addEditBookForm" name="addEditBookForm" class="form-horizontal" method="POST">
<input type="hidden" name="id" id="id">
<input type="hidden" name="user_id" id="user_id" value="{{ Auth::user()->id }}">
<div class="row">
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Name</label>
<input type="text" id="machine_name" name="machine_name" class="form-control form-control-sm" placeholder="Enter Machine Name" required>
<span class="text-danger">{{ $errors->first('machine_name') }}</span>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>IOT Device ID</label>
<input type="text" id="iot_device_id" name="iot_device_id" class="form-control form-control-sm" placeholder="Enter IOT Device ID" required>
</div>
</div>
<div class="col-sm-12 col-md-4">
<div class="form-group">
<label>Local device ID</label>
<input type="text" id="local_device_id" name="local_device_id" class="form-control form-control-sm" placeholder="Enter Local Device ID" required>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-gradient-danger mb-2" data-dismiss="modal" onClick="window.location.reload();">Close</button>
<button type="submit" id="btn-save" value="addNewBook" class="btn btn-sm btn-gradient-danger mb-2">Save</button>
</div>
</form>
</div>
</div>
</div>
and this is ajax code
i just want to run simpal html required field validation with ajax
$('body').on('click','#btn-save', function (event){
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save"). attr("disabled", true);
// ajax
$.ajax({
type:"POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id:id,
user_id:user_id,
machine_name:machine_name,
iot_device_id:iot_device_id,
local_device_id:local_device_id,
},
dataType: 'json',
success: function(res){
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
}
});
});
i just want to run required field validation with ajax i could not find any solution .
Try changing your btn click event to form submit event.
$('body').on('submit', '#addEditBookForm', function (event) {
event.preventDefault();
var id = $("#id").val();
var user_id = $("#user_id").val();
var machine_name = $("#machine_name").val();
var iot_device_id = $("#iot_device_id").val();
var local_device_id = $("#local_device_id").val();
$("#btn-save").html('Please Wait...');
$("#btn-save").attr("disabled", true);
// ajax
$.ajax({
type: "POST",
url: "{{ url('add-update-piezometer') }}",
data: {
id: id,
user_id: user_id,
machine_name: machine_name,
iot_device_id: iot_device_id,
local_device_id: local_device_id,
},
dataType: 'json',
success: function (res) {
window.location.reload();
$("#btn-save").html('Submit');
$("#btn-save").attr("disabled", false);
}
});
});
The following should help: change to a form confirmation event instead of a Click button event. And do not forget to write this code so that the page does not reload:
event.preventDefault();

Display error message in modal, after validation error in laravel

I have a problem displaying errors message in update modal form. I'm using laravel request for validation and AJAX to submit form inside a modal. I would like to see the error message for each field that are inputted incorrectly. However, I'm getting this error:
The Given data is invalid
I checked the network tab, and I'm seeing the errors there but I can't figure out why this is not showing in my fields.
Here is my script's
function updatePassword(e, t)
{
e.preventDefault();
const url = BASE_URL + '/admin/organizations/operators/updatePassword/' + $(updatePasswordForm).find("input[name='id']").val();
var form_data = $(t).serialize();
// loading('show');
axios.post(url, form_data)
.then(response => {
notify(response.data.message, 'success');
$(updatePasswordModal).modal('hide');
// roleTable.ajax.reload()
})
.catch(error => {
const response = error.response;
if (response) {
if (response.status === 422)
validationForm(updatePasswordForm, response.data.errors);
else if(response.status === 404)
notify('Not found', 'error');
else
notify(response.data.message, 'error');
}
})
.finally(() => {
// loading('hide');
});
}
Here is my Blade file
<form id="updatePasswordForm" onsubmit="updatePassword(event, this)">
<input type="hidden" name="id" value="">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> {{ __('Update Password') }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-sm-4 col-form-label required">{{ __('New Password') }}</label>
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password') error #enderror">
<input type="password" class="form-control" id="password" name="user[password]" placeholder="{{ __('Password') }}" required>
</div>
</div>
</div>
#error('user.password')
<p class="error-message">{{ $message }}</p>
#enderror
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label required">{{ __('Confirm Password') }}</label>
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
</div>
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-secondary mr-3" data-dismiss="modal">{{ __('Close') }}</button>
<button type="submit" class="btn btn-primary">{{ __('Save') }} </button>
</div>
</div>
</form>
Here is My Controller:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Organization\Operator\UpdatePasswordRequest;
use App\Models\OrganizationOperator;
use Illuminate\Http\Request;
use App\Services\Response;
use Exception;
use Illuminate\Support\Facades\Log;
class OrganizationController extends Controller
{
public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
{
try {
$data = $request->validated();
$user = $data['user'];
// dd($user['password']);
$operator->update([
'password' => bcrypt($user['password']),
]);
return Response::success(__('Successfully updated'));
} catch (Exception $e) {
Log::error($e->getMessage());
return Response::error(__('Unable to update'), [], 500);
}
}
}
Here is my Request Validation Class:
<?php
namespace App\Http\Requests\Admin\Organization\Operator;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePasswordRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'id' => ['required', 'integer', 'exists:organization_operators,id'],
'user.password' => ['required', 'string', 'min:8', 'confirmed'],
];
}
}
First, I think this issue is because you send the request from the client side (which is is ajax/axios). The validation work when you submit to the server side (without ajax/axios) then response validation will display to the blade/html.
In this case, you must set error to the html manually (with innerHTML or .html() in jquery) using class/id.
for example this response from the server/api :
{ "error" : {
"user.password" : ["invalid password"],
...
}
}
in client side, you need to put that message to html tag in that case with p tag.
<p id="error-password" ></p>
$('#error-password').html(error["user.password"])
// or
$('#error-password').text(error["user.password"])
Finally I solved this problem.
1. I change my controller
public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
TO
public function updateOperatorPasswordApi(User $user, UpdatePasswordRequest $request)
AND
try {
$data = $request->validated();
$user = $data['user'];
// dd($user['password']);
$operator->update([
'password' => bcrypt($user['password']),
]);
return Response::success(__('Successfully updated'));
}
TO
try {
$data = $request->validated();
$user->update([
'password' => bcrypt($data['password']),
]);
return Response::success(__('Successfully created'));
}
2. I change my blade file
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
TO
<div class="form-group">
<label for="">{{ __('Password') }}</label>
<input name="password" type="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="{{ __('Password') }}" required>
<small class="form-text error-message"></small>
</div>
AND
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
TO
<div class="form-group">
<label for="">{{ __('Confirm Password') }}</label>
<input name="password_confirmation" type="password" class="form-control" id="password_confirmation" aria-describedby="emailHelp" placeholder="{{ __('Confirm Password') }}" required>
<small class="form-text error-message"></small>
</div>

Show a succes/error message if data was/wasn't stored in data base on the same form page

I have a form from where the user imput data to the database and a php file with the function to do so.
I'd like to show an alert message on the same form page using javascript without refresing the page.
I don't know much about JS and I have tried every possible solution I came across but I cannot find the solution yet, what am I doing wrong? I hope someone could help me.
Edit: I decided to use modals to do this but modal is not showing and PHP file gets opened
Edit 2: I got it to show the modal on screen, but It has no message, not even the title specified in the h4 tags
What I'd like the user to see as message is the echo in the PHP file.
this is what I tried:
form code:
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
<div class="col-sm-12 form-group">
</div>
</form>
Modal:
<!-- Modal -->
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
JS function in the form page:
<script type="text/javascript">
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario="EnviarUsuario"; //name
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize()+"&btnEnviarUsuario="+btnEnvUsuario,
url : 'Logica/Usuario.php',
success : function(data){
$("#MSJ").html(data);
$("#ModalMSJ").modal("show");
}
});
return false;
});
</script>
PHP file:
$IDUsuario=$_POST["txtIDUsuario"];
$NombreRepresentante=$_POST["txtNombreRepresentante"];
$NombreComercial=$_POST["txtNombreComercial"];
$Expediente=$_POST["txtExpediente"];
$Observacion=$_POST["txtObservaciones"];
if(isset($_POST["btnEnviarUsuario"]))
{
$Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($Conexion->connect_error)
{
die("Connection failed: " . $Conexion->connect_error);
}
$sql = "insert into usuario
(NombreRepresentante,NombreComercial,Expediente,Observacion)
values
('$NombreRepresentante','$NombreComercial','$Expediente','$Observacion');";
if($Conexion->query($sql) === TRUE) {
/*Message I'd like to show to user*/
echo "Usuario guardado exitosamente";
}
Just remove the form tag and it won't fully refresh the page.
Then remove your alert from the php file and put it as shown below
<script>
$(document).ready(function(){
$("#EnviarUsuario").click(function(){
$.ajax({
url: "Logica/Usuario.php",
type: 'post',
data: {"btnEnviarUsuario":document.getElementByName("EnviarUsuario").value},
success: function(result){
//You put here your alert
alert("Usuario guardado exitosamente");
}
});
});
});
</script>
seems you having problem for using bootstrap. I wrap it using jsfiddle and fake JSON API. You could try it. I Hope it help. It's just simple problem that you have there. , your code is wrong on the ajax data.
see this.
https://jsfiddle.net/hp9jzfmo/1/
$(function(){
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario=$('#EnviarUsuario').val();
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize(), // This is the right one
url : 'https://jsonplaceholder.typicode.com/posts',
success : function(data){
$("#MSJ").html(JSON.stringify(data));
$("#ModalMSJ").modal('show');
}
});
return false;
});
});
the body should be
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
</div>
</form>
<!-- Modal -->
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The PHP Part I think you could do your self, as far as the data passed to server. I hope it helps :)
This is the final solution:
Form Code:
<form role="form" id="frmUsuario">
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> ID Usuario:</label>
<input type="text" class="form-control" id="IDUsuario" name="txtIDUsuario" readonly>
</div>
<div class="row">
<div class="col-sm-6 form-group">
<label for="name"> Nombre Comercial:</label>
<input type="text" class="form-control" id="NombreComercial" name="txtNombreComercial" required>
</div>
<div class="col-sm-6 form-group">
<label for="email"> Nombre del Representante:</label>
<input type="text" class="form-control" id="NombreRepresentante" name="txtNombreRepresentante" required>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Expediente:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Expediente" name="txtExpediente" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<label for="message"> Observaciones:</label>
<textarea style="resize:none" class="form-control" type="textarea" id="Observaciones" name="txtObservaciones" maxlength="6000" rows="3"></textarea>
</div>
</div>
<div class="row">
<div class="col-sm-12 form-group">
<button type="submit" name="btnEnviarUsuario" id="EnviarUsuario" class="btn btn-lg btn-default pull-right" >Enviar →</button>
</div>
<div class="col-sm-12 form-group">
</div>
</form>
Modal Code
<div class="modal fade" id="ModalMSJ" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" style="font-weight: bold; color:black;" id="exampleModalLabel">Usuario</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" style="color:red;" id="MSJ">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JS Code:
<script type="text/javascript">
$("#frmUsuario").submit(function(e){
e.preventDefault();
var btnEnvUsuario="EnviarUsuario"; //variable to check if user clicked the button
$.ajax({
type : 'POST',
data: $("#frmUsuario").serialize()+"&btnEnviarUsuario="+btnEnvUsuario,
url : 'Logica/Usuario.php',
success : function(data){
$("#MSJ").html(data);
$("#ModalMSJ").modal("show");
}
});
return false;
});
</script>
PHP File Code:
$IDUsuario=$_POST["txtIDUsuario"];
$NombreRepresentante=$_POST["txtNombreRepresentante"];
$NombreComercial=$_POST["txtNombreComercial"];
$Expediente=$_POST["txtExpediente"];
$Observacion=$_POST["txtObservaciones"];
if(isset($_POST["btnEnviarUsuario"]))
{
$Conexion = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if ($Conexion->connect_error)
{
die("Connection failed: " . $Conexion->connect_error);
}
$sql = "insert into usuario
(NombreRepresentante,NombreComercial,Expediente,Observacion)
values
('$NombreRepresentante','$NombreComercial','$Expediente','$Observacion');";
if($Conexion->query($sql) === TRUE) {
/*Message I'd like to show to user*/
echo "Usuario guardado exitosamente";
}

validations not working for checking empty fields

validations not working for checking empty fields
while clicking create button no message is alerting
and console is clear not showing any error
my Jquery code:
var assign_report_form = $('#assign_report_form');
$('#create').on('click', function(){
var source_id = $('#src_id option:selected').text();
var username = $('#username').val();
var email = $('#email').val();
var query_name = $('#query_name').val();
var channel = $('#channel').val();
var condition = $('#condition').val();
if((source_id =="")||(username == "")||(email == "")||(query_name == "")||(channel == "")||(condition == "")){
$('#error_message').show().delay(5000).fadeOut();
}
else{
// var data = {'source_id': source_id,
// 'username':username,
// 'email':email,
// 'query_name':query_name,
// 'channel': 'email',
// 'condition': condition
// }
// console.log('data',data)
$.ajax({
url:'/add_report/',
type:'POST',
data:{'source_id': source_id,
'username':username,
'email':email,
'query_name':query_name,
'channel': 'email',
'condition': condition
},
success: function(res){
if(res =='success')
// $('#Add_modal').modal('toggle');
// $('#success_message').show().delay(5000).fadeOut();
// $("input[type=text],input[type=email],select").val("");
// }
// else{
// $('#error_message').show().delay(5000).fadeOut();
// }
console.log('form saved..')
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown)
}
})
event.preventDefault();
}
});
});
validations not working for checking empty fields
while clicking create button no message is alerting
and console is clear not showing any error
Here is the html code:
<button type="button" data-toggle="modal" data-target="#Add_modal" class="btn btn-secondary" id="add_row" style="margin-right: 10px;">Add</button>
<!-- Add New Report Model -->
<div class="modal fade" id="Add_modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Assign New Report</h3>
</div>
<div class="modal-body">
<!-- content goes here -->
<div class="alert alert-warning" id="#error_message" style='display:none;'>
<strong>Error!</strong>Please fill Empty fields
</div>
<form id="assign_report_form">
{% csrf_token %}
<!-- <input type="hidden" id="src_id" value="{{ source_id }}"/> -->
<div class="form-group">
<label for="username">Source ID</label>
<select id="src_id" class="form-control" name="source_id">
{% for source in sources %}
<option value="{{source_id}}" selected>{{ source.id }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" name="username" id="username" placeholder="Username">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" name="email" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="queryname">Query_Name</label>
<input type="text" class="form-control" name="query_name" id="query_name" placeholder="Query_Name">
</div>
<div class="form-group">
<label for="channel">Channel</label>
<input type="text" class="form-control" name="channel" id="channel" placeholder="Channel">
</div>
<div class="form-group">
<label for="condition">Condition</label>
<input type="text" class="form-control" name="condition" id="condition" placeholder="Condition">
</div>
<input type="button" id="create" class="btn btn-primary" value='Create'/>
</form>
</div>
</div>
</div>
In your html code you need to omit the "#" in id="#error_message" and write id="error_message" instead.
You should always use $('<dropdown selector>').val();, like in your case.
var source_id = $('#src_id option').val();
This will work always for select elements.

modal keep open during validation

I'm doing a record with a modal boostrap laravel performing validation. sending data via jquery ajax realize it. the problem I have is that pressing the submit button closes the modal. how you could do to keep open modal until the end of the validacion ?? Thank you
modal:
<!--- Register Modal -->
<div class="modal fade" id="Register" 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">Registro</h4>
</div>
<div class="modal-body">
<form class="form" role="form" id="new-user" data-token="{{ Session::token() }}" method="post" >
{{ csrf_field() }}
<div id="error">
<!-- error will be showen here ! -->
</div>
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name">Nombre completo: </label>
<input id="name" type="text" class="form-control" name="name" value="{{ old('name') }}">
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label for="email">Correo electronico: </label>
<input id="email" type="email" class="form-control" name="email" value="{{ old('email') }}">
#if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('password') ? ' has-error' : '' }}">
<label for="pwd">Contraseña:</label>
<input id="password" type="password" class="form-control" name="password">
#if ($errors->has('password'))
<span class="help-block">
<strong>{{ $errors->first('password') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('password_confirmation') ? ' has-error' : '' }}">
<label >Confirmar contraseña:</label>
<input id="cpassword" type="password" class="form-control" name="cpassword">
#if ($errors->has('password_confirmation'))
<span class="help-block">
<strong>{{ $errors->first('password_confirmation') }}</strong>
</span>
#endif
</div>
<!-- <input type="hidden" name="_token" value="{{Session::token()}}"> seguridad -->
<button type="submit" class="btn btn-default" id="Submit" >Registro</button>
<div>
<!-- boton login facebook-->
<div>
Facebook</span>
</div>
<!-- boton login google-->
<div>
Google</span>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
js:
function send(event){
event.preventDefault();
$.ajax({
type: 'post',
url: "{{url('/register')}}",
data: {
name: $('#name').val(),
email: $('#email').val(),
password: $('#password').val(),
cpassword: $('#cpassword').val(),
_token: $('#new-user').attr('data-token')
},
success: function (data) {
$("#error").fadeIn(1000, function () {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
});
}
});
}
I don't know how you call the send() js function... so I don't know if you are preventing form submission. Anyway:
Your modal should not been closed on submit the form, except if the form is really being sent and your page reloads.
To prevent your form from being submitted and the current page to reload:
$('#new-user').submit(function(e) { e.preventDefault; });
And to close the modal in your ajax.success function try to use:
$('#Register').modal('hide');
I would Just give you an easy Validation Example. You can use it your own way
and to hide the modal Just add $("#Your Modal ID ").modal("hide"); if your Modal ID is Register then Use $("#Register").modal("hide"); and it will close
function send(event){
event.preventDefault();
if((!$('#name').val())||(!$('#email').val())||(!$('#password').val()))
{
alert("Please Fill All The Details !")
}
else{
$.ajax({
type: 'post',
url: "{{url('/register')}}",
data: {
name: $('#name').val(),
email: $('#email').val(),
password: $('#password').val(),
cpassword: $('#cpassword').val(),
_token: $('#new-user').attr('data-token')
},
success: function (data) {
$("#error").fadeIn(1000, function () {
$("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> ' + data + ' !</div>');
});
$("#Your Modal ID ").modal("hide");
}
});
}
}

Categories