How to pass variables from javascript to form? - javascript

In my application I get json with place details from google maps API using autocomplete
var place = autocomplete.getPlace();
I can get a name of the place with place.name
On the same page I have a form where I get another details from user. The question is how do I pass the place.name to my rails controller when the form gets submitted? In js I tried to change HTML of the form
<form...>
<div id="hidden_fields"></div>
</form>
using
$("#hidden_fields").append("<input name='name' type='hidden' value='"+place.name+"' />");
But apparently it doesn't works.
Should I learn AJAX to do such things or there another ways?
Thanks in advance for any hint.

Please ensure you are creating the hidden fields after the autocomplete finished. check the viewsource if the hidden variables has appended before submitting. As long as the control available with in the form tag before submit, your controller able to get it.

Thank you all! The problem has been solved. The important things I learned were
View/Source doesn't show dynamically added content, but Firebug does.
Rails modify forms field names: It turns
<%=form_for #place do |f| ...
<%= f.password_field :password , :class =>"form-field", :id =>"passwordField"
into
<input class="form-field" id="passwordField" name="place[password]" type="password" />
which means that I have to pass values from js in the same manner:
$text.append('<input name="place[name]" type="hidden" value="'+place.name+'"/>');
Hope it will help to someone else.

Related

Getting values from html form as JavaScript variables

