Submitting Value of Jquery Button To Server - javascript

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.

Related

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

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)

Not able to reset input field in laravel

I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.
<input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
JS for reset button:
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = "";
};
Reset Button:
<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
Use type="reset" for your button:
<button type="reset">Cancel</button>
try using reset():
document.getElementById("app_number").reset();
In this case you must use JQuery Lib. Basic you need to set ID for this element. And in jquery you listen click on this Element.
$('#app_number').on('change', function () {
// enter code here
});
Please try to use in js like:
$(document).on('click', '#YourOnclickButtonID', function(){
var $alertas = $('#YourFormID');
$alertas.validate().resetForm();
});
So answering my own question, any feedback would be appreciated but this is working.
It turns out that no matter what value="{!! Request::input('app_number') !!}" will always have value as this code gets executed on the server side and unless you make another post request you can not change the value and by using only vanilla JS and without post request this cannot be done.
So, instead of getting values from Request why not just takes the values from user input and save it to local storage and then just grab it and inject into the input field.
I added onkeyup event ion to the input field
<input type="text" name="app_number" class="form-control" onkeyup='saveValue(this);' id="app_number" placeholder="Application Number" required>
and JS to store and retrieve input
document.getElementById("app_number").value = getSavedValue("app_number"); // set the value to this input
function saveValue(e) {
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val); // Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return ""; // You can change this to your defualt value.
}
return localStorage.getItem(v);
}
and then reset the form as usual
document.getElementById("appForm").onreset = function() {
document.getElementById("app_number").value = '';
};
Your reset button :
<button class="btn btn-primary" id="reset-button" onclick="myFunction()">Reset</button>
In js:
function myFunction(){
document.getElementById("app_number").value = "";
}

Need to submit a form without the onsubmit and include the action

Here is a form
<cfoutput>
<form name = "xrefform"
id = "xrefform"
action = ""
method = "post"
onsubmit = "return submitx('#coltop#', '#col#')">
</cfoutput>
There are two different way to submit it:
1) when you want the data in the form to be placed in a MySql Table
2) when you want the data to be deleted from the Mysql Table
For the first case I have
<input type = "Submit"
name = "SubmitXref"
class = "submitbut"
value = "Submit"
onclick = "aasubmit('xref2.cfm')">
with corresponding javascript:
function aasubmit(target) {
document.xrefform.action = target;
}//end function aasubmit
This works fine.
For the delete case I have
<input type = "Submit"
id = "delbut"
class = "onoffbut"
value = "delete"
onclick = "aasubmit('repdel.cfm')">
This has a problem, which is that the submitx() javascript runs, and in this case I don't want it to.
I find references that say using the document.form.submit() method will avoid running the onsubmit function. But I can't figure out how to indicate the action.
Can someone show me how to do this?
After fussing around some more I found the answer:
For the delete button --which needs to evade the onsubmit script --here is the HTML:
<input type = "button"
id = "delbut"
value = "Delete this item"
onclick = "buttonsubmit('xrefdel.cfm', 'xrefform')">
And here is the javascript.
function buttonsubmit(target, source) {
var q = document.getElementById(source);
q.action = target;
q.submit();
}
This works perfectly. The ordinary submit honors the onsubmit script, the delete button skips it.
Let's outline your requirements:
One form
Two submit buttons
No JavaScript submit.
If you give each of the submit buttons a name, then you can have a single action page and check which button was clicked.
name="doUpdate" or name="doDelete"
The only name key that will exist in the form scope is whichever submit button was clicked. Use structKeyExists() to check and process accordingly.
Of course, you probably want to use onsubmit="return validateForm()" to call a validation function. If you click on "delete", you might want the user to confirm that was what they wanted to do before processing it. The function validateForm() just needs to return true or false, so you'll still avoid the JavaScript submit().
Do something like this in the form:
<input name="action" value="save" id="action" type="hidden">
<button type="submit" class="button button-basic-green" onclick="document.getElementById('action').value='save';"><span class="fa fa-save"></span> Save</button>
<button type="submit" class="button button-basic" onclick="document.getElementById('action').value='reload';"><span class="fa fa-repeat"></span> Save & Reload</button>
<button type="submit" class="button button-basic" onclick="document.location.href='./';return false;"><span class="fa fa-arrow-circle-o-left"></span> Cancel</button>
Note the default action of "save". Gets you something like:
Then in the singular form-action page, check to see what the form.action is and process accordingly.
<cfif form.action eq "reload">
<cfset loc="page.cfm?id=#form.id#">
<cfelse>
<cfset loc="./">
</cfif>

Using hidden inputs to POST JavaScript function result

