JavaScript href onclick not working with Perl - javascript

The below is my code. All my button functions are working perfectly, but if I click the link click the value of server should be remembered and the page should be reloaded again with the parameters view and subsys.
But the value for the server is empty when I getting reloaded.
my $server = $q->param('server') ;
my $unit = $q->param('unit') ;
my $bfile = __FILE__ ;
$bfile = `basename $bfile` ;
chomp $bfile ;
print "<form name=\"form1\" action =\"/cgi-bin/$bfile\" onsubmit=\"javascript:onsubmitform(doc_press)\">";
print "<input type=\"hidden\" name=\"server\" id=\"server\">";
print "<input type=\"hidden\" name=\"unit\" id=\"unit\">";
print "\n\n<input type=submit name=view value=\"View\" onClick=\"doc_press=this.value\">";
print "<input type=submit name=save value=\"Save\" onClick=\"doc_press=this.value\">";
print $var{$a}."<a href=\"/cgi-bin/$bfile?view=5&SUBSYS=$subsys\" onClick=javascript:click_page(\"$_\")>CLICK</a>\n" ;
print <<"END_OF_SCRIPT";
<script type="text/javascript">
function onsubmitform(doc_press) {
if (doc_press == "View"){
document.getElementById('unit').value="$unit";
}
else if (doc_press == "Save") {
END_OF_SCRIPT
var x = "$user=$val";
document.cookie=x;
document.getElementById('unit').value="$unit";
}
if (document.getElementById('HTTP_TYPE').value == "post") {
document.form1.method='post';
}
else if(document.getElementById('HTTP_TYPE').value == "get") {
document.form1.method='get';
}
}
function click_page(server){
document.getElementById('server').value=server;
}
</script>
END

When you click on a link (<a href="..."/>), the browser will make a new GET request for the given link, regardless of any forms you might have. This means that your form is NOT submitted; so any value in the form will be lost. For this reason, your onclick handler as posted here is useless.
Sometimes, if you’re really linking to the same page, modern browsers are smart enough to recognize that, and fill in the values you already had. This is only a commodity to users who get frustrated if their values are not kept, and so this doesn't work for hidden fields.
If you want clicking on the link to submit the form, you should either a) use a button, or b) change your onclick handler to submit the form and return false (so that the link isn’t followed):
function click_page(server){
document.getElementById('server').value=server;
document.forms[0].submit();
return false;
}
To make this work correctly, also change the onclick declaration:
CLICK

Related

PHP Multi page form getting a PHP variable into JavaScript on a different page

I have a working form with many variables and I need an option for one or two applicants the solution I am working on is to have the HTML fields hidden for the second applicant until a checkbox is ticked. I have the hide and show working on the first page and I've got the checkbox state set up as a variable in the PHP but I can't figure out how to get the PHP variable on the next pages to automatically trigger the second applicant fields. With past things I've tried looking in the dev tools on chrome its telling me the variable is returning empty however if I use the same variable on the same page in the HTML not the JavaScript it clearly shows ad "on".
The latest thing I'm trying is to convert the variable to JSON but still no luck.
<!DOCTYPE html>
<html>
<body>
<!-- p elements only for testing to see outputs -->
<p id="test"> <?php echo $twoapplicants ?></p>
<p id="test2"></p>
<!-- something to look at after endless page refreshs -->
<h2>Two Applicants Test Page</h2>
<!-- Hidden untill Toggleextrafields() is triggered fields need to be present on page but only showed if a variable from the previous page is "on" -->
<p class="extrafields" style="display:none">now you see me</p>
<script>
//$twoapplicants defined as on on another page in a PHP run multipage form
<?php
$twoapplicants = "on";
?>
//test for value set on previous page on page load
window.onload = pageload();
// trigger Toggleextrafields if variable is equal to "on"
function pageload(){
var a =<?php echo json_encode($twoapplicants); ?>;
var b = JSON.parse(a);
document.write (b);
document.getElementById('test2').innerHTML = b;
if(b === "on"){
Toggleextrafields();
}
else {extrafieldsoff();
}
}
// toggle extra fields and make them visible if they aren't already (this already works)
function Toggleextrafields() {
var x = document.getElementsByClassName("extrafields");
var i;
for (i = 0; i < x.length; i++){
if (x[i].style.display === "block") {
x[i].style.display = "none";
} else {
x[i].style.display= "block";
}
}
}
// hides extra fields if they aren't hidden already and the trigger isn't there
function extrafieldsoff() {
var x = document.getElementsByClassName("extrafields");
{
x.style.display = "none";
}
}
</script>
</body>
</html>

history.back(-1) not working in chrome

