form.submit() to a specific DIV - javascript

I want to submit a form using Javascript and jQuery to specific div but I can't work out how to do it.
This code below works, submitting the form to the header of the current page.
var form,
chart = this,
svg = chart.getSVG(chartOptions);
// merge the options
options = merge(chart.options.exporting, options);
// create the form
form = createElement('form', {
method: 'post',
action: options.url
}, {
display: NONE
}, doc.body);
// add the values
each(['filename', 'type', 'width', 'svg'], function(name) {
createElement('input', {
type: HIDDEN,
name: name,
value: {
filename: options.filename || 'chart',
type: options.type,
width: options.width,
svg: svg
}[name]
}, null, form);
});
// submit
form.submit();
// clean up
discardElement(form);
I have tried various options but nothing has worked. In simple terms I want to do this:
$('#myDiv').form.submit();
Or in other words, send the submit command to the div named myDiv.
Does anyone know how I would do this? Thanks.

You should be able to use the code given here:
Post form in JQuery and populate DIV - broken in IE
$.ajax({
url: options.url,
type: 'POST',
cache: false,
data: {
filename: options.filename || 'chart',
type: options.type,
width: options.width,
svg: svg
},
dataType: 'text',
complete: function(xhr, textStatus) {
alert('completed');
},
success: function(data) {
$("#myDiv").html(data);
},
error: function(xhr, textStatus, errorThrown) {
alert('woops');
}
});

$('#myDiv').click (function () {
$("form").submit();
});

Related

Ext js 7 modern, form.submit vs ajax.request

