Pass Parameter to Querystring AND Fire Javascript Function - javascript

I have a search function that returns an arraylist of objects to my form. I am iterating through the list using JSTL's foreach tags.
<c:forEach items="${searchResults}" var="contact" varStatus="loop">
<div style="padding: 5px;">
${contact.firstName} ${contact.lastName}
<br>
${contact.primaryPhone}
<br>
//Is this the proper way to set up the url?
View Contact
</div>
<br>
</c:forEach>
When the user clicks the link inside each row, the row index is passed to the querystring and at this point I would like to show a div that contains additional information about the user.
I have a javascript function that I use to display the div and center it on the screen bla bla bla, but my question is how do I refresh the page with the index loaded into the querystring and then fire my javascript function?
I considered using:
<c:if test="${not empty param.id}">
//Check if id in querystring is available and if so, display popup
</c:if>
To check if there was an index available in the querystring, but I don't think there is a way to fire my function from within a JSTL tag.
Should I be doing something on the server side when I request back to the servlet rather than trying to handle this on the client side? I just figure its a waste to requery my database and set another request parameter, when I already have the information I need stored in a parameter than I am using to display my list anyways.

You can embed a script tag within the parameter check, and run whatever you want within it. For example, set some variable that you can test later on, when the page finished loading.
Or, if you embed the parameter check late enough in the page, just invoke your function.
<c:if test="${not empty param.id}">
<script>
runSomeFunction();
</script>
</c:if>

The solution I eventually came up with is to check for my id parameter in the querystring each time the page loads (with javascript)
function init(){
console.log("Contacts page loaded.");
//Loads popup if 'id' is present in the querystring.
if(getQuerystring('id', 'null') !== 'null') {
showCenteredDiv('popup');
}
};
The function I use to check the querystring is:
//Search querystring for a specific parameter. Second arg is the value to display if its not found.
function getQuerystring(key, default_)
{
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null) {
return default_;
} else {
return qs[1];
}
}

Related

call a perl function on click of a button and fill the return value into a textfield in a form