The scenario is, I have this old application in html and javascript. The first page/form has a dropdown list, a search text field, a find button and a list view. When I enter something on the search field and click find, it invokes a javascirpt function which selects the items on the list view and goes to another page/form created by the javascript function displaying the items of the list view matched with the search and a back button. when back button is clicked it was supposed to go back to first form and display the selected items on the list view. It does work properly in IE11 but it is not working in chrome. Chrome goes back to page previous to the page with search text field, find button and list view. Same happens if I click on the chorme browser back button. Chrome version is 61.
Find code below:
<input type="button" value="Find" onclick="fndtxt(this.form)">
function fndtxt(lgrp)
{ var txt=lgrp.srchtxt.value
var stextgrp=txt.split(' ');
var seltxt='You Have Selected:<br>Start Date:\n';
var j=0,k=0;
var selfield=''
seltxt += lgrp.sdate.value+' and End date:'+lgrp.edate.value
seltxt += '<br>and Following Data Fields<br>'
for(k=0;k<document.inform.slist.length;k++){
// document.inform.slist.options[k].selected=false;
}
for(k=0;k<document.inform.slist.length;k++){
oname=document.inform.slist.options[k].text
var sfnd=0;
for(stxt in stextgrp){
re = new RegExp(stextgrp[stxt],'i' )
if( oname.search(re)!= -1 ){
sfnd++
}
}
if(stextgrp.length==sfnd){
document.inform.slist.options[k].selected=true;
seltxt=seltxt+oname+'<br>\n'
selfield +=oname.split(':')[0]+','
}
}
document.write("<html><body text='#F8B008' >");
document.write("<head><link rel=stylesheet type='text/css' href='/wqsys/include/wqsys.css' ></head>");
document.write("<br><br><table align=center text='#F8B008'><tr><td id=cel>");
document.write(seltxt);
// document.write(selfield)
document.write("<form name='getinfo' action='nocall.pl' method=get >")
document.write("<input type=hidden name=fname value='"+selfield+"'>")
document.write("</td></tr><tr><td align=center><input type=button id=expmenu value='Back' onclick='history.back(-1);'>")
document.write("</td></tr></table></form></body></html>")
document.close()
}
I have tried window.history.go(-1); return false; with no success.
Any help or suggestion is appreciated.

JAVASCRIPT : Parameter Passed Is "Not Defined"

I'm creating a page that should read data from the database, display it as a table, and allow row-wise editing of the entries (using AJAX calls). Here are brief code snippets where the problem comes -
Javascript:
function editParam(bname, button) {
alert(bname); //this part doesn't happen, the error on console comes up before it
tr = button.parentNode;
while (tr && tr.nodeName.toUpperCase() !== "TR" && tr.nodeName.toUpperCase() !== "BODY") {
tr = tr.parentNode;
}
if (!tr || tr.nodeName.toUpperCase() !== "TR") {
return;
}
//some more code
}
PHP:
//get $row_users['Name']
while ($row_users = mysqli_fetch_array($results)) {
echo "<form method='POST'> //some <tr><td></td></tr>
<button onclick='editParam(".$row_users['Name'].", this)'>Edit</button>
</form>";
}
My data in the column Name is like "B1", "C2", etc.
Error onclick of button : B1 is not defined.
While running the code for other text or numbers, it worked fine. So I understand that my problem has to do with the datatype. However, I do not know how resolve the same.
Any suggestions would be much appreciated, thanks!
You need to add quotes around $row_users['Name'] since otherwise it is interpreted as a JS variable.
"<button onclick='editParam(\"" . $row_users['Name'] . "\", this)'>Edit</button>";

the function is not working

