I'm currently using javascript to prevent link to be opened on multiple browser tabs every time user click on it. Let say my link destination is google, it will create a new tab if not exist but refresh if same destination exist. And it works good so far.
Here is the code.
Link
<div id="container">
Google
</div>
JavaScript
<script>
document.getElementById("container").onclick = function(test){
if (test.target.tagName === "A")
window.open(test.target.href, test.target.href);
return false;
}
</script>
My question is, How can I use same JavaScript on my form with similar effect? I mean if user submit my form. It will create a new tab when submitted if it not exist. But resubmit on same tab if the tab is exist. I tried to change JavaScript but can't make it work as normal link.
Here is my form
<form name='form1' action='/newform.php' method='post' target='_blank'>
<input type='hidden' name='test' value=''>
<input type='image' src='../data/images/myimages.gif' width='100px' height='30px' alt=''>
</form>
You might try something like this:
<script type='text/javascript'>
function formSubmit() {
window.open("about:blank","newWindow");
}
</script>
<form name='form1' action='/newform.php' method='post' onSubmit='formSubmit()' target='newWindow'>
<input type='hidden' name='test' value=''>
<input type='image' src='../data/images/myimages.gif' width='100px' height='30px' alt=''>
</form>
Basically, this will open new window when the form is submitted for the first time, and every other time form will submit to the already open window.
Keep in mind that window.open can be blocked by popup blockers and often is.
How about using a session variable?
Also use ID's for javascript.
<?php
//Check if session has not been started.
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
//If it has not been set, set no default.
if (!ISSET($_SESSION['hasSubmit'])
{
$_SESSION['hasSubmit'] = "no";
}
if ($_SESSION['hasSubmit'] == "no")
{
//Execute code for no
echo "
<form name='form1' id='firstSubmit' action='/newform.php' method='post' target='_blank'>
<input type='hidden' name='test' value=''>
<input type='image' src='../data/images/myimages.gif' width='100px' height='30px' alt=''>
</form>";
}
else if($_SESSION['hasSubmit'] == "yes")
{
//Execute code for yes
//Edit your form properties here to your likes.
echo "
<form name='form1' action='#' method='post' target='_newblank'>
<input type='hidden' name='test' value=''>
<input type='image' src='../data/images/myimages.gif' width='100px' height='30px' alt=''>
</form>";
}
?>
in newform.php set:
$_SESSION['hasSubmit'] = 'yes'
now the javascript:
$('firstSubmit').click(function(){
location.reload;
});
this should do the trick
Related
I have searched stackoverflow for the past hour and have found similar questions but attempting the solution has given me only errors - it may be as I am trying to load it on the same page.
I have tried saving the value to a cookie in JS then loading it in php, also attempted through ajax, etc.
From what I've read it can't just be done within as PHP is server side and Javascript is browser side which I get.
I currently have a .html page with a form that sends values through POST:
form.html
<form id="calc" form name="calculator" method="post" action="/calculate.php">
The solution is not with the form, I can't have hidden fields as I need to user input. I could have a radio box in the form yes and then get the value that way, but that's not my question. My question is how I can get the user's input and turn it into php on the page the form redirects to calculate.php:
calculate.php
<?php
if(isset($_POST['submit'])){
$x= $_POST['value'];
echo "your something:";
echo $x;
?>
Click button below for option one to do this, or click two for that, or three for something else...
<button id="one"> one </button>
<script>
$(document).ready(
function() {
$("#one").click(function() {
make php value 1
});
</script>
use php value from click
So the user will already have clicked submit. Then be redirected onto the .php page with their inputs, they can then choose button 1, 2 or 3 for example through javascript on calculate.php NOT the form.
My problem is I need to know on the same page - calculate.php, which button has been clicked in php. So that I can use their input and do different things with it depending on which button.
Is it possible to get a value to be set or create one from a button click on calculate.php itself with the javascript button producing a php value on the same page? Does it need to be loaded from an external.php page through ajax? Is there any other way?
PHP Option:
<?php
if(isset($_POST['submit'])){
$x= (isset($_POST['one'])) ? $_POST['one'] : '';
$y = (isset($_POST['two'])) ? $_POST['two'] : '';
$z = (isset($_POST['three'])) ? $_POST['three'] : '';
echo "your something:";
echo $x;
echo $y;
echo $z;
?>
<form name="calculator" method="post">
<INPUT TYPE="RADIO" NAME="one" VALUE="1"> ONE
<INPUT TYPE="RADIO" NAME="two" VALUE="2"> TWO
<INPUT TYPE="RADIO" NAME="three" VALUE="3"> THREE
<input type="submit" value="Submit">
</form>
JS mode:
if(isset($_POST)){
$value= (isset($_POST['value'])) ? $_POST['value'] : '';
$previous = (isset($_POST['previous'])) ? $_POST['previous'] : '';
//play with value and previous one
$x = //your algorithm;
echo "your something:";
echo $x;
?>
<form name="calculator" method="post">
<button type="button" value='1'>ONE</button>
<button type="button" value='2'>TWO</button>
<button type="button" value='3'>THREE</button>
<input name='value' type='hidden' value=''>
<input name='previous' type='hidden' value='<?= (isset($x)) ? $x : ''?>'>
</form>
<script>
$(document).ready(
function() {
$("button").click(function() {
$('input[name=value]').val($(this).val());
$('form').submit();
});
</script>
use php value from click
This code gets the password from below form I want it to fetch the username as well but the code is incapable to send it.
<?php
if(isset($_POST['password'])){
$usernamea = $_POST['username'];
$pas=$_POST['password'];
require('dbcoonect.php');
$sqla="UPDATE student SET password='$pas' WHERE username='$usernamea'";
if(mysqli_query($conn,$sqla)){
$out = '<h1>The form was submitted</h1>';
}
}
this code is the continuation of the above part
else{
//get the name through get method
$uska=$_GET['username'];
//make a form to post the data **`along with the username`**
//this is the code which post the data to the above if statement
$out = "
<form method='POST' id='form_id'>
<input type='hidden' name='username' value='$uska'>
<input type='password' id='con' name='conpass' >
<input type='password' id='lan' value='' name='password' onblur='fun()' >
</form>
<script type='text/javascript'>
function fun(){
document.forms['form_id'].submit();
}
</script>
";
}
echo $out;
?>
$out = "
<form method='POST' id='form_id'>
<input type='hidden' name='username' value='$uska'>
<input type='password' id='con' name='conpass' >
<input type='password' id='lan' value='' name='password' onblur='fun()' >
</form>
<script type='text/javascript'>
function fun(){
document.forms['form_id'].submit();
}
</script>
";
In second part of your code chunk, you start with PHP by typing else{ but after $out='', you go through html from <form method.... to </script>. You can't place a pure HTML code inside a PHP code. Either you have to echo the HTML part inside PHP code chunk or you have to close php chunk by ?>, start html and after html code chunk again start php code chunk by <?php. Again, after html, I can see a '';, perhaps that is the missing part/semicolon of $out=''.
Anyway, if it is typing mistake here, I assume you have placed form in HTML in your main code. If it is, then you have to echo the username like this:
<input type='hidden' name='username' value='<?php echo $uska; ?>'>
I have a problem here which I have solved with two different solutions. I would like to know:
Which solution is the most secure?
Which solution is more efficient, basically which one requires the least bandwith for user?
Which solution in the long run is easiest to maintain?
Is there a possibility that any of the solutions might get outdated in the near future? Example if they change how jQuery .hide() works or anything else, whatever.
Here are my solutions:
Solution 1 with jQuery and some php.
jQuery Code:
$(document).ready(function(){
$.get( "hide_forms_until_logged_in.php", function( data ) {
console.log(data.response);
if(data.response == "false") {
$("form").hide();
} else {
$("form").show();
}
}, "json");
});
HTML markup:
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="file" /> <br/>
<input type="submit" name="submit" value="Upload"/>
</form>
hide_forms_until_logged_in.php:
include 'session.php';
if (isset($_SESSION['login_user'])) {
echo json_encode(array("response"=>"true"));
} else {
echo json_encode(array("response"=>"false"));
}
Solution 2 with mostly php:
hide_forms_until_logged_in.php:
include 'session.php';
if (isset($_SESSION['login_user'])) {
echo "<form action='' method='POST'
enctype='multipart/form-data'>
<input type='file' name='file' /> <br/>
<input type='submit' name='submit' value='Ladda upp'/>
</form>";
} else {
echo "Logga in for att ladda upp filer";
}
And inside the page:
<?php include "hide_forms_until_logged_in.php" ?>
I know I could have made a function and call it inside the include there, for the sake just put the include there.
The form itself before posting anything to database has a check if the user is logged in or not.
I am trying to open multiple new windows(browser tabs) from php using javascript but don't know why it will open only one window always, and also don't found any solution of this. Here is my code.
<?php
openWindow("name1","id1");
openWindow("name2","id2");
function openWindow($name,$id)
{
echo "name = $name and Id = $id";
echo "
<form id=$name method='post' action='studentDetails.php' target='TheWindow'>
<input type='hidden' name='name' value=$name />
<input type='hidden' name='id' value=$id />
</form>
<script type='text/javascript'>
window.open('', 'TheWindow');
document.getElementById(<?php echo $name;?>).submit();
</script>
";
}
?>
Keep the following in mind:
Your 2 calls to the openWindow() function will create 2 identical forms along with the javascript blocks below it.
Since you have hardcoded the id of the form to be 'TheForm', it is illegal, since the element id should be unique in the DOM. Hence document.getElementById('TheForm') is ambiguous
You are better off using JavaScript to open URLs e.g. with window.open rather than the PHP function calls
Example:
Since the details of the requirements are unknown, it is difficult to suggest the correct solution, even if you get your initial code working. I would not recommend trying to open multiple new tabs programmatically. One reason is usability/user experience. Another reason is that there is no standard supported method to get this working on a variety of browsers and browser settings. There is css3 recommendation for opening in a new tab.
2 solutions you might want to consider:
a) Opening multiple pages as popups
b) Opening a single page with multiple records for each student
Depending on what you are after, you need to decide. For most cases, option be will be suitable.
Sample of option (a):
test.php
<html>
<head>
</head>
<body>
<form id='studentform' method='post' action='studentDetails.php' target="_blank">
<input type='hidden' name='name' id="name" value="" />
<input type='hidden' name='id' id="id" value="" />
</form>
<script type='text/javascript'>
function openWindows(){
window.open("http://localhost/test/studentDetails/studentDetails.php?name=john&id=1", "", "width=600, height=300");
window.open("http://localhost/test/studentDetails/studentDetails.php?name=mary&id=2", "", "width=600, height=300");
}
openWindows();
</script>
</body>
</html>
studentDetails.php
<?php
function getParam($name,$method){
if($method=="POST")
return isset($_POST[$name])?$_POST[$name]:"";
else
return isset($_GET[$name])?$_GET[$name]:"";
}
$name = getParam("name", "GET");
$id = getParam("id", "GET");
if($name && $id)
echo("name = $name and Id = $id");
else
echo("Invalid student info");
?>
And here is working code
<?php
openWindow("name1","Id1");
openWindow("name2","Id2");
function openWindow($name,$studentId)
{
echo "
<form id='$name' method='post' action='studentDetails.php' target='_blank'>
<input type='hidden' name='name' value=$name />
<input type='hidden' name='studentId' value=$studentId />
</form>
<script type='text/javascript'>
document.getElementById('$name').submit();
</script>
";
}
?>
if you specify another call of the window.open() method in your script, you should get it working:
<script type='text/javascript'>
window.open('', 'TheWindow');
window.open();
document.getElementById('TheForm').submit();
</script>
You can then give the parameters you want: window.open(url, name, specs, replace)
I hope it'll help.
I have table which displays the values of SQL table. In each row there is a dropdown which allows you to select which action you want to do. When you select the action and click '
go', it pops up a form which I want to be able to pass the $id variable from the table to the popup div form, then on to the next pop page. ID displays correctly in dropdown, but whenever when it shows the div, its showing the incorrect id (its displaying the first id of the table, rather than the id of the selected dropdown).
Heres the php
while($row = mysql_fetch_array($proposal_result)) {
$date=substr($row["date"], 0, 50);
$formatted_date=date('d/m/Y', strtotime($date));
$id=substr($row["idproposal"], 0, 50);
$businessname=substr($row["businessname"], 0, 50);
$status=substr($row["status"], 0, 50);
$staff=substr($row["staff"], 0, 50);
$file_access='<bucket-location>';
$file_name='proposal_'.$id.'_'.$businessname.'.pdf';
$file=$file_access.$file_name;
print "<tr><td>".$formatted_date."</<td>
<td>".$id."</td>
<td width='25px'><a href='".$file."'target='_blank'><img src='".$images."/attachment.png' alt='file'></a></td>
<td>".$businessname."</td><td>".$staff."</td>
<td>".$status."</td>
<td>
<div>
<select id='zb-admin-dropdown' name='zb-admin-dropdown' class='dropdowns' required>
<option value='0'>Select and action...*</option>
<option value='1'>Change Status for ID#".$id."</option>
<option value='2'>Delete Proposal</option>
</select>
<input type='submit' id='report-submit' value='Go' onclick='displayDiv()'></div>
</td></tr>";
}
Javascript
function displayDiv() {
e=document.getElementById("zb-admin-dropdown");
strUser=e.options[e.selectedIndex].value;
if (strUser=='1') {
document.getElementById('abc').style.display = "block";
}
if (strUser=='2') {
document.getElementById('def').style.display = "block";
}
}
popupdiv
print "<div id='abc'>
<div id='popup'>
<form name='changestatus' action='' method='post'>
<!--<img id='close' src='images/3.png'> CLOSE ICON-->
<h2>Change Status for ".$id."</h2>
<hr>
<textarea name='deletecomments' placeholder='Comments...'></textarea><br />
<a href='/delete?id=".$id."&businessname=".$businessname."'><input type='button' id='report-submit' value='Delete Proposal'></a><a href='/zerobooks-admin-dashboard'><input type='button' id='report-submit' value='Cancel'></a>
</form>
</div>
</div>";
print "<div id='def'>
<div id='popup'>
<form name='deletefeedback' action='' method='post'>
<!--<img id='close' src='images/3.png'> CLOSE ICON-->
<h2>Reason for deleting proposal <br />".$id."</h2>
<hr>
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Added by mistake<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>No longer required<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Incorrect Information Provided<br />
<input id='deletereason' type='radio' name='deletereason' class='radio' value='Added by mistake'>Reason 4<br />
<textarea name='deletecomments' placeholder='Comments...'></textarea><br />
<a href='/delete?id=".$id."&businessname=".$businessname."'><input type='button' id='report-submit' value='Delete Proposal'></a><a href='/zerobooks-admin-dashboard'><input type='button' id='report-submit' value='Cancel'></a>
</form>
</div>
</div>";
My aim is pretty much to pass the correct ID to the popupdiv. Any help would be appreciated. You can ignore the content of the popupdiv forms.
In your html, you call the function when a button is clicked. Pass the variable there in the function call. So:
<input type='submit' id='report-submit' value='Go' onclick='displayDiv(' + $id + ')'></div>
Then have the javascript function accept an input:
function displayDiv(divId) { ...
and use it in the javascript. But the thing is, php is server side, and javascript is client side. So to get the information to the server-side php, you need to make an http request.
I can't see where all the code is but you may be able to try a couple work-arounds with minimal refactoring. First, after the div element is displayed, you can have the javascript update the href tag with:
`document.getElementById(/*a_element's_id*/).href=''+divId`
Otherwise, I'm not a php expert, but I think perhaps if the php scripts are in the same scope, a global variable or perhaps a global static variable would be accessible to both php scripts?
Personally I'd go all javscript! :)
Best of luck