jquery form submission in new window - javascript

i want to set some header information and cookies with form submission using $('#formid').submit(); javascript code. Most of the site says that setRequestHeader is only working on ajax form submission. but i can not use the ajax method to submit the form.
my javascript code is
$(document).ready(function(){
$("#leftNav a").click(function(event){
event.preventDefault();
href = $(this).attr('href');
$("#dynamicform :input").remove();
var querystringArray = href.split('?')[1].split('&');
$("#dynamicform").attr("action", href.split('?')[0]);
$.each(querystringArray, function(index, value) {
var elementArray = value.split('=');
if(elementArray[0]=='methodtype') { $("#dynamicform").attr("method", elementArray[1]);}
$('<input>').attr({
type: 'hidden',
value: elementArray[1],
name: elementArray[0]
}).appendTo('#dynamicform');
});
usagelogsajax(href.split('?')[0],'ncrtester');
xhr.setRequestHeader('X-Test', 'three');xhr.setRequestHeader('X-shashi', 'three');
$('#dynamicform').submit();
});
});
function usagelogsajax(url, user) {
$.get("usagelogs.php?url="+url+"&username="+user,function(responseTxt,statusTxt,xhr){
if(statusTxt=="success");
//alert("Usagelogs created successfully!");
if(statusTxt=="error");
//alert("Error: "+xhr.status+": "+xhr.statusText);
});
}
And my page have link like
http://sitename.com/autologinSL3?readform=&userid=userid&methodtype=get&pwd=passowrd
How can i achieve my requirements.
Thanks

I think what you are looking for is the target-attribute of the form (see mdn).
If you set target="_blank" the form will be submitted and the result will be shown in a new window.

Related

AJAX call failing to process form

