passing information using javascript - javascript

can we pass any info., say a string between html pages using javascript. No forms, input fields I am using just want to pas some info in hyperlink.

What's your use-case?
There are lotta ways to do it. Say...
Storing the data in a session cookie (Assuming that you're accessing 2 pages from the same domain.)
Passing data in query string?
For example,
<input id="btnClickMe" onclick="btnClickMe_onClick()" type="button" />
...
<script type="text/javascript">
function btnClickMe_onClick() {
var data = "foo";
var urlOfNewPage = "http://www.test.com/testPage?data=" + data;
// Redirect user to the new URL
}
</script>

By the expression "info in hyperlink" i guess you want to let user inititate communication by clicking on it.
This could work:
Click here
<script>
extra_data = "key1=value1&key2=value2";
document.getElementById("mylink").href = "http://example.com/?" + extra_data;
<script>

Yes. There are many simple ways to do this if all you need to do is pass a short string. You could include a string in a link after a '#' and have that read by Javascript on the next page (looking at location.hash).
Without knowing more, its hard to narrow the approach down to suit your needs.
Simple Example:
one.html
...
Pass data
...
two.html
<script>
var passedData = location.hash.replace('#','');
alert('You passed this data: ' + passedData);
</script>

Related

Localstorage mistake, best way to correct?

I am still abit of a noob and I made a site with an admin panel where I made the option to change the price showed on the front page.
However I have made this with Localstorage and it works great but it probably wont show for other visitors right?
My current Localstorage code:
<script>
function save(){
var gpprice = document.getElementById('gpvalue').value;
localStorage.setItem("price", gpprice);
}
</script>
<script>
function save3(){
var gpprice3 = document.getElementById('gpvalue3').value;
localStorage.setItem("price3", gpprice3);
}
</script>
And to display it on the front page:
<script>
window.onload = function() {
document.getElementById("product-price1").innerHTML = "$" + localStorage.getItem('price') + "/M";
document.getElementById("product-price2").innerHTML = "$" + localStorage.getItem('price3') + "/M";
}
</script>
It works really good for me and I would like a similar system.
So I guess my question is how can I correct this oopsie? Should I use MySQL instead to store the value? Or is there a way to still use this?
No one else can access your localstorage data. You need to store it in a database.

Javascript: Is there a simple way to pass data from one webpage to the other?

I have one .html file where I click some checkboxes and store some data on an array.
All I need is to pass the array data to one other .html file.
Searching on Stack Overflow I found some answers, for example "How to pass JavaScript object from one page to other".
From what I figured out one way is to use Web Storage API and specifically the Window.localStorage.
Here's an example using basic HTML and querystring manipulation without using localStorage or sessionStorage, although these are actually very simple APIs and worth looking into.
HTML1 (sender):
This page will get the string representation of an object and then escape its content for transport in the query string.
<script>
var obj = { givenName: 'John', familyName: 'Doe', age: 45 };
console.log(obj);
function passToNextPage() {
window.location = 'test2.html?' + escape(JSON.stringify(obj));
}
</script>
<button onclick="passToNextPage();">Pass</button>
HTML2 (receiver):
This page unescapes the querystring and then parses the JSON text as an object, ready for use.
<script>
var json = location.search.substring(1);
json = unescape(json);
var obj = JSON.parse(json);
console.log(obj);
</script>
Localstorage is very simple - go for it. Only catch is that it saves the data on the user's own computer so it is (a) not available to other users, and (b) able to be seen with the right tools.
Another option, though, is to use a <form> - that's what they're for.
page1.html
<form action="page2.html" action="get">
Name: <input name="thename" type="text" /><br>
<input type="submit" value="Send It" />
</form>
In page2, to get the data from the first page, you can either use PHP (which means your page would be named page2.php and begin with <?php //php code here ?> or with Python or some other backend language.
For more information:
https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data
From your question, I think Localstorage will be a good option.

js refresh page while passing variable in yii

I am trying to refresh the page while pass an array from an onclick button.
Since I am using yii, posting isn't an option, and setting a session variable wasn't working. Any ideas would help. Thank you
<a style="width:100%;" onclick="my_picks_reset()" id="my_picks_reset">Reset</a>
<script>
$(function() {
/*set var picks = array of TBA and reset th my_picks div*/
$("#my_picks_reset").click(function() {
var my_picks = ['TBA','TBA','TBA','TBA','TBA','TBA','TBA','TBA'];
var url = document.URL;
$(location).attr('href',url,'my_picks',my_picks);
})
})
</script>
It seems from your comments that you're expecting POST request. Changing location of the page will give you GET request. So you have two options here:
1) Continue using location and read the the values from $_GET variable.
If you decide to use this option your need loop through my_picks array and construct the query string that would look like that:
?my_picks[]=arrayValue1&my_picks[]=arrayValue2... and do location.assign(currentLocation + composedQueryString)
2) The second better solution is to use $.ajax() to send values with post method.

Convert Form Post to Querystring