I have a Ext.form.Panel with multiple textareafield and fileinput like this
// https://requestbin.com/r/en0ej96odon2sm/1n6r1tb49KK6eObGMPHlYa1hh4C
Ext.create({
xtype: 'formpanel',
renderTo: document.body,
buttons: {
submit: 'onSubmit',
},
controller: {
onSubmit: function () {
var form = this.getView();
form.submit({
method: 'POST',
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
},
onSubmitTest: function () {
var form = this.getView();
Ext.Ajax.request({
url: 'https://en0ej96odon2sm.x.pipedream.net/test2',
method: 'POST',
params: {
data: form.getValues(),
},
success: function () {}
});
},
},
items: [{
xtype: 'textareafield',
name: 'testfield',
label: 'testfield',
value: 'test\nasd',
}, {
xtype: 'filefield',
label: 'Upload Test',
name: 'basedata-test',
}, {
xtype: 'button',
text: 'Ajax.request(), linebreaks but no files',
handler: 'onSubmitTest',
}]
});
Post Results:
https://requestbin.com/r/en0ej96odon2sm/1n6mtu8QtyreaisCAmV3csO724Q
Fiddle:
https://fiddle.sencha.com/#view/editor&fiddle/3b9j
So, cause i need fileinput/multipart, I have to use form.submit({}).
But when I do so, I don't get the linebreaks on Server side in my $_POST Var.
When I do a ajax.request({}) everything looks good, but $_FILES are missing, so this is not really an option. (but this is documented).
I also tried adding jsonSubmit to the form (then I get no $_POST at all).
When I add enableSubmissionForm: false I get the newline, but after submit the form disappears (and I don't know why).
Is there a solution for this or am I doing something wrong?
You can use the following override. Hope it will not make the framework unstable ;)
// https://requestbin.com/r/en0ej96odon2sm/1n6r1tb49KK6eObGMPHlYa1hh4C
// Override
Ext.define('overrides.form.Panel', {
override: 'Ext.form.Panel',
privates: {
createSubmissionForm: function (form, values) {
var fields = this.getFields(),
name, input, field, fileTrigger, inputDom;
if (form.nodeType === 1) {
form = form.cloneNode(false);
for (name in values) {
input = document.createElement('textarea');
input.setAttribute('type', 'string');
input.setAttribute('name', name);
input.innerHTML = values[name];
form.appendChild(input);
}
}
for (name in fields) {
if (fields.hasOwnProperty(name)) {
field = fields[name];
if (field.isFile) {
// The <input type="file"> of a FileField is its "file" trigger button.
fileTrigger = field.getTriggers().file;
inputDom = fileTrigger && fileTrigger.getComponent().buttonElement.dom;
if (inputDom) {
if (!form.$fileswap) {
form.$fileswap = [];
}
input = inputDom.cloneNode(true);
inputDom.parentNode.insertBefore(input, inputDom.nextSibling);
form.appendChild(inputDom);
form.$fileswap.push({
original: inputDom,
placeholder: input
});
}
} else if (field.isPassword) {
if (field.getInputType() !== 'password') {
field.setRevealed(false);
}
}
}
}
return form;
}
}
});
Ext.create({
xtype: 'formpanel',
renderTo: document.body,
buttons: {
submit: 'onSubmit',
},
controller: {
onSubmit: function () {
var form = this.getView();
form.submit({
method: 'POST',
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
},
onSubmitTest: function () {
var form = this.getView();
Ext.Ajax.request({
url: 'https://en0ej96odon2sm.x.pipedream.net/test2',
method: 'POST',
params: {
data: form.getValues(),
},
success: function () {}
});
},
},
items: [{
xtype: 'textareafield',
name: 'testfield',
label: 'testfield',
value: 'test\nasd',
}, {
xtype: 'filefield',
label: 'Upload Test',
name: 'basedata-test',
}, {
xtype: 'button',
text: 'Ajax.request(), linebreaks but no files',
handler: 'onSubmitTest',
}]
});
Not ideal, but you also can do this:
form.submit({
method: 'POST',
//just like the ajax
params: {
data: form.getValues(),
},
url: 'https://en0ej96odon2sm.x.pipedream.net/test1',
success: function () {}
});
Here is a simple workaround for using Ajax.request instead of form.submit
I needed that because I have to set an Authorization header, which can't be done with IFRAME used by the framework
So preventing Ext.data.request.Ajax from setting Content-Type header seems to do the job.
multipart/form-data will be automatically set.
Warning : neither options.headers nor defaultHeaders should already have the 'Content-Type' header
Ext.define('Override.data.request.Ajax', {
override: 'Ext.data.request.Ajax',
setupHeaders: function(xhr, options, data, params) {
if (data instanceof FormData) {
if (Ext.apply({}, options.headers || {}, this.defaultHeaders).hasOwnProperty('Content-Type')) {
console.warn('The Content-Type header must not be set before request if you need to use FormData with this override');
}
/* prevent Ext.data.request.Ajax from setting Content-Type header */
return this.callParent([xhr, options, null, null]);
} else {
return this.callParent(arguments);
}
}
});
And call Ajax.request with a FormData as rawData
var formData = new FormData();
var files = myView.down('filefield').getFiles();
if (files.length > 0) {
formData.append('file', files[0], files[0].name);
}
Ext.Ajax.request({
url: 'your_url',
rawData: formData,
success: function(response) {
// handle success
},
failure: function(response) {
// handle failure
}
});

JQuery .show() after replacing html erases styling in MVC 4 application

I have an empty div:
<div id="reportBody"></div>
with simple css:
#reportBody {
height: 100%;
}
The reportBody div is in a hidden modal that is called on button click. Using jquery/ajax to call the controller to build an iframe string to an SSRS report.
$(document).ready(function () {
$('#dashboardReportForm').validate({ // initialize the plugin
rules: {
BrewerySelect: {
required: true
},
LineSelect: {
required: true
},
datepicker: {
required: true,
date: true
}
},
errorElement: "div",
errorPlacement: function (error, element) {
element.after(error);
},
submitHandler: function (form) {
var brewery = document.getElementById('BrewerySelect').value;
var line = document.getElementById('LineSelect').value;
var day = document.getElementById('datepicker').value;
var url = '#Url.Action("GetUrl")';
$.ajax({
url: url,
data: { breweryCode: brewery, packageLine: line, date: day },
dataType: 'json',
cache: false,
type: "POST",
success: function (data) {
var url = '<iframe src="' + data + '" height="100%" width="100%" scrolling="auto"></iframe>';
$('#reportBody').html(url).show();
},
error: function (response) {
alert('document.ready() dashboardReportForm.validate method failed');
}
});
ResetStyle();
$('#reportModal').modal('show');
}
});
});
It is the $('#reportBody').html(url).show(); in that code that replaces the inner html of the div. When I hardcode the iframe and skip this method it displays perfectly. When I use this method it breaks, the height: 100% does not show in chromes tools after inspecting at all.
How do I prevent this from happening or, failing that, reinsert it in the same method.
Thanks.
The answer: Hard code the style into the div.
<div id="reportBody" style="height: 100%;"></div>

How to refresh jTable after adding record w/o page refreshing

Here is my add driver button
$( "#addDriver" ).button().click(function( event ) {
event.preventDefault();
var dn = $("input[name=driver_name]").val();
var ds = $("input[name=driver_status]").val();
var dataString = 'driver_name='+ dn + '&driver_status='+ ds;
//Here is where im trying to load it but it's not working
$('#driversTable').jtable('load');
if(dn == '' || ds == '' )
{
alert("Fill up all Fields with \'*\'");
}
else
{
$.ajax({
type: "POST",
url: "processDriver.php",
data: dataString,
dataType: "json",
success: function(data){
if(!data.error && data.success) {
alert(data.successMsg);
$("input[name=driver_name]").val('');
$("input[name=driver_status]").val('');
} else {
alert(data.errorMsg);
}
}
});
}
});
And here is my jTable init
$("#driversTable").jtable({
title: 'Drivers',
actions: {
listAction: "getAllDrivers.php",
},
fields: {
did: {
key: true,
list: false
},
dID: {
title: 'Driver ID',
width: '7%'
},
dName: {
title: 'Name',
width: '7%'
},
dStatus: {
title: 'Status',
width: '12%'
}
}
});
$('#driversTable').jtable('load');
I want it to be right after adding a new record i want the table to refresh without refreshing the page. I tried the load and reload functions of jtable is not working or am i just putting them on the wrong place of my code?
Insert Data First Then Reload.
$.ajax({
type: "POST",
url: "processDriver.php",
data: dataString,
dataType: "json",
success: function(data){
if(!data.error && data.success) {
alert(data.successMsg);
$('#driversTable').jtable('reload');//<== Reload after Success
$("input[name=driver_name]").val('');
$("input[name=driver_status]").val('');
} else {
alert(data.errorMsg);
}
}
});

Tooltip script. Need to correct code

$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
var ajaxQueue = $({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
$.ajaxQueue = function(ajaxOpts) {
var oldComplete = ajaxOpts.complete;
ajaxQueue.queue(function(next) {
ajaxOpts.complete = function() {
if (oldComplete) oldComplete.apply(this, arguments);
next();
};
$.ajax(ajaxOpts);
});
};
});
});
it's my first experience with js and i need some help. for tooltips i use bootstrap tooltips.
when cursor hover on link, script send post data to controller and receive callback data. in the first hover script receives the data, but tooltip doesn't pop up, only the second hover. how i can fix it?
and one more question. can script will send the request only the first mouse hover, and the following hover will use the information from the cache?
and sorry my english ;D
It is hard to test cross domain
Here is what I THINK you need
$(function() {
$('.challenge').tooltip({html: true, trigger: 'hover'});
$('.challenge').mouseover(function(){
var that = $(this);
$.ajax({
url: "<?=base_url();?>/ajax/challenge_tip",
type: 'POST',
cache: true,
data: {
'idd': $(this).attr("rel"),
},
dataType: 'json',
success: function(challenge_j) {
that.tooltip('hide')
.attr('data-original-title', challenge_j)
.tooltip('fixTitle')
.tooltip('show');
}
});
});
});
Create flag for ajax query.
var isTooltipTextEmpty = true;
$('.challenge').mouseover(function(){
if(isTooltipTextEmpty) {
...add ajax query here)
}
}
And you need to trigger tooltip show event, when ajax query is ready like this
.success(data) {
$('.challenge').show();
isTooltipTextEmpty = false; //prevents multiple ajax queries
}
See more here: Bootstrap Tooltip

How can I assign an HTML5 data value to an element?

I have the following code:
$.modal({
title: title,
closeButton: true,
content: content,
complete: function () {
applyTemplateSetup();
$('#main-form').updateTabs();
$('#main-form').data('action',action);
// updated to line below but still does not work
$('#main-form').data('action','Edit');
},
width: 900,
resizeOnLoad: true,
buttons: {
'Submit': function (win) {
formSubmitHandler($('#main-form'));
},
}
Once my data is loaded I am trying to set the data attribute action. I then have more code that reads it in the submit handler:
var formSubmitHandler = function (form) {
//e.preventDefault();
var $form = form;
var val = $form.valid();
if (!$form.valid || $form.valid()) {
var submitBt = $(this).find('button[type=submit]');
submitBt.disableBt();
var sendTimer = new Date().getTime();
$.ajax({
url: $form.attr('action'),
dataType: 'json',
type: 'POST',
data: $form.serializeArray(),
success: function (json, textStatus, XMLHttpRequest) {
json = json || {};
if (json.success) {
if ($form.data('action') == "Edit") {
$('#modal').removeBlockMessages()
submitBt.enableBt();
} else {
However it seems the value is not being set correctly as when I step through the code this is not getting a true value: $form.data('action') == "Edit". Am I doing something wrong?
This might be the issue.
First you do - $('#main-form').data('action',action);
I'm not entirely sure what the actionvariable holds, but from this line of your code - url: $form.attr('action') I'm going to assume you're giving the form action value. Why you do that is your concern, but I do believe it does not == "Edit".
What value do you get in your $form.data('action') ?

Categories

Resources