Make Submit button not kill my dialog box - ajax

I have a form and I'm trying to perform Ajax posts.
With the default submit button the dialog window closes, with the jQuery button, nothing happens.
I want the dialog window to stay open so I can keep doing Ajax requests uninterrupted and only close when I press Esc or click the big "X".
Thanks
<div id="formBox" style="display: hidden;">
<form>
<fieldset>
<legend>File System Space Calculator</legend>
<p>
<label for="curr_alloc">Current Space Allocation:</label>
<br />
<input type="text" size="5" name="curr_alloc" id="curr_alloc" />
KB <input type="radio" name="curr_unit" value="KB" />
MB <input type="radio" name="curr_unit" value="MB" />
GB <input type="radio" name="curr_unit" value="GB" checked/>
TB <input type="radio" name="curr_unit" value="TB" />
</p>
<p>
<label for="curr_percent">Current Usage Percentage:</label>
<br />
<input type="text" size="5" name="curr_percent" id="curr_percent" />
</p>
<p>
<label for="desired_percent">Desired Usage Percentage:</label>
<br />
<input type="text" size="5" name="desired_percent" id="desired_percent" />
</p>
<br />
<p>
<input type="submit" value="calculate"/></p>
</fieldset>
</form>
</div>
<div id="calcBox" style="display: none;"> </div>
<script>
$(document).ready(function() {
$("#formBox").dialog({
bgiframe: true,
autoOpen: false,
height: 500,
width: 500,
modal: false,
closeOnEscape: true,
title: "Calculator",
closeText: 'Close',
buttons:
{
"Calculate": function()
/* form post */
$("#calcQuery").submit(function(){
$.post("calc.php", $("#calcQuery").serialize(),
function(data){
if (data.length > 0)
{
$("#calcBox").html(data);
$("#calcBox").show();
}
else
{
$("#calcBox").html("<h1>nuttin' here yet</h1>");
}
}, "html");
return false;
});
/* form post */
}
}
});
$('#calcButton').click(function(){
$('#formBox').dialog('open');
return false;
});
});
</script>

In your button method, just make the post. You shouldn't have to do anything else.
buttons:{
"Calculate":function(){
$.post("calc.php", $("#calcQuery").serialize(), function(data){ if (data.length > 0) {
$("#calcBox").html(data);
$("#calcBox").show();
}
else
{
$("#calcBox").html("<h1>nuttin' here yet</h1>");
}
}, "html");
});
}
I apologize for the formatting. I worked with what you gave me without opening an editor. You shouldn't need to return false in a jQuery-UI button.

This works (except for form reset which is addressed in another post)
// form popup
$(document).ready(function()
{
$("#formBox").dialog({
bgiframe: true,
autoOpen: false,
height: 600,
width: 400,
modal: false,
closeOnEscape: true,
title: "Calculator",
buttons: {
"Calculate": function() {
// form post
$.ajax({
type: "POST",
url: "calc.php",
data: $("#calcQuery").serialize(),
dataType: "html",
success: function(response)
{
$("#calcBox").html(response);
$("#calcBox").show();
},
error: function
(xhr, ajaxOptions, thrownError)
{
alert(xhr.status);
alert(thrownError);
}
}).responseText;
// form post
}
}
});
$('#calcButton').click(function(){
$('#formBox').dialog('open');
});
});

Related

How to send other variable datas along with new FormData() inside AJAX?