i want to capture input variables sent via form from one page to another.html page and obtain these values as JavaScript variables. Can this be done.
This is my form;
<form action='another.html' id='form' data-ajax='false'>
<input id='sent_by' value='tom'/>
<input type='submit' value='Submit'/>
</form>
And in my another.html i tried to get the values as;
var sent_by = $.session.get("sent_by");
But i am not able to get the values. All help is appreciated.
You can use the browser's localStorage to achieve this. Before submitting and going to the other page store all the values of the form in the localStorage and you can access it on the other page:
Page1.html
Field Name = "name" <input type="text" name="name" id="name" />
Read the value and store it to localStorage
localStorage.setItem('name', document.getElementById('name').value);
and so on.
You can make a function in JavaScript that saves all the fields of the form in localStorage on / before submit.
To read these values on the other page:
Page2.html
Value stored for key name can be get using the following JavaScript:
localStorage.getItem("name");
NOTE
the page1.html and page2.html should be in the same domain for you to access the localStorage.
Read more about localstorage at https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
Have you tried using Window.localStorage? It's similar to sessionStorage but with no expiration date. So, be sure to clear it once the browsing session ends.
I think the answer provided by #Shakti Phartiyal is probably the most practical and a sweet trick I might add. The main reason I'm writing this post is because I had also taken a long path of using javascript to pass along this kind of information. It resulted in me bewildered at how powerful PHP can be for some tasks that you dedicated javascript to do. (Yea I know some javascript wizards out there can do everything with it, I'm just talking about basic programming tho). So if you wondered what the PHP way of passing this around:
Your modified html form:
<form action='another.html' id='form' data-ajax='false' method='post'>
<input id='sent_by' value='tom' name='uname'/>
<input type='submit' value='Submit'/>
</form>
and then in "another.php" you would have this to retrieve the input from the form:
<?php
$uname= htmlspecialchars($_POST['uname'];
?>
Great. But how to make this php variable into javascript?
Ah, the fun part. You're going to write javascript to your webpage with php - you do something like this:
var uname = "<?php echo $uname; ?>";

Redirecting form submission to URL after sending the details to database

I am working on a popup newsletter signup. I already have the similar signup form in another page. I used the exact code and it works great. Once I submit the form, two actions has to happen.
Sending the form details to database
Redirecting to thank you page.
With the existing code(this is from a ecommerce website, I cannot manipulate the code), I can send the details to database - perfectly works fine, but
it is not redirecting to Thank You page, instead redirecting to the page hardcoded in the database(assigned to "action". Is there a way out?
This is the code.
<form name="MailingList" method="post" action="http://www.mywebsite.com/MailingList_subscribe.asp">
<input type="text" name="emailaddress" placeholder="Email Address" maxlength="100" size="28"> <br>
<input type="submit" name="Submit" value="Submit" width="260px">
</form>
Instead of this - http://www.mywebsite.com/MailingList_subscribe.asp, I would like to redirect to "www.mywebsite/thankyou.html" . If I assign www.mywebsite.com/ThankYou.html to "action" , then the form is getting redirected to Thank you page, but not sending the information to the database. I have to use HTML, I cannot call from outside file. I guess I need to use PHP, but I am unclear with the code.
Sorry my mind is all over the place, I guess I explained it clearly. Apologies if my question is unclear. Thanks
Give id to your form like formId and you can do this using jQuery,
Download the jQuery latest version from JQuery repo and then place the jquery.min.js file in your resources folder.
Updated
<script src="yourResourcesFolderPath/jquery.min.js"></script>
// above code will use the jQuery plugin online
// chances are that the file path might be wrong according to where you put the js file
// A simple way to try this is put your file in the same folder of your html file and then change above code to
// <script src="jquery.min.js"></script> change file name according to downloaded file name.
<script>
$(document).ready(function(){ // will run the below code after all html loaded
$('#formId').submit(function(){ // will be called upon form submission
$.ajax({
type: "POST",
url: "http://www.mywebsite.com/MailingList_subscribe.asp",
context: document.body
}).success(function() {
// this will be called when you return from your server submit code
location.href = "www.mywebsite.com/ThankYou.html";
});
});
)};
</script>

jsp in javascript

I've created a jsp page. In that when i select 1 check-box or both check-box or none, the corresponding text-boxes and list-box must be displayed in the same page.
For that i tried of calling a javascipt function when i click the checkbox. The javascript function contain code to display the textboxes. But it didn't work.
Since I'm doing this project in struts, I don't know how to get check-box value. And calling of JavaScript function works. But didn't enter into jsp code in JavaScript function.
My code is
<tr>
<td>SEJ:</td>
<td>SEJ 1:<html:checkbox property="sej1" value="on" onclick="checkbox_trial()"></html:checkbox></td>
<td>SEJ 2:<html:checkbox property="sej2" value="on" onclick="checkbox_trial()"></html:checkbox></td>
</tr>
<script type="text/javascript">
function checkbox_trial()
{
<% if(request.getParameter("sej1")=="on"){
%>
<tr><td>SEJ1 Age<html:text property="sej1_age"></html:text></td></tr>
<tr><td>SEJ1 DOI<html:text property="sej1_doi"></html:text></td></tr>
<%}
else if(request.getParameter("sej2")=="on"){%>
<tr><td>SEJ2 Age<html:text property="sej2_age"></html:text></td></tr>
<tr><td>SEJ2 DOI<html:text property="sej2_doi"></html:text></td></tr>
<%}
else if((request.getParameter("sej1")=="on")&&(request.getParameter("sej2")=="on")){%>
<tr><td>SEJ1 Age<html:text property="sej1_age"></html:text></td></tr>
<tr><td>SEJ1 DOI<html:text property="sej1_doi"></html:text></td></tr>
<tr><td>SEJ2 Age<html:text property="sej2_age"></html:text></td></tr>
<tr><td>SEJ2 DOI<html:text property="sej2_doi"></html:text></td></tr>
<%}
else{%>
NOTHING <% } %>
}
This is how it works: Java/JSP runs at webserver, produces HTML/CSS/JS, webserver sends it to webbrowser, webbrowser runs HTML/CSS/JS. Not Java/JSP. Rightclick the page in webbrowser and choose View Source. If Java/JSP has done its job right, you shouldn't see any line of it in there.
If you want to invoke Java/JSP code using JavaScript, you've got to invoke another HTTP request to the webserver so that it can execute the Java/JSP code based on the specific request. You can do that by either submitting the form or firing an asynchronous (ajaxical) request.
Given the skills shown as far and the fact that you're using Struts, I think ajax is going to be a bit too complex. I'd suggest to just submit the form on click of the checkbox
<input type="checkbox" name="show" value="true" onclick="submit()" />
and then let JSP conditionally display the input fields (just a JSTL example since I don't do Struts)
<c:if test="${param.show == 'true'}">
<input type="text" />
<select />
</c:if>
Update: you've by the way another major problem in the code. You can't compare string values by == in Java code (you can do so in EL only). In Java code you need to use equals() method. Otherwise they will be compared by reference instead of by value. I'd suggest to learn basic Java as well.

ASP.NET 4 Form inside a webform page

I am new to programming but attempting to learn. Im running visual studio 2010 with an asp.net webform project using C#. I am trying to implement paypals buy now buttons on one of the pages and the code that is generated is in form tags also. No matter which button it is, the first button on the page never works and there is a solid blue line underneath it. All the other buttons work fine. even if i remove it, the next button becomes the first on the page and then it too doesnt work....i am learning that since all the pages are forms and the code generated is also a form, i cannot have a form inside a form. Is this correct?
Is there any way around this...all i really know is a lil HTML and a lil CSS, i am trying to learn JavaScript, C#, XML, CSS, ASP.NET, as well as Visual Studio itself. Any help would be greatly appreciated. If anyone wants to see what im talking about go to www.curbappealfordummies.net/Packages.aspx That is the site im working on and webmaster of...Thank you guys for your help.
This is a wide-reaching question, but one possible answer is to generate a second form which has the needed PayPal code in it.
This is a simplified example; usually there is logic needed to lead up to this point. For example, if the buttons need to be contained within the ASP.Net default form, there will need to be server and/or client code to connect them to this second form and to make sure that it contains the correct hidden values.
In Your WebForm
<form id="form1" runat="server">
<!-- Contents of your server form -->
</form>
<%=base.GetMarkupOutsideDefaultForm() %>
In Your CodeBehind
public string GetMarkupOutsideDefaultForm()
{
//
// Return the markup needed for a PayPal form,
// including javascript needed to automatically submit it.
// AppSettings can be any configuration object that contains
// the needed URL (or you can hardcode it)
StringBuilder sb = new StringBuilder();
sb.Append( "<form action=\"" + AppSettings.PayPalUrl + "\" method=\"post\" id=\"frmPayPal\" target=\"_blank\">" );
// add hidden PayPal fields
sb.Append( "</form>" );
sb.Append( "<script type=\"text/javascript\">document.forms[\"frmPayPal\"].submit();</script>" );
return sb.ToString();
}
If the logic is complex, the second block of code should really be contained in a helper class.
Hope this puts someone on the right path.
Maybe you need to start with a tutorial designed to help you get enough of the basics under your belt so that you can make better sense out of the things you really want to do... check out the video at http://www.asp.net/general/videos/build-your-first-asp-net-application-with-asp-net-web-forms and there are lots of resources there too. It's not that hard if you are motivated to learn, which it sounds like you are.
I know what you mean. Try adding an extra
<form action='https://www.paypal.com/cgi-bin/webscr' method='post' target='paypal'></form>
At the top.
Example:
<form id="form1" runat="server">
<div>
<form action='https://www.paypal.com/cgi-bin/webscr' method='post' target='paypal'>
</form>
</div>
<div>
<form action='https://www.paypal.com/cgi-bin/webscr' method='post' target='paypal'>
<input type='hidden' name='add' value='1'>
<input type='hidden' name='cmd' value='_cart'>
<input type='hidden' name='business' value='<%# DataBinder.Eval(Container.DataItem, "business_email") %>'>
<input type='hidden' name='no_shipping' value='0'>
<input type='button' name='submit' value='Add To Cart' title='Add to Cart Button'>
</form>
</div>
</form>
Simple, but it works.
Or, if you don't like that idea, try this post:
"Add to cart" button and ASP .NET are not working together

ASP.Net MVC, Submit a form using javascript

I have a form on one of my ASP.Net MVC views that I created using the following code
<% using (Html.BeginForm(null, null, FormMethod.Post))
Using this code I have no control as far as I am aware of setting the name of the form. I'm now trying to write a javascript function to submit the form, is this possible without knowing the forms name?
Thanks
You can use jquery to submit the form:
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "myForm"})) { %>
(the last part is for htmlAttributes parameter)
just do this:
$("#myForm").submit();
and do not forget to include jquery-1.2.6.js that comes with mvc (or use a higher version).
If you want to use jQuery without naming the form, and you will only have one form on the page, you can just add a link like this to your page:
Submit
And then add this jQuery which will wire up the link to submit every form:
$(document).ready(function () {
$("a.submitForm").click(function () {
$("form").submit();
});
});
So this is a way of doing it (the way I just did it on my site) that doesn't require you to name the form - provided you only have one. Saying that, you may want to submit multiple forms ..
If you have only one form on that page, you can access the form by using:
document.forms[0].
So you could add a link:
submit form
If you need to set name of the form, use object htmlAttributes parameter of BeginForm method.
<% using
(Html.BeginForm(null, null, FormMethod.Post,
new {name="MySuperForm"})) %>
For submitting forms through javascript, check out this post. Might be useful.
This simple solution submit the Ajax form without post-back
Generate
<input id="sbmt" type="submit" style="visibility: hidden" />
Works in IE and Firefox.

Categories