jqWidgets: How can I post an HTML form inside a jqxWindow? - javascript

I created the following HTML form inside a jqxWindow widget for a Laravel project:
<div id="provinceWindow">
<div id="provinceWindowHeader"></div>
<div id="provinceWindowContent">
<form id="provinceForm" method="POST" action="{{route('province.store')}}">
{{ csrf_field() }}
<input type="hidden" name="provinceId" id="provinceId" value=""/>
<div class="form-group row">
<div class="col-6"><label>English province name</label></div>
<div class="col-6"><input type="text" name="provinceNameEn" id="provinceNameEn" maxlength="20"/></div>
</div>
<div class="form-group row">
<div class="col-6"><label>Spanish province name</label></div>
<div class="col-6"><input type="text" name="provinceNameSp" id="provinceNameSp" maxlength="20"/></div>
</div>
<br/>
<div class="form-group row justify-content-center">
<input type="button" value="Submit" id="submitBtn" class="btn btn-sm col-3" />
<span class="spacer"></span>
<input type="button" value="Cancel" id="cancelBtn" class="btn btn-sm col-3" />
</div>
</form>
</div>
</div>
This is the javascript file:
$(document).ready(function () {
var datarow = null;
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
//-----------------------------
// Window settings
//-----------------------------
$('#provinceWindow').jqxWindow({
autoOpen: false,
isModal: true,
width: 400,
height: 160,
resizable: false,
title: 'Province name',
cancelButton: $('#cancelBtn'),
initContent: function () {
$('#submitBtn').jqxButton();
$('#submitBtn').on('click', function () {
$('#provinceForm').submit();
});
}
}).css('top', '35%');
The file routes\web.php has only one resourse route defined for this page:
// Routes for province maintenance
Route::resource('province', 'provinceController');
Checking the available routes with php artisan route:list command, I get these:
Method URI Name Action
GET|HEAD / APP\Http\Controllers\homeController#index
GET|HEAD province province.index APP\Http\Controllers\provinceController#index
POST province province.store APP\Http\Controllers\provinceController#store
GET|HEAD province/create province.create APP\Http\Controllers\provinceController#create
GET|HEAD province/{province} province.show APP\Http\Controllers\provinceController#show
PUT|PATCH province/{province} province.update APP\Http\Controllers\provinceController#update
DELETE province/{province} province.destroy APP\Http\Controllers\provinceController#destroy
GET|HEAD province/{province}/edit province.edit APP\Http\Controllers\provinceController#edit
My controller action:
public function store(Request $request)
{
$fields = $request->all();
if ($request->provinceId == '') {
$province = new province($fields);
$validator = Validator::make($fields, $province->rules());
if ($validator->fails()) {
return redirect('')->withErrors($validator)->withInput();
}
else {
$province->save();
}
return view('province/index');
}
}
The form is shown on top of a jqxGrid widget, as a modal window, in order to capture the required information and perform the CRUD operations for the corresponding DB table.
The problem is, when I click the "Submit" button the window is closed and nothing else happens. The form is not posted to the indicated action and the data entered get lost.
It does not matter if I initialize the submitBtn inside the initContent or outside of it. The form is never posted.
I also tried the Close event of the jqxWindow to no avail.
If I take a look to the generated HTML it looks like this:
<form id="provinceForm" method="POST" action="http://mis:8080/province">
<input type="hidden" name="_token" value="Y9dF5PS7nUwFxHug8Ag6PHgcfR4xgxdC43KCGm07">
<input type="hidden" name="provinceId" id="provinceId" value="">
<div class="form-group row">
<div class="col-6">
<label>English province name</label>
</div>
<div class="col-6">
<input type="text" name="provinceNameEn" id="provinceNameEn" maxlength="20">
</div>
</div>
<div class="form-group row">
<div class="col-6">
<label>Spanish province name</label>
</div>
<div class="col-6">
<input type="text" name="provinceNameSp" id="provinceNameSp" maxlength="20">
</div>
</div>
<br>
<div class="form-group row justify-content-center">
<input type="button" value="Submit" id="submitBtn" class="btn btn-sm col-3 jqx-rc-all jqx-button jqx-widget jqx-fill-state-normal" role="button" aria-disabled="false">
<span class="spacer"></span>
<input type="button" value="Cancel" id="cancelBtn" class="btn btn-sm col-3">
</div>
</form>
Pressing the submit button takes me to the home page and nothing gets added to the DB table.
I guess the issue has something to do with Laravel routes because I get no errors.
What is missing or what is wrong with this approach?
Any light is appreciated.

Alright, because I erroneously added in my Model a validation, that was not needed, for a column (there was already a constraint defined at the DB table level), it was not possible to fulfill the validator when saving a new record. I commented that line in my Model and, that was it!
protected $rules = array(
'provinceNameEn' => 'required|alpha|max:20',
'provinceNameSp' => 'required|alpha|max:20'
//'deleted' => 'required|in:M,F' // This is already validated in a DB constraint.
);
I noticed the control was returned to my home page but without any message or error, but if you pay attention to my controller it was precisely the behavior programmed. However, there is no implementation to display the error messages, so I added dd($validator); before that return statement. There I read the message and finally found the solution.

Related

How load forms in modal dynamically?

I'm trying to load forms in modal dynamically using jquery and ajax in python but when i submit the form i get the error werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand. KeyError: 'title'.
Mentioning that I recently started using jquery and ajax with python, could you help me please?
I want to reuse modal section to load multiple forms with jquery.
The code is as below.
HTML: lockbox.html
<input class="btn add" type="button" value="New">
<!--Modal-->
<dialog class="modal">
<div class="modal-header">
<h4 class="modal-title"></h4>
<button class="close-modal">X</button>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button class="close-modal">Cancel</button>
</div>
</dialog>
Javascript
$('.add').on('click', function () {
$.ajax({
type: "get",
url: "/newentry",
success: function (data) {
$('.modal-body').html(data);
$('.modal-header').css('background-color', '#0688fa');
$('.modal-title').text('New register');
$('.modal-footer').css('background-color', '#0688fa');
modalBox.showModal();
}
});
});
Python route
#app.route('/newentry')
def newentry():
return render_template('app/addpass.html')
HTML: addpass.html
<form method="post" class="addPass" action="/addPassReg">
<div class="field-block">
<label for="title">Title: </label>
<input type="text" id="title" value="">
</div>
<div class="field-block">
<label for="user">User: </label>
<input type="text" id="user" value="">
</div>
<div class="field-block">
<label for="passw">Password: </label>
<input type="text" id="passw" value="">
</div>
<div class="field-block">
<input type="submit" value="Save" class="btn save">
</div>
</form>
Python route
#app.route('/addPassReg', methods = ['POST', 'GET'])
def addPassReg():
#cur = mysql.connection.cursor()
if request.method == 'POST':
print('is post')#for debug
print(request.args.listvalues)#trying to know the error
title = request.form['title']
user = request.form['user']
passwd = request.form['passw']
if title and user and passwd:
return json.dumps({'message' : 'OK.'})
else:
print('After')
return redirect(url_for('lockbox'))#json.dumps({'html' : 'Complete please.'})
if request.method == 'GET':
print('is get')#for debug
else:
print('whats up?')#for debug
return redirect(url_for('lockbox'))
When I reuse the modal just to see data it's OK, but for forms I realize that it doesn't work and I don't know if it doesn't recognize the form data or I'm doing something wrong.

keep properties after jquery.load

I'm learning javascript/jquery on the go, I'm trying to reload a form but keeping its js properties (required and masked inputs), code and pictures attached.
First image: Masked inputs works like a charm
Second image: The form its fully filled, still working
Third image: The form it reloaded, but no properties applied
The html form (minmized, just the first field)
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
<div class="form-group row" id="clientRutDiv">
<div class="col-lg-6">
<div class="form-group" id="clientRutInnerDiv">
<label class="col-form-label" for="clientRut">RUT <span class="required">*</span></label>
<input type="text" name="clientRut" id="clientRut" class="form-control" placeholder="Ej. 11.111.111-1" required="" data-plugin-masked-input="" data-input-mask="99.999.999-*" autofocus>
</div>
</div>
</div>
</div>
</form>
<footer class="card-footer">
<div class="switch switch-sm switch-primary">
<input type="checkbox" name="wannaStay" id="wannaStay" data-plugin-ios-switch checked="checked" />
</div> Mantenerme en esta página
<button type="button" style="float: right;" class="btn btn-primary" onclick="realizaProceso();">Enviar</button>
</footer>
The JS for realizaProceso()
function realizaProceso(){
var validator =0;
validator += validateRequiredField('clientRut');
if(validator == 0){
var parametros = {
"clientRut" : document.getElementById('clientRut').value,
"tableName" : 'clients'
};
$.ajax({
data: parametros,
url: 'route/to/addController.php',
type: 'post',
success: function (respText) {
if(respText == 1){
if(document.getElementById('wannaStay').checked){
$("#clientsAddFormContainer").load(location.href + " #clientsAddFormContainer");
}else{
window.location = "linkToOtherLocation";
}
}else{
showNotyErrorMsg();
}
},
error: function () {
showNotyErrorMsg();
}
});
}else{
showNotyValidationErrorMsg();
}
}
So my JS check all fields are validated, then prepare the array, and wait for the php binary response, 1 means the data has been inserted to db, if wannaStay is checked reload the div "clientsAddFormContainer" but as I said, it loose the properties.
Please sorry for my grammar or any other related english trouble, not a native english speaker.
Ps. I've removed some code so it could go different than the images.
Thanks in advance!
EDIT!
The original code is
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
one the js exec I got
<div class="card-body" id="clientsAddFormContainer">
<div class="card-body" id="clientsAddFormContainer">
<form method="post" action="main/clients/addController.php">
</form>
</div>
</div>
2nd EDIT
I found the answer in other stackoverflow question

Ajax form not submitting form rails

I'm using a super basic google form on my website. I'm using this website to extract the HTML to display it on my website - http://stefano.brilli.me/google-forms-html-exporter/
Once I hit submit, nothing happens. The page is just locked. I'm trying to resubmit it to another page. Here is my code
<div class="row">
<form action="https://docs.google.com/forms/d/e/1FAIpQLSfJQ9EkDN8aggSL9AEB2PK4BGiZgBzLDbS1IPppfSkU1zy-oA/formResponse"target="_self" id="bootstrapForm" method="POST">
<div class="col-sm-6 col-md-3">
<input id="679075295" type="text" name="entry.679075295" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="897968244" type="text" name="entry.897968244" class="form-control" >
</div>
<div class="col-sm-6 col-md-3">
<input id="685661947" type="text" name="entry.685661947" class="form-control" >
</div>
<input id="503500083" type="hidden" name="entry.503500083" value="<%= #investment.id %>" >
<div class="col-sm-6 col-md-3">
<button type="submit" value"submit" class="btn btn--primary type--uppercase" >Get Started</button>
</div>
</form>
Here is the ajax script
<script>
$('#bootstrapForm').submit(function (event) {
event.preventDefault()
var extraData = {}
$('#bootstrapForm').ajaxSubmit({
data: extraData,
dataType: 'jsonp', // This won't really work. It's just to use a GET instead of a POST to allow cookies from different domain.
error: function () {
// Submit of form should be successful but JSONP callback will fail because Google Forms
// does not support it, so this is handled as a failure.
alert('Form Submitted. Thanks.')
// You can also redirect the user to a custom thank-you page:
window.location = 'http://reif.com.au/thankyou'
}
})
})
</script>
</div>
Feeling a little silly on this one. Essentially i didn't copy over all of the scripts. I was rushing through.. ALWAYS number 1 error!
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js" integrity="sha256-2Pjr1OlpZMY6qesJM68t2v39t+lMLvxwpa8QlRjJroA=" crossorigin="anonymous"></script>
This is what i needed to add, it now successfully submits and redirects!

Empty values are not submitting in Angular 4 form

I working on Angular 4 project. I am using smart table and form in it.
<div class="row">
<div class="col-lg-12">
<nb-card>
<nb-card-header>Default Inputs</nb-card-header>
<nb-card-body >
<form #f="ngForm" (ngSubmit) = "addNewStudent(f)" >
<div class="row full-name-inputs">
<div class="col-sm-6 input-group">
<input type="text" placeholder="First Name" class="form-control" name="firstName" [(ngModel)]="data.firstName" />
</div>
<div class="col-sm-6 input-group">
<input type="text" placeholder="Last Name" class="form-control" name="lastName" [(ngModel)]="data.lastName" />
</div >
<div class="col-sm-6 input-group">
<input type="text" placeholder="ID" class="form-control" name="id"[(ngModel)]="data.id" [required]=false />
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<button type="cancel" class="btn ">Cancel</button>
</form>
</nb-card-body>
</nb-card>
</div>
</div>
On edit button of table the form is open and shows the whole data of that row in that form, similar form button will be open on add new data in which the data should be added but if I enter only one data and submit it it does not add it it requires all fields.
The add function is as follows:
addNewStudent(f: NgForm)
{
console.log(f.value);
if(this.isAddPage)
{
this.service.addNewEnquiry(f.value);
console.log("addenquiry");
}
else{
this.service.editEnquiry(f.value);
console.log("editenquiry");
}
this.router.navigate(['pages/dashboard1']);
}
The addNewEnquiry function in service is as follows:
addNewEnquiry(data)
{
this.af.list('/enquirydata/').push(data);
}
When I enter all fields it added it to the firebase but when I doesn't fill all fields it shows me error.
ERROR Error: Reference.push failed: first argument contains undefined
in property 'enquirydata.lastName
When you want to push an object into Firebase, you can't have values of the properties equals undefined. Firebase accepts value or null only. Else you always show this error.
In your case :
{ id:undefined, lastName:undefined, firstName:undefined }
To resolve your issue :
public data:any = { id:null, lastName:null, firstName:null };
Before inserting it into your list, you can eliminate undefined ones from object.
addNewEnquiry(data)
{
var newData = data.filter(resp=>{
if(resp.firstName && resp.lastName) {
return resp;
}
})
this.af.list('/enquirydata/').push(newData);
}

Input field with two buttons

I have a form with one input field, but two buttons. The idea is to check in or out with a code. The process comes to the php file, where it ends with just a blank page. What´s wrong?
EDIT
I changed "btn_in" to "inputAnst_nr" And now it works to reg in. BUT, how to i fetch wich button is pressed?
HTML
<form class="form-inline well" id="usr_stamp" name="usr_stamp" method="post" action="php/usr_time_reg.php">
<div class="control-group">
<input id="inputAnst_nr" name="inputAnst_nr" class="form-control input-lg" placeholder="Ange Anst. nr" type="tel">
<button id="btn_in" name="btn_in" class="btn btn-lg btn-info primary col-sm-offset-1" type="submit">In</button>
<button id="btn_out" name="btn_out" class="btn btn-lg btn-danger primary col-sm-offset-1" type="submit">Ut</button>
</div>
</form>
JS
$(document).ready( function () {
$("#btn_in").on('click', function() {
$("#usr_stamp").attr("action", "php/usr_time_reg.php");
});
$("#btn_out").on('click', function() {
$("#usr_stamp").attr("action", "php/usr_time_reg.php");
});
});
PHP
//Check if POST is empty
if(!empty($_POST)){
//Check if POST is "inputAnst_nr"
if(!empty($_POST['inputAnst_nr'])){
//Put POST_btn_in in variable
$posted_anst_nr = $_POST['inputAnst_nr'];
You could just use the same name attribute value for both buttons, just make sure you designate the appropriate value. Example:
<?php
if(isset($_POST['btn_in_out'])) {
$status = $_POST['btn_in_out']; // In or Out depending on which one you clicked
echo $status;
}
?>
<form class="form-inline well" id="usr_stamp" name="usr_stamp" method="post">
<div class="control-group">
<input id="inputAnst_nr" name="inputAnst_nr" class="form-control input-lg" placeholder="Ange Anst. nr" type="tel">
<button id="btn_in" name="btn_in_out" type="submit" value="In">In</button>
<button id="btn_out" name="btn_in_out" type="submit" value="Out">Ut</button>
</div>
</form>
Sample Output

Categories

Resources