How can I pass parameters to a new page from Javascript? - javascript

I have the following code:
$('#CreateButton').click(function (event) {
var datastoreValue = $("#SelectedDatastore").val();
window.location = "/Q/Create?datastore=" + datastoreValue;
});
It works good but I would like to have the datastore=XYZ hidden from my user. Is there another way that I can pass this information so I would be able to read it in my MVC controller. Currently I read it like this:
public ActionResult Create(string datastore)
{
When inside this method the value of datastore is available to me.

Surround you code with a form tag with a method set to POST. Also add HttpPost attribute above your Create action. This will post the data to your action without client seeing the query string value. If you are posting to another action that specify that in your action attribute inside form. For example,
<% using (Html.BeginForm("Create", "MyController", null, FormMethod.Post)) { %>
<%: Html.Label("Data store value: ")%>
<%: Html.TextBox("datastore") %>
<input type="submit" value="Submit" />
<% } %>
Your Create action will pick this up and do the rest.
Hope this helps,
Huske

You could put the datastore value in a cookie to hide it from the user, though cookies are best used for settings that you want to last awhile, not settings that are meant just for one page.
Or, you could use a Post and put the create information in a hidden form and submit that.
Or, you could use an Ajax call to issue the create and then change the page yourself afterwards.
Otherwise, the query parameter like you are using is a standard way of specifying page-level parameters for a new page.

If you stay on the same website, you can post your data to your controller; it will pick up the data from the post collection and your url won't display the query string parameters.
Just wrap your form with the control whose id is SelectedDataStore in a tag with the action set to your url and the method set to post
Here is one quick example with a submit button:
<FORM action="/Q/Create" method="post">
<INPUT id="SelectedDataStore" />
<INPUT type="submit" value="Send">
</FORM>

Related

How to pass a variable to a specific html page in javascript and call that variable when needed on that page

I am new to html and javascript coding. So i have encountered a problem where i have to send a variable to a specific page and call that function out when needed.
function submit() {
firstname = document.getElementByName("firstname");
document.write(firstname);
}
<html>
<body>
<form>
<p>firstname: <input type="text" name="firstname" />
</p>
<input type="submit" onclick="submit()" />
</from>
</body>
</html>
now what should i do if i want to display the first name on a specific html page in javascript. For example, if i want to display the person name on third page then what should i do.
When you need to pass on an information from one page to another in the web, the general way you do is to use server side sessions. As I can see that there's no server side languages you are using, I believe you have only two options:
Using Query String Parameters (this works all the time).
Using Cookies (if the user has enabled it).
Using Local Storage (if your browser supports it).
For the first option, see How can I get query string values in JavaScript? For the second option, it's been answered a lot of times, so I'll leave the implementation with you: Set cookie and get cookie with JavaScript.
For the second one, you just need to use localStorage object this way:
function submit() {
var firstname = document.getElementByName("firstname");
document.getElementById("output").innerHTML = firstname;
if (!!window.localStorage) {
localStorage.setItem('firstname', firstname);
}
return false;
}
<form onsubmit="return submit();">
<p>firstname: <input type="text" name="firstname" /></p>
<input type="submit" onclick="return submit();" value="Save" />
</form>
<div id="output"></div>
I have also made some changes in your form submission method. And in your new page, you just need to use this code to get the item.
function getname() {
return localStorage.getItem('firstname');
}
There are multiple ways to resolve this issue but it is based upon your requirements. Are you going to third or any other page via a server navigation or is it client-side navigation. In any case you can use localstorage which is supported by almost all latest browser.
On first page you can do localStorage.setItem('firstName', 'Tom'); localstorage is globally available keyword.
On any other page then you can get the value by
var name = localStorage.getItem('firstName');
Other options you can look at cookies, querystring and session storage
when redirecting to next page, bind parameters in redirecting url like this,
window.location.href = "http://yoursite.com/page?data1=one&data2=two";
And fetch them from retreiving end like below,
var url_string = "http://yoursite.com/page?data1=one&data2=two";
var url = new URL(url_string);
var parameter_1 = url.searchParams.get("data1"); //returns "one"
var parameter_2 = url.searchParams.get("data2"); //returns "two"

Yahoo Merchant Store Catalog Tags Insert Dynamically with Javascript, Jquery, or Ajax

I opened up a yahoo store through their Merchant Service. They have a pretty good store catalog that I have used on a business site that I own. I like it so I decided to use the service again on another business I own. I got the site built but have ran into a few issues with calling the Yahoo Catalog Tags. The tags are basically comments. EX: (<!--#ystore_order id=item_id -->). When the site is loaded it is parsed and the page loads the product details in place of this tag/comment.
I can get everything to work except for the action attribute of my form.
I have tried a bunch of things but I cannot seem to get the action set for my form. If I hard code the tag then it works fine but obviously if I did that then I would have to create a page for every single product.
My form:
<div id="list">
<form method="post">
<input id="btnSubmit" type="submit" value="Add To Cart">
</form>
</div>
Trying to add the comment/tag to form action attribute. I've done it this way(below) and also by getting rid of the variable and just paring the url in the jquery attr function.
<script language="javascript">
$.ajaxSetup({cache: false});
$(document).ready(function(){
//Get URL from URL Query String.
var obj = getUrlVars()["Object"];
//Set form action attribute
$('form').attr('action', '<!--#ystore_order id='+ obj +' -->');
});
</script>
I've also tried creating the form dynamically.
<script language="javascript">
$.ajaxSetup({cache: false});
$(document).ready(function(){
//Get URL from URL Query String.
var obj = getUrlVars()["Object"];
var new_form = '<form method="post" action="<!--#ystore_order id='+obj + ' -->">' +
'<input type="submit" value="Add To Cart" id="btnSubmit">' +
'</form>';
$('#list').append(new_form);
});
</script>
I have tried to escape some characters but have had no success there either.
"\<\!--#ystore_order id='+obj + ' --\>"
I know the issue has something to do with the comment syntax but if I can add it manually then I should be able to do it dynamically. I know this is a hard one to test but if anyone thinks they may have a solution I would be happy to set up an ftp account on my site so you can test and I will provide the product ID's for testing. I've fought with this for about 30+ hours.
Yahoo store tags are populated server-side. Adding a store tag on the client side using Javascript won't do anything, because the code that recognizes the store tag and appends the appropriate html will never see the tag you drop in on the client side. There's no client-side solution possible
The best solution here would be to write a server side program to populate a template with the appropriate tag in response to http requests. I'm not super-familiar with the Yahoo store, so I don't know what the best language for this would be, but it would be a very simple program given how straightforward it sounds like your template is. Since this is already embedded in a site you own, I'd just use whatever backend language you are already working in.
Once you have a server side script that executes and returns the html you need, you could use AJAX to populated it with the appropriate product details as needed.

confusing syntax in JSP portal

JSP code in Liferay portal..
<portlet:actionURL name="addDetails" var="addDetailsURL" />
where from var gets value ?
var just exposes the action URL value through a variable named addDetailsURL. This is so that you can use it conveniently in a link as so:
Link
is used to perform any action(Action Phase) i.e user submitting form and controller(processAction) processes that request.
i.e
<form action="<%= addDetailsURL %>" method="POST" name="form">
// input fields which will get submitted to controller
</form>
from pageContext.
ActionURL.toString() is assigned to addDetailsURL and added to pageContext

php form : twig parameter from javascript or textarea html

i have a textarea defined by an id
<textarea id='vegetable'> Tomato </textarea>
i have a button
<button type="button" onclick="MyFunction()">generate vegetable</button>
which trig a javascript in order to modify the content of the textarea
<script>
function MyFunction()
{
document.getElementById("vegetable").innerHTML = VegetableNameGenerator();
}
</script>
The problem is this php action :
<form action="{{ path('mypath', { 'myparam': ??? }) }}" method="post" >
<input type="submit" />
</form>
??? must be the content of the textarea (which is also known by the javascript code) but i don't know how to access it in twig.
I guess there are several way of doing that : jquery, dom, global variable twig... any syntax example would be great.
This is impossible in the way you're describing it.
When a request is made to the server, twig renders the page, then it is sent to the browser, and then javascript can run.
There are options for how to make this work:
Create a controller action which returns the rendered path when you call it using a GET request with the provided parameter. Then create an event listener on the submit button that blocks the submit process until it has retrieved the route via AJAX and modified the form's action attribute.
Redirect from your controller to the path you want displayed. myparam will be included in the post data, so you can redirect from your controller action after you've handled the form.
$this->redirect($this->get('router')
->generate('mypath',
array('myparam'=>
$this->getRequest()->get('myparam')
),
true);

Spring MVC - Set an actionURL parameter with Javascript

Is it possible to dynamically set a Spring MVC portlet:actionURL portlet:param using javascript? I have tried with the following code, but the id value always comes across as null to the controller. I have verified that setting the portlet:param manually passes the value correctly:
<portlet:param name="id" value="2" />
I have also verified the value in the javascript is being set correctly and is not null.
(Note: I've changed the variable names, etc. from the original code to simplify it and obfuscate it since it is my employer's code.)
JSP:
<portlet:actionURL var="modifyURL">
<portlet:param name="do" value="modify" />
<portlet:param name="id" value="${model.id}" />
</portlet:actionURL>
...
<form:form action="${modifyURL}" id="modifyForm" modelAttribute="model">
<form:hidden path="id" id="id" />
</form:form>
Javascript called when the update URL is clicked:
function update() {
document.forms[0]["id"].value = selectedId;
document.forms[0].submit();
}
Controller:
#RequestMapping(params = {"do=modify"})
public void modify(#ModelAttribute("model") Model model,
#RequestParam(value = "id", required=true) Long id,
ActionRequest request, ActionResponse response,
SessionStatus sessionStatus, ModelMap modelMap) {
....
A co-worker figured it out. It looks like you just have to add the parameter to the action within the javascript and not include it in the actionURL or form.
JSP:
<portlet:actionURL var="modifyURL">
<portlet:param name="do" value="modify" />
</portlet:actionURL>
...
<form:form action="${modifyURL}" id="modifyForm" modelAttribute="model" method="POST">
</form:form>
Javascript called when the update URL is clicked:
function update() {
$("modifyForm").action = '${modifyURL}&id='+selectedId;
$("modifyForm").submit();
}
I came across this almost 3 years later, still i found it easier to add a hidden form field and when the action is clicked than to set this value to the hidden field
something like
<input type="submit" id="btn_terminate_cmpn"
value="Terminar campaƱa" onclick="setAction('terminate');">
and the javascript code
function setAction(action){
$("#actionToDo").val(action);
}
The URL generated by the portlet tag is on the server side. Javascript doesn't see the portlet tag. It only sees the actual URL. What your coworker is suggesting would work but it's not a good approach. Here he's just adding the dynamic parameter as a query string parameter which makes it visible to all the portlets on your target portal page. A better solution is to keep a hidden element (text box or something) and set the dynamic value to this hidden element in your onSubmit Javascript hander function.

Categories

Resources