I have an email sign-up form on a website.
The form appears in two areas of each web page: the header and the footer
It's the same exact form, just available on the top and bottom of the page for better UX and accessibility.
The form uses a jQuery/AJAX script to provide success and error responses to the user. (i.e., "Success! Your subscription is complete." and "Error. Please review and re-submit")
The problem I'm having is that the header form processes but the footer form does not.
Any ideas what's wrong with this code? Thanks.
P.S. The form was working perfectly when the header and footer forms each had their own script. The problem started when the scripts were consolidated into one file. I've posted the original scripts at the bottom. Also, nothing has been changed in the PHP, so I don't think the problem is there.
$(function() {
// get the forms
var form = $('#header-form, #footer-form');
// set up event listener
$(form).submit(function(e) {
// disable html submit button
e.preventDefault();
// get the submit button
var submitButton = $('[type=submit]', this);
// get the messages element
var formResponses = $('#header-form-responses, #footer-form-responses', this);
formResponses.text(" ");
// serialize form data
var formData = $(form).serialize();
// disable submit button to prevent unnecessary submission
submitButton.attr('disabled', 'disabled');
// tell users that form is sending
submitButton.text('Processing...');
// submit form via AJAX
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// make sure formResponses element has 'success' class
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
// set message text
$(formResponses).text('Your subscription is complete. Thank you!');
// clear form
$('input').val('');
})
.fail(function(data) {
// make sure formResponses element has 'error' class
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
// set the message text
$(formResponses).text('Input error. Please review and re-submit.');
})
.always(function(data) { // this will always fire even if the request fails
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- simplified HTML -->
<form action="form_processing.php" method="post" id="header-form">
<input type="email" name="email_subscription">
<button type="submit" id="header-form-submit">Submit</button>
<div id="header-form-responses"></div>
</form>
<form action="form_processing.php" method="post" id="footer-form">
<input type="email" name="email_subscription">
<button type="submit" id="footer-form-submit">Submit</button>
<div id="footer-form-responses"></div>
</form>
Here's the original header code (works perfectly):
$(function() {
var form = $('#header-form');
var formResponses = $('#header-form-responses');
var submitButton = $("#header-form-submit");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
submitButton.attr('disabled', 'disabled');
submitButton.text('Processing...');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
$(formResponses).text('Your subscription is complete. Thank you!');
$('input').val('');
})
.fail(function(data) {
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
$(formResponses).text('Input error. Please review and re-submit.');
}).always(function(data) {
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
Here's the original footer code (works perfectly):
$(function() {
var form = $('#footer-form');
var formResponses = $('#footer-form-responses');
var submitButton = $("#footer-form-submit");
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
submitButton.attr('disabled', 'disabled');
submitButton.text('Processing...');
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
$(formResponses).removeClass('error');
$(formResponses).addClass('success');
$(formResponses).text('Subscription complete.');
$('input').val('');
})
.fail(function(data) {
$(formResponses).removeClass('success');
$(formResponses).addClass('error');
$(formResponses).text('Input error. Please review and re-submit.');
}).always(function(data) {
submitButton.removeAttr('disabled');
submitButton.text('Send');
});
});
});
Within the $(form).submit( you're still using $(form), eg
var formData = $(form).serialize();
as form = $('#header-form, #footer-form') any call to $(form) (or just form) will affect/apply to/read from both forms. This depends on what the call is, eg form.attr("action") will always get the action from the first form.
Within the handler, change all $(form) (or just form) to $(this):
var formData = $(this).serialize();
...
url: $(this).attr('action'),
be careful using this inside a callback, so if you do need the relevant form then instead, change to
$('#header-form, #footer-form').submit(function(e) {
var form = $(this);
and continue to use form.
Note that in your code form is already a jquery object, but jquery allows you to "double wrap" - ie $(form) is the same as $($(form))
I recommend you remove the outer form variable completely, ie change to
// set up event listener
$('#header-form, #footer-form').submit(function(e) {
which will help to remove the issue of using form not meaning this form.

how to create dynamic ajax submission form

I have 10 form in a page & there data is submitted through ajax, Now i don't want to create ajax script for each form. So here is what i tried
var form_id = $(this).closest("form").attr('id');
$(document).on("submit", "#"+form_id, function(e){
e.preventDefault();
var postData = $("#"form_id).serialize()
var send = true;
var ptel = 1;
$("#"+form_id).find("input").each(function () {
if ($(this).val() === '') { send = false; ptel = 0; }
});
if(ptel == 0) { bootbox.alert('Please Fill All fields'); }
if(send){
$('form_id').trigger("reset");
$.ajax({
type: "POST",
url: "/ajax/X-Profile",
data: postData,
cache: false,
success: function(msg)
{
bootbox.alert('Your Profile has been updated.');
}
});
}
return false;
});
var form_id results in undefined because when page loads no attribute was defined to it
Above codes are just to make you understand,
So my question is how can i make 10 forms submit through single ajax function
You can create a function such as SendForm() and attach it to the forms onsubmit attribute
<form id="yourid" onsubmit="SendForm(this);return false;">
inside the SendForm() function place your script
for instance:
function SendForm(form) {
var postData = form.serialize();
// .......etc
}
To know which form was submitted in PHP, you can place a hidden input inside the form or have a second parameter on SendForm which gets sent through, such as SendForm(node,formtype)
if the form isn't submitting or page reloads, remove the onsubmit attribute and add this to your JS instead
$(document).on("submit","form", function(e){
e.preventDefault();
SendForm($(this));
return false;
});
Have javascript function like below
<script type="text/javascript">
function submitForm(formID) {
data = $('#'+formID).serialize();
//your ajax code
}
</script>
Now use input button with onclick like below, and pass form Id as a parameter
<input type="button" value="Submit" onclick="submitForm({formID})">
This will work without refreshing the page. And on success you can trigger reset() function to form that particular form values.

Troubles Submitting Form programmatically

I have a simple page that takes a form and makes a jsonp ajax request and formats the response and displays it on the page, this is all fine, but I wanted to add it so that if the form was populated (via php $_GET variables) then the form would auto-submit on page load but what happens instead is that the page constantly refreshes despite the submit function returning false.
Submit Button (just to show it doesn't have an id like submit or anything)
<button type="submit" id="check" class="btn btn-success">Check</button>
jQuery
$(document).ready(function() {
$('#my_form').on('submit', function() {
var valid = 1;
$('#my_form .required').each(function() {
if ($(this).val() == '') {
$(this).parents('.form-group').addClass('has-error');
valid = 0;
} else {
$(this).parents('.form-group').removeClass('has-error');
}
});
if (valid === 1) {
$.ajax({
url: '/some_url',
data: $('#my_form').serialize(),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function(data) {
var html = 'do something with data';
$('#results').html(html);
},
error: function() {
$('#results').html('An error occurred, please try again');
}
});
} else {
$('#results').html('Please fill in all required fields');
}
return false;
});
});
The part I added just after the $(document).ready(function(){ and before the submit was:
if ($('#input_1').val() != '' || $('#input_2').val() != '') {
// $('#check').trigger('click');
$('#my_form').submit();
}
Both those lines have the same effect but I am doing the same in another project and it works fine, as far as I can see, the only difference is the jQuery version, I'm using 1.11 for this page.
Update
Apologies, I seem to have answered my own question, I thought that since the programmatic submit was the first thing in $(document).ready(function(){ then maybe it was the case that the actual submit function wasn't being reached before the event was triggered so I simply moved that block after the submitfunction and it now works fine.
url: ''
it seems like you are sending your ajax request to nothing.
just an additional: if you want to submit your form through jquery without using AJAX, try
$("#myForm").submit();
it will send your form to the action attribute of the form, then redirect the page there.

Save Two forms at the same time using jquery or ajax?

I'm planning on saving 2 forms but the 1st form is where I get the Foreign key for the Second form.
This is my Attempt to save this Using Javascript:
$("#btnSave").click(function (e) {
e.preventDefault();
$('#workForm').submit();
$('#contForm').submit();
});
But it errors on Contact Form Submit in the control because the ID of Worker Form is still null while saving the contact form that is its Foreign Key
How can I Handle This using Jquery and Javascript and Ajax?
I also Tried this method:
$("#btnSave").click(function (e) {
e.preventDefault();
if (Id != 0) {
$('#workForm').submit();
$('#contForm').submit();
} else {
$('#workForm').submit(); }
});
But it only goes at Else because the ID is null
I hope someone can help me here
Worker Address is the WorkForm Worker Contact is the ContForm
I want to save them both when they populate all the textbox
You will have to use ajax because
$('#contForm').submit();
will never be run as the page will be unloaded by the first call:
$('#workForm').submit();
You can submit the first form using ajaxSubmit() and on its success, submit the second form.
$("#btnSave").click(function() {
$('#workForm').ajaxSubmit({
forceSync: true,
error: function(errorDetails) {
//Error Handling
},
success: function(successData) {
$('#contForm').submit();
}
});
});
You need to post both forms using .ajax. Serialize the data from both forms and then post to your server script.
$("#btnSave").click(function (e) {
e.preventDefault();
//Serialize the form data
var formOne$ = $('#workForm').serialize();
var formTwo$ = $('#contForm').serialize();
$.ajax( { url : "YOURURL", type: 'post', data : { formOne : formOne$ , formTwo : formTwo$ },
success : function( responseText ){
//Forms were submitted
},
error : function( e ){
alert( ' Error : ' + e.statusText );
}
});
});

Javascript issue re form reset

I've got an issue with a small javascript form that submits perfectly, brings up the success message but fails to reset the form. The data remains visible, until you manually refresh the page.
The code is:
jQuery(document).ready(function(){
$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
.after('<img src="images/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
phone: $('#phone').val(),
subject: $('#subject').val(),
comments: $('#comments').val(),
verify: $('#verify').val()
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null);
}
);
});
return false;
});
});
I wondered if I can add in a reset command but as my java is limited I'm not sure where? Would appreciate any pointers or advice. Thanks in advance.
You could add this inside the if (data.match...), as follows:
if (data.match("success") != null){
$('#contactform')[0].reset();
}
You need to manually clear/reset the form.
As you using JQuery to send the request, it is not like form action that changes your browser location.
Just call RESET once the data has been successfully sent.
For more on that see: http://www.w3schools.com/jsref/met_form_reset.asp
If on the other hand you want to reset your form values to defaults you specify you can create a function such as:
function resetFormValues()
{
$('#name').val('name');
$('#email').val('email');
etc..
}
and call resetFormValues(); from within your code such as:
if (data.match("success") != null){
resetFormValues();
}

Categories