Alright, so I'm making a form validation everything is good in this JS, but now I'm facing a problem in the output, I am trying to display all the chosen data. So I used the action attribute and called the following function:
function funcs()
{
var favor = document.reg.favor[selectedIndex].value; //Select input
var fname = document.reg.fname.value; // text input
var lname = document.reg.lname.value; // text input
var email = document.reg.email.value; // text input
var pass = document.password.value; //text input
for(i=0;i<document.reg.rad.length;i++)
{
if(document.reg.rad[i].checked == true)
{
var rad = document.reg.rad[i].value; // Radio input
}
}
if(document.reg.bike.checked == true)
{
var bike = document.reg.bike.value; //CheckBox input
}
if(document.reg.car.checked == true)
{
var car = document.reg.car.value; //CheckBox input
}
document.write('<head><link type="text/css" rel="stylesheet" href="registrationtable.css"/></head><body>');
document.write("<div class = 'team'>");
document.write('<table>');
document.write("<tr><td> שם פרטי: </td><td>" + fname + "</td></tr> <tr><td> שם משפחה: " + lname + "</td></tr> <tr><td> אימייל: " + email + "</td></tr> <tr><td> סיסמא: " +pass +"</td></tr>");
document.write("<tr><td> השחקן האהוב עליך הוא " + favor +"</td></tr>");
document.write("</table>");
document.write("</div></body>");
}
Here's the form header:
<form name ="reg" action ="Javascript:funcs()" onsubmit ="return checkValidation()">
I'd like to clear that all the other javascript code is working perfectly, it must be something with this function.
When I'm pressing the send button, it won't do anything. Anyone knows whats the problem?
Thanks in advanced.
You can't shouldn't have a javascript function in your action attribute, it needs to be a URI. You can just call the funcs onsubmit if validation succeeded.
As Aquinas has shown that calling a javascript function in the action attribute is in fact possible, it is advised that you not put js code in the action attribute.
As I suspected. One problem is this line:
var favor = document.reg.favor[selectedIndex].value;
It should be
var favor = document.reg.favor[document.reg.favor.selectedIndex].value;
And your second problem is this:
var pass = document.password.value;
Should be:
var pass = document.reg.password.value;
See updated fiddle: http://jsfiddle.net/x7SBy/1/
Finally, you should use Firefox and download Firebug. It is invaluable for debugging JS problems like this.
Edit: There are other problems with your JS that I won't get into in detail, but in general you don't want to use document.reg.password, because of issues like this. You should really use document.getElementById. FYI.
It looks like you are trying to validate a form, then if valid call the funcs function to alter HTML on the page.
Maybe something like this:
<form name="reg" action="" onsubmit="checkValidation()">
Then a checkValidation function to pause form submission and if valid, call the funcs function:
function checkValidation(e) {
e.preventDefault();
if (checkValidation()) {
funcs();
}
}
But if this is the case, your funcs function should not be writing <head> tags and such. Maybe you could just add HTML to the body instead of trying to lay a new HTML document into the DOM with javascript.
Alternate solution:
function checkValidation() {
... do your validation
return true; // or false if invalid
}
Then use a real HTML page/resource in your action tag of the form.

Show bootstrap modal when url has some parameters

I'm new to develop web apps, I'm creating a mini project which has a simple signup, signing system, I don't want user to go to a different page to login, instead I have used a bootstrap modal which has a login form for which I have a button that on click also changes the url and also triggers the modal. Now I only want to show the modal, if url has parameter = ?action=login.
Firstly, I have tried document.getElementById('#myBtn').addEventListener('click', setQry) to my button which calls the function which on click changes the url parameter. The url parameter changes on click really fine, but the modal does not show up, please note that I have data-target and data-toggle attributes on my button for the modal to show. I have also tried this example. But its not working.
I just want to achieve that modal should show up, if url has the parameter
and on login success I want to hide the modal and also delete the url parameter.
Here's my HTML:
<button type='button' id='toggle-modal' data-toggle='modal' data-target='#login-modal'></button>
My JavaScript:
document.getElementById('#toggle-modal').addEventListener('click', setQry);
function setQry() {
const url = new URL('http://localhost/learning%20php/practice%20programs/login%20system/');
var qry_params = new URLSearchParams(url.search);
if (!qry_params.has('action', 'login')) {
qry_params.set('action', 'login');
window.location.search = qry_params;
}
if (window.location.search == qry_params) {
$('#login-modal').modal('show');
}
};
This code should work, your handler only fires on click, it doesn't have effect on page load, for this reason, it should be called to handle parameters on a page loading, sorry for my bad english
setQry();
function setQry() {
const url = new URL('http://localhost/learning%20php/practice%20programs/login%20system/');
var qry_params = new URLSearchParams(url.search);
if (!qry_params.has('action', 'login')) {
qry_params.set('action', 'login');
window.location.search = qry_params;
}
if (window.location.search == qry_params) {
$('#login-modal').modal('show');
}
};
Consider using PHP for that. You can get the GET Params in PHP and then change the content dependent on the get parameters.
<?php
if ($_GET['action'] == "login")
{
?>
<!-- Add content in html if action code is set to "login" -->
<?php
}
else
{
....
}
?>
The event is called twice when the button is clicked. so I have remove other attributes from button.
<button type='button' id='toggle-modal' ></button>
the # used in document.getElementById('#toggle-modal').addEventListener('click', setQry); is also creating the issue.
setting parameters in javascript qry_params.set('action', 'login'); is refreshing the page. so the popup gets close.
so the update code is given below hope it will resolve the issue
``'`
<button type='button' id='toggle-modal' ></button>
<script>
document.getElementById('toggle-modal').addEventListener('click', setQry);
function setQry() {
const url = new URL('http://localhost/learning%20php/practice%20programs/login%20system/?action=login');
var qry_params = new URLSearchParams(url.search);
if (window.location.search.replace("?", "") == qry_params) {
$('#login-modal').modal('show');
}
}; </script>

Categories