I'm completely new to the HTML, javascript & web world. My requirement is as follows.
UI layout
username: __________ |find button|
First name: __________
Last name: __________
e-mail: __________
To be done
user enters a user name in the username textfield & clicks on find button
On click of find button, call the Perl method getDetails("enteredUName")
Capture the return value from the called Perl method and fill the details in the remaining textfields (first, last names & email).
I've the form and the searching logic ready.
Now my confusion is what should I put in the -onClick attribute of the search button. In the code, for forms, there's always javascript calls written for other buttons. So how should I make a call to the Perl method upon click of the search button and fill the remain text fields?
Update
Based on my current understanding did the following:
Defined a hidden boolean parameter isUsernameGiven, with initial value 0, in the form
When user types something in textfield with name usernameText and clicks search button, invoke javascript which sets the value of isUsernameGiven to 1 and the window location with a specified action.
Action is routed to the Perl module file via the application perl script. In this module, the search happens based on usernameText parameter
Newly appearing form comes with the details pre-filled.
Code Structure
ApplicationDirectory
application.pl
ModuleFolder
ModuleFile.pm
application.pl:
...
if ($action eq 'save') {
my $m = new ModuleFile();
}
...
ModuleFile.pm:
...
sub new {
# param isUsernameGiven is preserved/carried over from previous??
my $isUsernameGiven = param('isUsernameGiven');
if ($isUsernameGiven != 0) {
param(-name=>'isUsernameGiven',-value=>$isUsernameGiven);
}
if ( $action eq "add" ) {
showAddForm($self);
} elsif ($action eq "addEmp") {
showAddForm($self, $self->getUserInfoFromActiveDir(param('usernameText')));
}
}
sub getUserInfoFromActiveDir {
# search info and return employee object
...
}
sub showForm {
...
print "\n<form name=\"edit_employee_form\" method=\"post\" action=\"application.pl\" onSubmit=\"return validate_form();\">\n";
print "<input type='hidden' name='isUsernameGiven' value='0'/>\n";
print "<table class=edit style=\"width:420px;\">\n";
my $findButton = '';
if (!$id) {
$findButton = "<td>\n".button(-value=>"Find", -class=>"bigbutton",
-onClick=>"document.edit_employee_form.isUsernameGiven.value=1;getDetailsFilled();")."</td>";
}
my $fieldname = 'username';
print "<tr><td>Username:</td><td > \n".textfield(-name=>$fieldname -default=$unameValue,".
"-size=>30, -maxlength=>50)."</td>".$findButton."</tr><br>";
print "<tr><td>First Name:</td><td > \n".textfield(-name=>'first', -default=>$fnameValue, -size=>30, -maxlength=>50)."</td></tr>\n";
print "<tr><td class=edit>Last Name:</td><td > \n".textfield(-name=>'name', -default=$lnameValue, -size=>30, -maxlength=>50)."</td></tr>\n";
...
}
ModuleFile.js:
...
function getDetailsFilled()
{
if ( document.edit_employee_form.username.value == "" )
{
alert ( "Please fill in a username." );
document.edit_item_form.username.focus();
} else {
// Call Perl method here
window.location="application.pl?application=ModuleFile&action=addEmp";
}
}
...
Problem
Upon clicking the find button nothing happens. What did I miss?
Seems the parameter isUsernameGiven is coming as undefined in the sub showform.
Do the param values get preserved or reset for every ModuleFile object?
How's the value coming as undefined if the default value of isUsernameGiven is set to 0?
Is my understanding of params correct?
Is my current overall approach correct?
You can't do this without involving Javascript (well, you probably could, but 99.9% of your users will have browsers that can only use Javascript for client-side programming).
You need to do it like this:
Set up a Javascript event handler on your find button which grabs the username value and makes an AJAX call to your web server, including the username.
Write an AJAX handler sitting on your web server which takes the username, calls your code, formats the data as JSON and returns that data to the browser.
Set up Javascript in the web page that takes the JSON returned from the AJAX call, extracts the various data items and inserts them into the appropriate part of the page.

Getting the value of # from a url

I have a problem. i have a website am working on. I have created a php script to fetch all the receipts id from the data base using pagination, and all works fine. But the problem is every receipt id, i have added a link so as when clicked a specified results will be displayed without loading the page.
The links are like :
G145252 G785965 and when each link is clicked will show http://test.com/?go=any#G145252
When clicked the page will not reload.
So what i need help with is how can i get G145252 from the url after when the link is clicked using javascript and print it using html?
i need to pass the value to the process.php as a $GET value so the i can load the receipt detail of the clicked id with out reloading the page.
Please note: there are a lot of get values before the #value i need to get out of the url address.
You should not be using the fragment identifier section of the URI for server side related tasks. This section is intended for client-side manipulation only. More info here.
You can use some other means such as query parameters to access this data.
For example, turn this:
http://test.com/enter code here?go=any#G145252
Into this:
http://test.com?go=any&hash=G145252
Then:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
console.log(getQueryVariable("go")); // any
console.log(getQueryVariable("hash")); // G145252
NOTE: I know this is not the exact answer to your actual problem, but the question itself is presenting a bad practice scenario, thus my suggestion.
Credits for the getQueryVariable function goes to CSS Tricks: https://css-tricks.com/snippets/javascript/get-url-variables/?test=3&test2=5
Let's assume you're using jQuery.
Change all your links so that they have a common class name, lets say 'hashClick' e.g
My Link
To get the hash part when clicked, add a click event handler for those links
$('.hashClick').click( function(event) {
event.preventDefault();
var url = $(this).attr('href');
var hash = url.substring(url.indexOf('#')+1);
alert("You clicked " + hash);
// or at this point you can do an AJAX call
// or GET request to process.php with hash as one of the parameters
})
suppose this is the link
http://test.com/?go=any#G145252
to get the hash value
window.location.hash
which will return you #G145252
and
window.location.hash.substring(1) will return you "G145252"

Submit to external form with "action:javascript" using javascript

I have a form on one page (one.html) that has a javascript funtion as its submit action:
<form id="the_form" action="javascript:myfunc('input_text');" method="post">
<input type="text" id="input_text" name="input_text">
<input type="submit">
</form>
I have another page (two.html) with a button that when clicked I would like to submit the form on one.html, along with a value for input_text. Is this possible with ajax or any other way for that matter? If possible, I would also like to redirect to the page I submit the form too although this is optional.
this code should be on second form:
$(document).ready(function(){
var QueryString = function () {
// This function is anonymous, is executed immediately and
// the return value is assigned to QueryString!
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
// If first entry with this name
if (typeof query_string[pair[0]] === "undefined") {
query_string[pair[0]] = decodeURIComponent(pair[1]);
// If second entry with this name
} else if (typeof query_string[pair[0]] === "string") {
var arr = [ query_string[pair[0]],decodeURIComponent(pair[1]) ];
query_string[pair[0]] = arr;
// If third or later entry with this name
} else {
query_string[pair[0]].push(decodeURIComponent(pair[1]));
}
}
return query_string;
}();
if(QueryString.preview){
console.log(QueryString.preview);
}
});
this sample read query and parse.
So, first you can send your form as GET, like http://asd.com/?param1=a&param2=b
and then just use QueryString.param1 and QueryString.param2 in your another page.
Based on the comment under this post, I'm asuming you want to send it info from pageA to a php file that returns a resulting file:
download file using an ajax request
How to download file from server using jQuery AJAX and Spring MVC 3
Downloading file though AJAX POST
Based on the comments under your question, I'm assuming you want to post from pageA to new page (pageB) with javascript.
Quick answer: Not possible (in a userfriendly way).
More useful answer:
It requires a bit more work, but based on the info given, this might work:
Submit the form from pageA via either GET or POST to pageB
Create hidden fields (<input type="hidden"/>) and fill those with the corresponding GET or POST values. This might be easier with a serverside language like PHP, but isn't impossible in JS
Set a hidden input and name it like <input type="hidden" id="linkedSubmit" value="1" />
Create some javascript to see if $('#linkedSubmit').val()==1, if so continue to submit the form on pageB
This isn't the prettiest solution and on a slow connection the user will see page hopping. And because it is javascript it's clientside, thus a user can manually change the value to 1 and trick your page. This should not become a security problem.

How to pass a variable to a new page and insert it to a textbox?

I am trying to transfer a variable from one page using this code:
Edit
to the page login.html, and insert the variable(asdf in this example) to a textbox in the new page.
I have tried this code:
function NameFunction(name) {
document.getElementById("username").value = name;
}
It is not working. I think it doesn't work because thats another page.
If you want to pass parameters to another page you can put them using query string:
Edit
To get parameter on the login.html page you can use jQuery as it described here: Get escaped URL parameter
you can try using localStorage.
In you're onClick method, save the data you want to store in localStorage
localStorage.setItem(key,value);
When the new page loads, in the onLoad (ready function if using jquery) method get the data from localStorage and set it in the textbox
you can find more about localStorage in the following links
Storing Objects in HTML5 localStorage
http://www.w3schools.com/html/html5_webstorage.asp
and many more are available online

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.

Categories