Here I am sending the upload files into FormData() to be accessed in expressjs. And it is working perfectly.
$(".commonForm").submit(function (e) { //For Submitting the Uploaded Files
e.preventDefault();
if(validateForm($(this).attr('name'), text))
{
$.LoadingOverlay("show");
var formData = new FormData(this);
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response){
if (response.status == '200') {
$.LoadingOverlay("hide");
swal({
title: "Excellent!",
text: "Files submitted successfully!",
icon: "success",
button: "Ok",
showCancelButton: true
}).then((result) => {
if (result) {
window.location.reload();
}
});
}
},
error: function (e) {
console.log("some error", e);
}
});
}
});
But along with that I want to send one another field data along with formData.
var text = 'Done';
How to send this along with formData in data ?
I am trying this:
data : {
formData:formData,
text:text
}
But then I don't think that I will be able to retrieve the uploaded files data directly with req.files
UPDATE:
route code/expressjs
router.post('/api/upload/:cid',function(req,res,next){
console.log("req.body.text = " + req.body.text + req.query.text);
upload2(req,res,function(err) {
if(err) {
console.log("Error is important = "+ err);
}
else
{
console.log("Uploaded successfully.");
}
})
})
MULTER CODE:
var upload2 = multer({storage: storage2, limits: { fileSize: 1024 * 1024 * 1 }}).array('FileUploadForClient',4);
HTML HANDLEBAR FORM CODE:
<form name="{{this.status}}" class="commonForm" enctype="application/x-www-form-urlencoded" action="/api/upload/{{this.commonID}}" method="post">
<td class="col-sm-2">
<div class="center">
<select name="sourcesSelect" id="{{this.commonID}}" data-notUse="{{this._id}}" data-Id4AddtasksBigpaths="{{this.Id4AddtasksBigpaths}}" class="custom-select sources" placeholder="{{this.status}}" style="font-size:20px; background: {{this.background}}; color: white;" {{this.statusDisabled}}>
<option value="0" >In Progress</option>
<option value="1" >Done</option>
<option value="2" >Rejected</option>
</select>
</div>
</td>
<!-- <td class="col-sm-2"><span id="deadline" style="font-size:14px"><input type="text" class="form-control" value="{{this.deadline}}" readonly/></span></td> -->
<td class="col-sm-1">
<!-- <input type="file" class="btn btn-light" name="FileUploadForClient" multiple required/> -->
<input type="file" id="{{this._id}}" class="form-control" name="FileUploadForClient" multiple required {{this.statusDisabled}} />
</td>
<td>
<button type="submit" class="btn btn-primary btn-block col-sm-2" style="font-size:16px" {{this.statusDisabled}}>Submit</button>
</td>
</form>
Use the method append to add another parameter to the request
var formData = new FormData(this);
formData.append('text', 'text to send in the request ');

Inserting a general validation alert using KnockoutJS validation

