jQuery to handle two submits one with validation and another without validation - javascript

I have a form as:
<form method='post' action="submit.cfm" id='formid' class="formclass" name="formname">
<input type='submit' name='submit' value="save">
<input type='submit' name='submitDraft' value="save draft">
</form>
Now without jQuery, I can submit the form and it will validate with html required fields for whichever fields it needs to be, and I will fill it and save it, now for the save draft, I want to save it without validation and trying to use jQuery to accomplish this but it's not working as expected.
I tried like this:
$("#formid").submit(function(event) {
event.preventDefault(); // prevent default action
var post_url = $(this).attr("action"); // get form action url
var form_data = $(this).serialize(); // Encode form elements for submission
$.post( post_url, form_data, function( response ) {
$("#server-results").html( response );
});
});
Now can I kill 2 birds with one stone, any feasible solution? There is no upload field, so I am safe from that perspective.
More tried came up with
<script type="text/javascript">
$(document).on('submit','#formid',function(event) {
event.preventDefault(); //prevent default action
var _id = $(this).find("#saved").attr('id');
if(_id == 'saved') {
alert('hi');
var isDrafted = 0;
$.validate({
modules : 'date, file'
});
} else {
alert('hello');
var isDrafted = 1;
var post_url = $(this).attr("action"); //get form action url
var form_data = $(this).serialize() & '&isDrafted=' + isDrafted; //Encode form elements for submission
$.post( post_url, form_data, function( response ) {
$("#server-results").html(response);
});
}
});
</script>
Now I am using a formvalidation.net validator, its old but its working, and honestly it is going to be mess to replace it, so how can I make this work?
Something else noticed, I had to click the button twice before it shows validation messages when clicked on save.
And the whose context is save means submit to the action page to save in database

You would need to name the buttons the same with different values, like mentioned here:
<input type='submit' name='submit' value="save">
<input type='submit' name='submit' value="save draft">
Or, since you are open to jQuery, setting a hidden field to which submit button was pressed:
<input type='hidden' name='whichSubmit' id='whichSubmit'>
<input type='submit' name='submit' value="save">
<input type='submit' name='submitDraft' value="save draft">
$("#formid").submit(function(event){
$('#whichSubmit').val(event.target.name);
});
(both of those are untested pseudo code)

Related

onClick and action html

I am using purecss as a base for a simple project. What I am currently having trouble with is I have a submit button where I will pull some info from the fields, and when clicked I want to run some javascript, as well as take the user to another page. This is what I am trying with no luck:
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" onClick="saveInfo(this.form)" action="confirm.html">Submit</button>
<button type="submit" class="pure-button pure-button-primary">Search</button>
</div>
Give your buttons IDs for simplicity, and take out that nasty inline JS.
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
And then with your script:
var el = document.getElementById("button1"); //cache the save button
el.addEventListener("click", function() {
document.forms[0].submit(); //submit the form or save it etc
window.location.href = "confirm.html";
}, false); //event handler
Send your form data into the function, and then use a simple redirect since only form elements have action properties. Then just add the click event, save your form however you want (submission, ajax call, doesn't matter), then either in a callback or how it is, redirect the client with window.location.href
You could have a Javascript event handler for a button press which might look something like:
document.getElementById('buttonID').onclick=function(){
//Do whatever processing you need
document.getElementById('formID').submit();
};
Alternatively, you could have an event handler in jQuery which would look something like:
$('#buttonID').on('click',function(){
// Do whatever processing you need
$('#formID').submit();
});
You can make the code inside saveInfo() redirect the user to confirm.html after you're done saving the info.
window.location = "confirm.html"
<div class="pure-controls">
<button type="submit" class="pure-button pure-button-primary" id="button1">Submit</button>
<button type="submit" class="pure-button pure-button-primary" id="button2">Search</button>
</div>
<script>
$(document).ready(function() {
$('#button1').click(function(){
var form = $(this).parents('form');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
window.location.href = "http://www.page-2.com";
}
});
return false;
});
});
</script>
Your form could as well do without a type submit..
Type can be a mere button.. On click, you could now do all your javascript stuff with onclick="javascript:somefunction()",
somefunction = function (){
Process javascript here
document.formname.submit();
location.href = "new.html"
}