I am working in ASPDotNetStorefront on an XML package (largely irrelivant). Basically I have a form with a bunch of fields and a button that 'submits' the form. I would actually like to have the button convert the values of the fields into a querystring and then perform a GET instead of a POST.
I would imagine that I could do something like this with JavaScript, perhaps jQuery, but I'm not sure how I would do that. Ideally, I would like a simple function I could call.
I should note that I'm using ASP.Net and I only want to convert the actual values of the fields to a query string, not any state information. This is for a search form.
With jQuery:
$.ajax({
url: 'url/Action',
type: 'GET',
data: $('#formId').serialize()
})
using:
jQuery ajax
jQuery serialize
Response.Redirect("Webform2.aspx?Name=" +
this.txtName.Text + "&LastName=" +
this.txtLastName.Text);
in WebForm2.aspx you can do like this
for (int i =0;i < Request.QueryString.Count;i++)
{
Response.Write(Request.QueryString[i]);
}
for jquery you can use AJAX to send data between pages. Here is the sample code
This is the best article i have found Using jQuery for AJAX in ASP.NET : codeproject
example of using AJAX
<div style="width:350px">
<div style="background:#CCC"> Edit</div>
<div id="divView"><asp:literal id="litName" runat="server"/></div>
<div id="divEdit" style="display:none"></div>
</div>
var options = {
method: 'POST',
url: 'ChangeName.aspx',
after: function(response) {
$("div#divView").html(response).show();
$("div#divEdit").empty().hide();
$("a#editName").show();
}
};
//bind to form's onsubmit event
$("form#ChangeName").ajaxForm(options);
Example without AJAX.Simple Javascript with Query String
<script lang=”javascript” type=”text/javascript”>
function testQueryStrings()
{
window.location = “search.aspx?q=abc&type=advanced”;
}
</script>
<input type=”button” id=”btn” value=”Test Query Strings” onclick=”testQueryStrings()” />
for search.aspx
<script lang=”javascript” type=”text/javascript”>
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split(‘&’);
for (var i=0;i<arr.length;i++){
// splits each of field-value pair
var index = arr[i].indexOf(‘=’);
var key = arr[i].substring(0,index);
var val = arr[i].substring(index+1);
// saves each of field-value pair in an array variable
arrQrStr[key] = val;
}
document.write(“<h1>Search parameter: “+arrQrStr["q"]+”. Extra parameter: “+arrQrStr["type"]+”</h1>”);
You could do this:
<input type="submit" value="get">
With (since you tagged this jQuery):
jQuery('input[type=submit]').click(function () { this.form.method = 'GET'; });
… but forms that might go to bookmark-able data or might make significant changes sound like they would be confusing to the user (and I can't think of any other reason to switch from post to get on the fly in end user controls).
If you always want to GET data, then you should modify the source sent to the browser instead of twiddling the DOM on the fly with JS.
Really, you just need to change the method attribute of your <form> tag in your HTML.
If you don't have direct control over the markup that your .NET component generates, you can always manipulate the <form> tag and set the attribute with JavaScript when the page loads.
Or, you can bind a click event to the form's submit button, and cancel the event (by returning false for example), and do a GET yourself.
You could just se <form method="GET"> instead of <form method="POST">. No Javascript needed (unless you do not want to refresh the page).

Servlet calling from window.showModalDialog(...)

I am calling another application context from window.showModalDialog but confused with following work. Same code to pass parameter within showModalDialg.
var myArguments = new Object();
myArguments.param1 = "Hello World :)";
window.showModalDialog("java2sTarget.html", myArguments, '');
and i can read these myArguments(parameters) in generated HTML using following code:
<script>
document.write(window.dialogArguments.param1);//Hello World :)
</script>
I can't use query string & i am sending myArguments(parameter) because i want to hide parameter from Application user.
Now i am calling servlet from showModalDialog(..)
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test',myArguments,'');"
But as per my knowledge
Servlet --> Servlet container --> HTML+JS+CSS
so JS will be available at last phase, but i want to use in first phase(Servlet).
Now, i need to make some Decision in servelt code based on myArguments(parameter).
is there any way to read these myArguments(parameters) in servlet code?
Pass it as a request parameter in the query string.
var queryString = "param1=" + encodeURIComponent("Hello World :)");
onclick="window.showModelDialog('http://localhost:7778/app/servlet/test?' + queryString, myArguments, '');"
No, there's no other alternative. The request URL is not visible in the modal dialog anyway.
As main objective is to hide query string from User to avoid misuse of those parameters.
I tried following work around.
Developers send hidden parameters to get relative information form source(e.g.:DataBase). And we also know that we can send hidden information in Window.showModalDialog using dialogArguments
Work Around:
(i) I got relative information from server one-step before calling Window.showModalDialog using jQuery.getJSON()
(ii) i used google-gson API at servlet side to convert JavaBeans into Json strings.Solution 1 Solution 2
(iii) Convert JSON into javascript object using jQuery.parseJSON
var args = jQuery.parseJSON(json);
window.showModalDialog("pages/"+args.pageName, args, '');
i used args.pageName to make things dynamic
Please suggest improvements in this work-around. Thanks

Categories