I'd looking for the most effective way of inserting a general validation alert "Please check your submission" to be positioned above the fieldset, instead of in an alert pop-up as coded below.
http://jsfiddle.net/Nz38D/3/
HTML:
<script id="customMessageTemplate" type="text/html">
<em class="customMessage" data-bind='validationMessage: field'></em>
</script>
<fieldset>
<legend>Details</legend>
<label>First name:
<input data-bind='value: firstName' />
</label>
<label>Last name:
<input data-bind='value: lastName' />
</label>
<div data-bind='validationOptions: { messageTemplate: "customMessageTemplate" }'>
<label>Email:
<input data-bind='value: emailAddress' required pattern="#" />
</label>
</fieldset>
<br>
<button type="button" data-bind='click: submit'>Submit</button>
<br>
<br> <span data-bind='text: errors().length'></span> errors
JS:
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
decorateElement: true,
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
var viewModel = function() {
this.firstName = ko.observable().extend({
minLength: 2,
maxLength: 10
});
this.lastName = ko.observable().extend({
required: true
});
this.emailAddress = ko.observable().extend({ // custom message
required: {
message: 'Enter your email address.'
}
});
this.submit = function () {
if (this.errors().length == 0) {
alert('Thank you.');
} else {
alert('Please check your submission.');
this.errors.showAllMessages();
}
};
this.errors = ko.validation.group(this);
};
ko.applyBindings(new viewModel());
I inserted a virtual element to hold the validation summary message and bound its display to an observable in the click function: http://jsfiddle.net/sx42q/2/
HTML:
<!-- ko if: displayAlert -->
<p class="customMessage" data-bind="text: validationSummary"></p> <br />
<!-- /ko -->
JS:
this.validationSummary = ko.observable("Complete missing fields below:");
this.displayAlert = ko.observable(false);
this.submit = function () {
if (this.errors().length == 0) {
alert('Thank you.');
} else {
this.displayAlert(true);
this.errors.showAllMessages();
}

Fancybox form submit with ajax

I have fancybox, where I want to submit a form. Also I want to handle that form by PHP code which is inside the same page. Below is my code.
function lunchModal(itemID){
jQuery('.share').on('click', function(){
$data = '<div class="shareModal" ><div class="modal-header"><h3>Share Form Submission</h3></div> \
<form action="" class="shareForm" method="post">\
<div class="modal-body">\
<div class="control-group">\
<label for="inputEmail" class="control-label">Enter Share Email</label>\
<div class="controls">\
<input type="email" id="inputEmail" placeholder="Share Email" name="email">\
<input type="hidden" value="'+itemID+'" id ="documentID">\
</div>\
</div>\
</div>\
<div class="modal-footer">\
<div class="controls">\
<button type="submit" class="btn btn-primary" id="submit">\
<i class="icon icon-envelope"></i>Share</button>\
</div>\
</div>\
</form>\
</div>';
jQuery.fancybox({
height : '55%',
autoDimensions: false,
width: '70%',
scrolling: 'auto',
padding: '20px',
title: false,
content: $data,
transitionIn: 'elastic',
transitionOut: 'elastic',
easingIn : 'easeOutBack',
easingOut : 'easeInBack',
centerOnScroll: 'true',
onComplete: submitForm()
});
item_id = false;
});
};
function submitForm() {
jQuery('#submit').on('submit', function(e) {
e.preventDefault();
//var dataString = {
// 'action' : 'shareDocument'
//};
var email = jQuery('#inputEmail').val();
var id = jQuery('#documentID').val()
var dataString = 'email='+email+'&documentID='+id;
//jQuery.extend(true, dataString, form_data);
console.log(dataString);
jQuery.fancybox.showActivity();
jQuery.ajax({
url: window.location.pathname,
type: 'POST',
data: dataString,
beforeSend: function() {
console.log(dataString);
},
success: function(data) {
alert('Document shared successfully');
}
});
return true;
});
}
Now my problem is When I submitting the form, the page is reloading, although I have used ajax form submit. Can anyone help me in this regard?
button type="submit"
this will reload ur page bcz ur submitting value to the declared page.
so you have to change ur code like below
input type="button" onclick="submitForm()"
this wont reload ur page.

Kendo UI: Update transport doesn't trigger after calling datasource sync

Im struggling on this in hours now, I cant find a good documentation on how to implement simple ajax UPDATE on server using forms and Kendo MVVVM and datasource.
KENDO MVVM
$(function() {
var apiUrl = "http://a31262cd2f034ab8bcda22968021f3b8.cloudapp.net/api",
meetingDatasource = new kendo.data.DataSource({
transport: {
read: {
url: apiUrl + "/meetings/4",
dataType: "jsonp"
},
update: {
type: "PUT",
url: apiUrl + "/meetings",
contentType: "application/json; charset=utf-8",
dataType: 'json',
},
parameterMap: function(options, operation) {
return kendo.stringify(options);
}
},
batch: true,
change: function() {
},
schema: {
model: {
id: "Id",
fields: {
Title: { editable: true },
StartTime: { type: "date" },
EndTime: { type: "date" }
}
}
}
});
meetingDatasource.fetch(function () {
var viewModel = kendo.observable({
description: result.Description,
title: result.Title,
venue: result.Location,
startDate: result.StartTime,
endDate: result.EndTime,
saveChanges: function (e) {
//im not sure with this line
this.set("Title", this.Title);
meetingDatasource.sync();
e.preventDefault();
}
});
kendo.bind($("#view"), viewModel);
});
});
THE UI
<ul class="forms" id="ul-meeting">
<li>
<label for="title" >Title:</label>
<input data-bind="value: title" class="k-textbox" style="width:350px;"/>
</li>
<li>
<label for="description" >Description:</label>
<textarea data-bind="value: description" id="description" rows="6" cols="80" class="k-textbox" style="width:350px;"></textarea>
</li>
<li>
<label for="location">Venue:</label>
<textarea data-bind="value: venue" id="location" rows="4" cols="80" class="k-textbox" style="width:350px;"></textarea>
</li>
<li>
<p>
<label for="start-datetime">Start:</label>
<input data-bind="value: startDate" id="start-datetime" style="width:200px;" />
</p>
<p>
<label for="end-datetime">Finish:</label>
<input data-bind="value: endDate" id="end-datetime" style="width:200px;" />
</p>
</li>
</ul>
The problem is, the TRANSPORT READ triggers but the TRANSPORT UPDATE never triggers even if I explicity call the Datasource.sync(). Is is something I am missing here?
Your code is not complete (you are not showing what is result or how you trigger saveChanges but from what I see the problem is that you are not updating the content of the DataSource (meetingDataSource).
In your code that you copy the fields from result into and ObservableObject but you never update the content of the DataSource. When you do this.set, in that context this is not the DataSource so when you call sync you are doing nothing.
Try doing:
meetingDatasource.data()[0].set(`Title`, this.Title);
meetingDatasource.sync();
This should do the trick!

KendoUI: MVVM Autocomplete Events

I was searching all over but couldn't find an answer to my question. I'm initializing an autocomplete widget as the following:
This code is loaded into my DOM as a result of an Ajax request:
<div id="view_ticketCreate">
<form id="jar_ticketing_create"action="" class="k-block jar-container">
<fieldset class="login">
<legend>Kontaktinformationen</legend>
<p class="notice">Definieren Sie hier die Kontaktinformationen zu diesem Ticket.</p>
<p>
<label>Kunde</label>
<input data-role="autocomplete" data-bind="source: customers, events{click: inject}" data-text-field="CName" placeholder="Suchen Sie nach dem Kunde" type="text" id="jtc_cID" class="k-textbox sourced">
</p>
<p>
<label>Kontakt</label>
<input type="text" name="jtc_cName" class="k-textbox">
</p>
<p>
<label>E-Mail</label>
<input data-bind="value: cMail" type="text" name="jtc_cMail" class="k-textbox">
</p>
<p>
<label>Telefon</label>
<input data-bind="value: cPhone" type="text" name="jtc_cPhone" class="k-textbox">
</p>
<p>
<label>Gerät</label>
<select name="dID" class="k-textbox sourced">
<option value="000">Nicht geräte spezifisch</option>
<option value="001">CFBS01</option>
<option value="002">CFBS02</option>
<option value="003">CFBS03</option>
<option value="004">CFBS04</option>
</select>
</p>
<p>
<label>Login</label>
<input type="text" name="cLogin" class="k-textbox">
</p>
</fieldset>
</form>
</div>
<script>
kendo.bind($("#view_ticketCreate"), view_ticketCreate);
</script>
in my main (an always loaded) JS file i got:
var view_ticketCreate = kendo.observable({
customers: new kendo.data.DataSource({
transport: {
read: {
url: "http://server/API/customers/search/",
dataType: "jsonp",
contentType: "application/json; charset=utf-8"
},
parameterMap: function(options, operation) {
return {
SearchTag: options.filter.filters[0].value
}
}
},
schema: {
data: "data"
},
serverFiltering: true,
dataTextField: "CName",
select: function(e){
if (e.item == null) return;
var DataItem = this.dataItem(e.item.index())
cPhone: DataItem.Telefon
}
}),
inject: function(e){
alert('ok')
},
cPhone: "0123456789",
cMail: "asd#asd.de"
});
However, the autocomplete search works perfect. But now I want to populate the fields jtc_cMail and jtc_cPhone with values from my autocomplete request. But either the select: Function is working (not allowed here (guess because MVVM?), also the custom event inject is fireing.
I couldn't find anything how I need to go on. Please help me out.
Greetings
Just have to use e.sender.dataItem function and pass in the index of the item selected.
selectPerson: function(e) {
var item = e.sender.dataItem(e.item.index());
viewModel.set("selectedPerson", item);
}
See jsbin http://jsbin.com/iLaK/3/edit

Resources