submitting form through javascript and passing a variable with it - javascript

I want to submit a form and add a javascript variable with it. I tried using AJAX but that didn't work properly because the form is cut in two parts on the same page. I'm now using a <button onclick='submit_form()'>send</button> which calls on the following function:
function submit_form()
{
document.getElementById("form2").submit();
}
however I need to pass on a javascript variable current_score I have it declared and it has a value I just don't know how to add this to my submit function I tried using a return within the function itself and writing a function for it but neither worked :) help and hints are greatly appreciated.
The idea is that people receive a score fill a form and send it to a database, The ajax script part was to try and pass the values on to the next page that will submit the data

Your question is not very clear. The simple way would be to append a get parameter to the URL you are requesting. The following example will append a hidden input element to your form:
var hidden = document.createElement("input");
hidden.type = "hidden";
hidden.name = "theName";
hidden.value = current_score;
var f = document.getElementById("form2");
f.appendChild(hidden);
f.submit();

You could store the information in window.variable also

Related

How send string parameter using Post Method from the view to the controller ASP.NET [duplicate]

Here is a line of code in my Controller class:
return JavaScript(String.Format("window.top.location.href='{0}';", Url.Action("MyAction", "MyController")))
Is there a way to make it use the verb=post version of MyAction?
You can't use POST by simply navigating to a different URL. (Which is what you'd do by changing location.href.)
Using POST only makes sense when submitting some data. It's not clear from your code what data would actually be POSTed.
If you really want to initiate a POST via javascript try using it to submit a form.
I came across the same problem myself and solved it using a data- attribute and some jQuery. The benefit of doing it this way is that you still get the correct URL when you hover over the link, even though it does a POST. Note that the Html.BeginForm contains the default action in case the user hits the enter key.
HTML (ASP.NET MVC3 Razor)
#using (Html.BeginForm("Quick", "Search"))
{
<input type="text" name="SearchText" />
Search
Advanced
}
jQuery
$("a[data-form-method='post']").click(function (event) {
event.preventDefault();
var element = $(this);
var action = element.attr("href");
element.closest("form").each(function () {
var form = $(this);
form.attr("action", action);
form.submit();
});
});
Continuing off of Matt Lacey's answer, your action could return a bit of Javascript that does this:
Use jquery to add a new form to the DOM
Use jquery to submit the newly added form
Something like this: (untested code)
var urlHelper = new UrlHelper(...);
var redirectUrl = urlHelper.Action("MyAction", "MyController");
var redirectScript = String.Format(#"
var formTag = $('<form action=""{0}"" method=""post"" id=""redirectForm""></form>');
$(body).append(formTag);
formTag.submit();"
, redirectUrl
);
return JavaScript(redirectScript);

fill articlenumber automatically after writing articlename