Submit URL via AJAX / PHP set variable without refreshing page, load variable

I'm having an issue with some script to perform a function via AJAX without refreshing my page. I have a field for a user to enter an external URL, and when they click submit it pops up a modal window, with some information generated through a separate PHP page (images.php currently). I have the script working when the form is actually submitted, the page reloads, and images.php is able to see index.php?url=whatever, but I'm trying to update the page without having to refresh. Do I need to re-render the DIV after defining the variable? I think this may be where I'm having problems.
JS
<script type="text/javascript">
$(function() {
$("#newNote").submit(function() {
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $('#noteUrl).val();
$.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl},
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
HTML
<form id="newNote">
<input type="text" class="form-control" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
PHP (aside from form being submitted to this, this is also included in the modal, which opens, but returns NULL on var_dump($postUrl))
$postUrl = $_REQUEST['noteUrl'];
echo $postUrl;
I could definitely be missing something glaring here, but honestly I've tried every combination of AJAX example I could find on here. Am I missing a huge step about having PHP get the variable? Do I need to refresh a DIV somewhere?
Please help.
Here is a bit neater version of the same code, with the missing quote corrected.
$(function() {
$("#newNote").submit(function() {
$('#notePreview').empty();
var url = "images.php"; // the script where you handle the form input.
var noteUrl = $(this).find('#noteUrl').val();
var request = $.ajax({
type: "POST",
url: url,
data: {noteUrl: noteUrl}
});
request.done(function(data) {
$('#notePreview').append(data);
});
return false; // avoid to execute the actual submit of the form.
});
});
Add the attribute name="noteUrl" to your input
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
You can also do var_dump($_REQUEST); to see what request variables are being sent.
You might have missed the noteUrl as name. Try giving the name as below and get it using the same name. In your case it is noteUrl
<form id="newNote">
<input type="text" class="form-control" name="noteUrl" id="noteUrl">
<input type="button" class="btn btn-default" id="addNote" data-toggle="modal" data-target="#noteModal" value="Add Note"/>
</form>
Shouldn't this
var noteUrl = $('#noteUrl).val();
be
var noteUrl = $('#noteUrl').val();
^^^

submit event not capturing submit type input

I have a Ajax GET request as mentioned below
$(document).ready(function() {
$('#comment-edit-form').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: '/comments/edit/' + $(this).attr('comment_pk') + '/',
data: $(this).serialize(),
success: function(data){}
});
return false;
});
});
The form is something like this
<form method="get" id="comment-edit-form">
..
<input class="btn btn-primary" type="submit" name="preview" value="Preview">
<input class="btn btn-primary" type="submit" name="submit" value="Submit">
</form>
In this form, I have two different submit buttons! each has different operation!
The GET request URL I traced is something like below
?input1=1&input2=2...
I am expecting ?input1=1&input2=2&submit=
or ?input1=1&input2=2&preview=
Why I am not able to observe "submit" or "preview" names in the request??
This is because jQuery only serializes the nodeTypes input, select, textarea and keygen with input types that are not submit,button, image, file or reset.
Looking at the jQuery source code, you can tell that form elements' input type is checked against the following regular expression:
/^(?:submit|button|image|reset|file)$/i
This check is in .serializeArray which is called by .serialize in your code.
For the interested reader - this is the complete filter:
return this.name && // has a name
!jQuery(this).is(":disabled") && // is not a disabled input
rsubmittable.test(this.nodeName) && // is either input, select,textarea or keygen
!rsubmitterTypes.test(type) && // the test explained above
(this.checked || !manipulation_rcheckableType.test(type)); // checked

JQuery get formaction and formmethod

I have the a like this one
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button" onclick="popisgolubova_radiobutton(this)">
<input name="rodovnik" type="button" formaction="rodovnik.php" formmethod="post" formtarget="_blank" value="rodovnik" class="button" onclick="popisgolubova_radiobutton()">
<input name="podaci" type="button" value="poodaci" formaction="podaciogolubu.php" formmethod="post" formtarget="_blank" class="button" onclick="popisgolubova_radiobutton()">
</form>
and javascript
function popisgolubova_radiobutton(element)
{
alert($(element).find("[formaction]").val());
var popisgolubova_radiobutton=$("input[name=RadioGroup1]").is(":checked");
if(popisgolubova_radiobutton==false)
{
alert("nop");
}
else
{
$("form#popisgolubova_form").submit();
}
}
First I'm checking if any checkbox is checked or not and if it is the I can submit the form. But the problem is formaction, formmethod and formtarget. how to get them and submit them
To get the action or method attributes of a form you can try something like below:
$(function() {
var action = $("#formid").attr('action'),
method = $("#formid").attr('method');
});
Hope this helps to get an idea to solve ur problem
<form id="popisgolubova_form">
<input name="pregledaj" type="button" formaction="uredigoluba.php" formmethod="post" formtarget="_self" value="pregledaj" class="button postForm"/>
</form>
$(document).on('click', '.postForm', function () {
$('#popisgolubova_form').attr('action', $(this).attr('formaction'));
$('#popisgolubova_form').attr('method', $(this).attr('formmethod'));
$('#popisgolubova_form').attr('formtarget', $(this).attr('formtarget'));
});
So the question is talking about the unfortunately named
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formaction
...which is a way to override
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-action
per clicking a properly set up submit button. The place you want to check this is upon submit - when you're sure things are actually being submitted.
The button you used to submit is stored as :focus - this does not seem to be otherwise stored in the event object at the moment.
$('form').on("submit", function(event) {
if( $(':focus').is('[formaction]') ) {
console.warn($(':focus').attr('formaction'));
}
if( $(':focus').is('[formtarget]') ) {
console.warn($(':focus').attr('formtarget'));
}
});
if( $(':focus').is('[formaction]') ) {
console.log($(':focus').attr('formaction'));
}
I had this problem and after searching the web I couldn't find a proper answer. Finally, I realized it's so simple.
When you add an event on form.submit you have an event argument that contains e.originalEvent.submitter, just use it as follows:
$('form').submit(function(e){
var url = form.attr('action');
if (e.originalEvent.submitter) {
var frmAction = $(e.originalEvent.submitter).attr('formaction');
if (frmAction)
url = frmAction;
}
,.....
});
You can use the samething for the formmethod as well.

Submitting Value of Jquery Button To Server

I have a form with several buttons, i want to submit the form to the server using script so i use a function bind to the click events of the buttons. On the server side i want to be able to get the value of the button that was clicked. How can this be achieved?
Using the conventional method to post the form i am able to do a request.getParameter() and get the value of the button that was clicked. I would also like to do a request.getParameter() on the server side and get this parameter or some other more efficient method. Under is what i have:
jquery
function submitPage(){
document.getElementById("citizenRegistration").action="citizen_registration.htm";
document.getElementById("citizenRegistration").target="_self";
document.getElementById("citizenRegistration").method = "POST";
document.getElementById("citizenRegistration").submit();
}
$(document).ready(function(){
$('#query').click(function(e){
e.preventDefault();
//need to send the value of the button to server
alert($(this).val());
//alert("hello");
submitPage();
});
});
Jsp
<li><input id="save" type="submit" name= "user_request" value="Save"/>
<input id="update" type="submit" name= "user_request" value="Update"/>
<input id="query" type="submit" name= "user_request" value="Query"/>
</li>
function submitPage(actionFlag){
// actionFlag value can be save,update,Query
document.getElementById("citizenRegistration").action=
"citizen_registration.htm?actionFlag="+actionFlag;
document.getElementById("citizenRegistration").target="_self";
document.getElementById("citizenRegistration").method = "POST";
document.getElementById("citizenRegistration").submit();
}
And you can send the button value to the function.
$('#query').click(function(e){
e.preventDefault();
//need to send the value of the button to server
var buttonVal = $(this).val();
alert(buttonVal);
submitPage();
});
Hope this helps you.

Categories

Resources