I have a single form input on my homepage userinput. The homepage also contains a JavaScript function that uses that userinput value to calculate a result.
<form action="/run.php" method="POST" target="_blank">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go!</button>
</form>
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
</script>
I'm trying to find a way in which a user can enter their input, submit the form, the JavaScript takes that userinput and calculates a result, then that result is POST'ed along with the userinput in the form.
The problem I can forsee with this method is that:
The JavaScript function needs the userinput before it can calculate the result. However, the only way to get the userinput is to submit the form, which means the form data will be POSTed before the JavaScript result is returned.
My attempted solution(s):
I've been attempting to use AJAX (Unable to access AJAX data [PHP]) and have been consistently running into issues with that.
I was wondering whether it's possible to use a button (type="button"), instead of a submit (type="submit") for the form. Then just use that button to call the JS function, then (somehow) submit the form (with the JS function result) after the JS function has completed? (either with plain JS or jQuery).
there are multiple approaches to do this,
i'm gonna use jquery here instead of pure javascript to simplify it
[without submission] you may check the event change
$('#userinput').change(function (e) {
// make some calculation
// then update the input value
});
[with form submission] you will disable the submission using the object preventDefault inside the submit event
$('#userinput').submit(function (e) {
e.preventDefault();
// make some calculation
// then update the input value
// your ajax goes here OR resubmission of your form
// to resubmit the form
$(this).submit();
});
What you will find useful in this scenario is event.preventDefault();
function calcResult(e) {
// Prevent the default action of the form
e.preventDefault();
var userinput = document.getElementById('userinput').value;
var result = userinput + 10;
// Do whatever else you need to do
// Submit the form with javascript
document.getElementById("myForm").submit();
}
I believe this is what you are looking for. A way of having the information computed over PHP, without a page request. This uses a form and then serializes the data, then transmits it to PHP and displays the result from run.php.
Note:
I did change your id to a name in the HTML so the code would serialize properly. I can change this per request.
index.php
$rand = rand(10,100);
?>
<form action="javascript:void(0);" id="targetForm">
<input type="hidden" name="idg" value="<?php echo $rand ?>">
<input type="text" value="12" name="userinput" id="userinput">
<button onclick="ready()">Go!</button>
</form>
<div id="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function ready() {
$.post('run.php', $('#targetForm').serialize(), function (data) {
$("#result").html(data);
})
}
</script>
run.php
<?php
echo floatval($_POST['userinput']) * floatval($_POST['idg']);
?>
Nowhere in your question is there any indicator that your task requires AJAX. You're just trying to change an input value right when you submit. AJAX is not needed for that.
First, attach an onsubmit event handler to your form instead of using an onclick attribute on your button. Notice, we are not stopping the form from submitting with return false as we still want the form to submit.
For convenience, let's add an ID to your form and let's add a hidden input field to store the calculated value.
(Side-remark: you don't need to use document.getElementById(ID) if the ID is a string with no dashes i.e. document.getElementById('userinput') can be shortened to just userinput )
<form action="/run.php" method="POST" target="_blank" id="theform">
<input type="hidden" id="idg" value="<?php echo $rand ?>">
<input type="text" name="userinput" id="userinput">
<input type="hidden" name="hiddeninput" id="hiddeninput">
<button type="submit">Go!</button>
</form>
<script>
// this will be called right when you submit
theform.onsubmit = function calcResult() {
// it should update the value of your hidden field before moving to the next page
hiddeninput.value = parseInt(userinput.value, 10) + 10;
return true;
}
</script>
One way is by onSubmit
<form action="/run.php" method="POST" onSubmit="return calcResult()">
<input type="hidden" id="idg" value="<?php echo $rand ?>"> // gets random url, can be ignored
<input type="text" name="userinput" id="userinput">
<button type="submit" onclick="calcResult();">Go! </button>
</form>
And when you return true then only form will submit.
<script>
function calcResult() {
var userinput = document.getElementById('userinput').value;
var result = userinput + 10; // want to POST result in a hidden input field w/ form
return true;
}
</script>

Action always going to Index using submit()

In my view, I'm using a function, submitForm(action) to submit the form on button click. This is one of many buttons that will use this function. The action parameter will indicate which controller method to use.
The function seems to generate the correct Action attribute (the path is correct in the console), but it is always directed to the Index method rather than the action parameter.
The button:
<input type="button" value="Save Only" id="save" onclick="submitForm('SaveOnly')" />
The function:
function submitForm(action) {
var $form = $("#myForm");
$form.action = ("/Area/MyController/" + action);
$form.submit();
}
You're not accessing the 'action' attribute of the form itself, but to the jQuery selector result, in order for your code to work, you need to access the DOM element from inside the selector with $form[0].
I recommend to stick to jQuery, you're already using it!. Below is a working code with jQuery selectors.
<form id="myForm"></form>
<input type="button" value="Save Only" id="save" data-action="saveOnly" />
<script>
$('#save').click(function(){
var action = $(this).data('action');
var $form = $("#myForm");
$form.attr('action', "www.google.com?q=" + action);
$form.attr('method', 'GET');
$form.submit();
});
</script>

Categories

Resources