I have a HTML <form> and im creating it with php. It contains three <input> fields.
The second <input> field should be filled automatically, when the first one is filled. A HTTP request is triggered over an API. The request works fine and puts out the article number. I tested it already.
The problem is, that it has to run the request and fill the field, whenever the other field is filled.
I have tried it with jQuery:
<script>
$(document).ready(function(){
$("input[name*='artNr1']").click(function(){
.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
});
<script>
Any help is appreciated.
Form screenshot
I think you forgot to insert the $ (dollar sign) before .get()
Your code should be like this :
<script>
$(document).ready(function(){
$("input[name*='artNr1']").click(function(){
$.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
});
<script>
jquery provides the change() method to listen to change events, e.g. on <input> fields. You can replace the click() handler with it.
$("input[name*='artNr1']").change(function(){
$.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
The problem with your code is, that you call jquery.get() with the PHP variable $_POST['artName1']. This shows two flaws:
If the replacement with that PHP value works, it is evaluated on server side and therefore never replaced with the current value from the <input>, that is present on client side
You seem to expect the value to be transferred via POST, but you use jquery.get() to transfer it via GET.
To address the first flaw, you need to use the value from the first <input> instead of the value that was evaluated from PHP.
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
//TODO: $.get("artikelnamen_suchen.php", nummeruebergeben($_POST['artName1']));
});
Because you are currently in the onChange handler of the first <input> field, it is available as the this context in that function. With jquery.val() you can access its current value.
To address the second flaw, you can use two different ways. Either use the jquery.post()mehtod to send your data as POST to PHP:
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
$.post("artikelnamen_suchen.php", {
'artName1': articleNumber
}).success(function(result){
//Work with the result here
});
});
Or provide the information as GET and access it in PHP as a $_GET field instead of $_POST:
In javascript:
$("input[name*='artNr1']").change(function(){
var articleNumber = $(this).val();
$.get("artikelnamen_suchen.php?artName1=" + articleNumber)
.success(function(result){
//Work with the result here
});
});
In php
$articleNumber = $_GET['artName1'];
... //Use $articleName instead of $_POST['artName1'] in your PHP code.
After that you can work with result to replace the value in your second input. But thats another question... :-D

How do you get URL parameters in a Google Form using Google Apps Script?

So I've got a Google Form where I'd like to pass in a parameter from an email link like this:
https://docs.google.com/URL/forms/d/LONGSTRING/viewform?id=12345
I'd like to be able to grab that id and pass it into the spreadsheet recording results. Now I've got writing to a spreadsheet down, but getting the id is problematic.
I've already tried:
function doGet(e) {
var id = e.parameter.id;
Logger.log(id);
}
and
function doPost(e) {
var id = e.parameter.id;
Logger.log("do post " + id);
}
Both of which throw errors when I view the execution transcript, which I suspect is because they're designed to run within deployed webapps.
Additionally, I've tried using plain old javascript to do something like:
var formUrl = window.location.href;
var formId = formUrl.split('?id=')[1];
which also throws errors when you view the execution transcript .
Any other ideas?? Maybe I can get the information in another way?
I think you can't use your own id, you have to use the id of the Google Form's "Item" object. You can figure out the id by viewing a prefilled form. In the Form edit screen, click "Responses", "Get Pre-filled URL". Fill in the field that you want to use and click Submit. On the new page, you are given a URL in "Share this link to pre-fill the responses" . Examine that url and you can see "get" arguments like ?entry.265525444=mytext . Replace mytext with whatever you want to be in the field.
This will display the field on your form, however. I myself was searching for how to make such a field readonly or invisible when I got here, but I hope this shows you a new direction to try.
I am assuming you are trying to get the form id?
You will need to set up a trigger that will run on form submit.
function onSubmit(){
var form = FormApp.getActiveForm();
var formID = form.getId();
}

Can't get a JS var inserted into a hidden field

I promise...I have researched this for over 24 hours. I know it is similar (if not exactly the same) as some other questions. I'm obviously missing something. (This is going to be a long-winded explanation...I apologize. Please don't let it scare you off...I'm pretty sure the root problem/question will be much easier than what all this looks like!)
End result desired is to get some JS vars POSTed over to my process PHP script from an HTML form. Simple, right?
I have a fully working form that does a bunch of calculations with a bunch of input fields...it's way too complex to post here...not to mention I really don't want to embarrass myself with what I'm sure is very bad coding!
In a nutshell...I have a function that in the process of running sets various JS vars. I need to get these vars inserted into some hidden input fields so that they will get moved over to my processing PHP along with all of the "normal" inputs. All of these vars represent floating point numbers (if that makes any diff)
Here is my form definition:
<form id="multiForm" action="App_post.php" method="POST" action="javascript:void(0)" id="appform" name="appform">
I have a "master" function that starts all of the calculations primarily based on when the user selects various radio buttons. Various selectors are dynamically updated in the form as the user selects buttons (which in reality is a user selecting different options of club membership fees and "add-on" items...someone is bound to ask what I'm doing!)
$(function () {
...lots of JS code here along with the calculations that create the JS vars I need
}
(I assume this function is called via the action="javascript:void(0)" )
Let's focus on just one var right now. The JS var "regularfee" (along with all the others I want) exists after all of the calculations are done. I need to have these values plugged into the hidden fields so that they can get POSTed.
Here is an example of the hidden field:
<input type="hidden" name="regularfee" id="regularfee" value="">
Here is where I am getting lost. I have done a console.log(regularfee) in the function right after all the calculations are done...it is set to the float number 26.5 (which is correct)
Here are a couple of things I have tried so far:
document.getElementById('regularfee').value=regularfee;
// --OR--
document.getElementById('regularfee').value=regularfee.value;
document.getElementById("app").submit();
No matter what I've tried, I get blank values POSTED over to my process PHP. Based on the other questions I've seen, the hidden input field method appears to be one of the "accepted" ways of doing this. I am not stuck on this method...just looking for the easiest way to get my vars POSTed! What am I missing? All help extremely appreciated!
Try regular post or use AJAX to SUbmit.
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
This method gets all input in ur form including select and checked.
//multiForm form is your ID in ur form
var data = $("#multiForm :input").serializeObject();
after use ajax to save in php script.
$.ajax({
type: "POST",
url: "phpscript.php",
data: data,
success: function() {
alert("Input Success!");
}
});
How this will help you!
Technically, this syntax should be good to go...
document.getElementById('regularfee').value=regularfee;
This is assuming that the regularfee variable exists and it is of type float. Or even better use jQuery
$('#regularfee').val([your value here]);
Question, why do you have two actions in your form? How does it work?
<form id="multiForm" action="App_post.php" method="POST" action="javascript:void(0)" id="appform" name="appform">
Also, for peace of mind, also do a console.log to check the value of the hidden field after it's been set
You have two action attributes in your form. Remove the second one for "javascript:void(0)". It is not calling the function you think it is (the anonymous function you have there looks to be executed on dom ready).

calling an Action using javascript

Fairly new to the PLAY Framework and because of restriction at my work we are using the 1.2.5 version, and while up til now was able to do all my process using the regular process from HTML to Controller via form submit. I would like to call an Application.Action from a JavaScript function.
While I have a form where information is inputted, another non-submit button could be clicked to go on a separate page for extra information. I want to call a JavaScript function via the "onClick" and inside the JavaScript function call the "#Application.Action(some param...)".
I need to get what is in a particular input field before calling the action.
I tried to do that with a PLAY "popup" but that does not seems to work as I can't pass the parameters along.
so here is the snippet I have:
in HTML file (extends the main.html who has all the javascript file "include")
<form>....
some input fields here
submit button here
</form>
<button onclick="myFunction()" data-role="button" style="width: 5em">Click here</button>
in the JavaScript file that is included in main.html I have something like this
function myFunction() {
var inputField1 = document.getElementById('inputField1').value;
var inputField2 = document.getElementById('inputField2').value;
var inputField3 = document.getElementById('inputField3').value;
window.location = "#{Application.moreInfo(inputField1, inputField2, inputField3)}";
}
Of course that does not work
Is there a way to do it like that?
Do I have to create a route for that?
I was able to reach a separate page by replacing
window.location = "#{Application.moreInfo(inputField1, inputField2, inputField3)}";
with
window.location.href='/goThere';
as long as I have a route
/goThere Application.goThere
but I could not figure out a way to pass parameters, I tried to set the route like
/goThere/{inputField1}{inputField2}{inputField3} Application.goThere(inputField1...)
but I guess I do not have the right syntax either.
Is there a way to call an Application.Action and pass it parameters/fields from a JavaScript function.
Any help is appreciated
The built-in #{jsAction /} template tag does exactly what you want.
Example:
Assume you have a route
GET /moreinfo/{foo}/{bar} Application.moreInfo
You can use the result of jsAction to get the correct URL with the parameters you want:
var fieldOne = "I'm a Javascript variable";
var fieldTwo = "Really? Me too";
var moreInfoAction = #{jsAction #Application.moreInfo(":foo", ":bar") /};
// and since it looks like you want to set the current location
// to your freshly obtained URL:
window.location.href = moreInfoAction({"foo": fieldOne, "bar": fieldTwo});

Categories

Resources