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.
Related
I'm building a website, and I am incorporating PHP and Javascript into the website. What I am trying to do with this website is to use an interface that allows a user to "log in" in a sense, and then store the information entered through the use of cookies. I am trying to call an external js function using php, however for some reason, although the script tag is being added into the html document as desired, the function is not being called at all and can't figure out why or how to fix it. I have attached a portion of my code below. Thank you very much in advance.
My PHP code:
<?php
$fail="";
$success="";
if (isset($_POST['submit'])) {
echo "<script>console.log('Submitted');</script>";
$first=$_POST["first"];
$last=$_POST["last"];
$city=$_POST["city"];
if ($first!="test"||$last!="test"||$city!="test"){
$fail="This is an error message";
}
else{
echo "<script>console.log('This is working from html');</script>";
$success= "<script src='main.js'>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>
<script>
console.log("Hello World!");
</script>";
}
}
?>
Portion of my HTML:
<div id="container">
<?=$fail?>
<form action="" method="POST">
<p>Enter Family Name (as it appears on your invitation): </p>
<input class="entry" type="text" name="first" placeholder="FIRST NAME" required><br><br>
<input class="entry" type="text" name="last" placeholder="LAST NAME" required><br><br>
<input class="entry" type="text" name="city" placeholder="CITY (ONLY)" required><br><br>
<input name="submit" type="submit" style="margin:auto; display:block">
</form>
<?=$success?>
Javascript code:
function createCookie(name,value){
document.cookie=name+"="+value;
console.log("This is working");
console.log(document.cookie);
console.log("This is too");
}
function getCookie(name){
var split=document.cookie.split(";");
for (let i=0;i<split.length;i++){
if (split[i].indexOf(name)===0){
return split[i].substring(name.length+1);
}
}
}
This portion of code is creating a conflict in behavior in the web browser (you have both src and code in the same script tag):
$success= "<script src='main.js'>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>";
You should change this, by simply making a second script tag (splitting them up):
$success= "<script src='main.js'></script>
<script>
console.log('success variable is working');
createCookie('first',$first);
createCookie('last',$last);
createCookie('city',$city);
</script>";
That way the src does not negate any code content of the script tag.
Second, you should also quote the strings being added from php in those js function calls. Like so:
$success= "<script src='main.js'></script>
<script>
console.log('success variable is working');
createCookie('first',". json_encode($first) .");
createCookie('last',". json_encode($last) .");
createCookie('city',". json_encode($city) .");
</script>";
The use of json_encode here is to ensure the values are javascript safe to pass through and not break the script.
I want to get an input from a user in PHP in a loop and store it in an array. But loop print all iterations in one go. And I want the loop to wait for input in one iteration and get value and then execute next iteration like in C++ and Java. it this possible? if yes then how?
If possible in javascript, then that would also be an acceptable solution.
my code is:
<?php
print "<form method=Post action=try.php>";
for ($i=1; $i<=10; $i++){
echo "<form action='try1.php' method='post'>"."<input type='text'
name='link'>";
echo "<input type='submit' name='link' value='done'>";
}
?>
I'm not really sure that I understand what you are asking for. But if you want to create an array of user inputs you could use Javascript/jQuery. Simply append the array with the input value and clear the field. If you want to process the data with PHP, just send it to the script with AJAX. This might be a good start:
var content = [];
$( '#myForm' ).submit(function( e ) {
e.preventDefault();
content.push( $( '.link' ).val() );
$( '.link' ).val( '' );
$( '#console' ).html( content.toString() );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" method="post">
<div>
<input type="text" class="link" name="link">
<button type="submit" class="done">Click!</button>
</div>
</form>
<div id="console"></div>
The reason this does not work is that PHP in the context of a webserver is request based. When you run your script in the browser, itss executed on the websever from start to finish and then the result (e.g HTML page) is returned to your client.
If you want a more interactive approach you need to implement that in Javascript, which is running on your client and can manipulate the HTML page based on user input. (you can combine Javascript and PHP)
If you want to learn how to do all that the W3Schools are a great place to start.
It is possible, but you will have to use php session to keep track of form click, and store the variable as well
<?php
if(isset($_SESSION['count'])){
$count = $_SESSION['count'];
}else{
$count = $_SESSION['count'] = 10;
}
if ($count){
echo "<form action='try1.php' method='post'>"."<input type='text'
name='link'>";
echo "<input type='submit' name='link' value='done'>";
$_SESSION['count']--;
}
?>
You also need to use session to keep track of the form response.
This code should help you.
<html>
<body>
<form action='try1.php' method='post'>
<div class="txt-area">
<input type='text' name='link[]'>
</div>
<div>
<button type="button" class="btn-add">+ Add</button>
</div>
<input type='submit' name='link' value='done'>
</form>
</body>
</html>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script type="text/javascript">
var x = new Array();
$('.btn-add').on('click', function(){
$(".txt-area").append("<input type='text' name='link[]' style='display:block'>");
});
</script>
1) Why does the URL show "&submit=Submit" at the end? What should be done to get only the two variables name and age?
2) Does isset function work well with GET method as well? Is there another function or way to handle this?
Result screenshot
<html>
<head>
<title>My first PHP page</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="get">
Name: <input type="text" name="name"/>
Age: <input type="text" name="age"/>
<input type="submit" name="submit"/>
</form>
</body>
</html>
<?php
if ( isset($_GET['submit']) ) { //was the form submitted?
echo "Welcome ". $_GET["name"] . "<br>";
echo "You are ". $_GET["age"] . "years old<br>";
}
?>
The URL is showing variable -> value key pairs. The name= attribute supplies the var name, the element value provides the value. Remove the name= from the submit button. Problem solved.
Yes, isset works with both GET and POST methods.
everybody.
I have the following situation:
I have:
http://example.com/ and http://example.com/new
In example.com, I have some forms that I load in example.com/new domain with fancybox iframe.
My form, basically shows some fields for the user to enter his pessoal data, like name, phone and etc... After he submit that, I show some user agreement terms that comes from database and a checkbox for the user to say that he agree with the terms.
After he check and submit, I want to alert some sucess message and the fancybox modal/iframe to close and thats it.
In the form page, i've loaded jquery, and bootstrap. So, when the user agree, I print:
<?php
echo "
<script>
alert('Some success message!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
?>
I have three forms, in one, works, in the other two, i get:
Error: Permission denied to access property '$'
The only difference between the form that works and the other two, is that in the form that works, i don't have the agreement terms coming from database, only the checkbox.
I could put my entire code here, but would be a giant question. But if you guys need, I can update.
Sorry for my english and forgive-me if I was not clear.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<?php
/* Connect with DB */
require_once('require/conectar.php');
if(!empty($_POST))
foreach($_POST as $k => $v)
$$k = $v;
?>
<script type="text/javascript" src="http://example.com/new/assets/js/jquery.js"></script>
</head>
<body>
<?php if(!isset($agree) and !isset($next)): ?>
<h1>The form</h1>
<form method="post" action="">
<label>Your name:</label>
<input type="text" name="name">
<br>
<label>Your email:</label>
<input type="text" name="email">
<br>
<input type="submit" name="next">
</form>
<?php
else:
$error = (!isset($name)) ? true : false;
$error = (!isset($name)) ? true : false;
if($error)
{
echo '<script>You must fill all fields before submit.</script>';
exit;
}
$qrr = mysql_query("SELECT * FROM `terms`");
$terms = mysql_fetch_object($qrr);
?>
<h1>Terms:</h1>
<?php echo $terms->content; ?>
<form method="post" action="">
<input type="hidden" value="<?php echo $name; ?>" name="name">
<input type="hidden" value="<?php echo $email; ?>" name="email">
<input type="checkbox" value="1" name="accept"> I agree.
<input type="submit" name="agree">
</form>
<?php
endif;
if(isset($agree))
{
/*
Here i mail me the user data.
*/
echo "
<script>
alert('Soliciação Realizada com sucesso!');
$(document).ready(function(){
parent.$.fancybox.close();
});
</script>
";
}else
{
echo "<script>alert('You need to agree with the terms to proceed.');</script>";
}
?>
</body>
</html>
This is a browser security thing. While there's a few ways around it, the best one is probably to use the postMessage API.
On your example.com parent page, add some code like this:
function handleMessageFromiFrame(event) {
alert('Some success message: ' + event.data);
//$.fancybox.close();
}
window.addEventListener("message", handleMessageFromiFrame, false);
And, then on your child example.com/new iframe, add code like this:
var parentOrigin = "*"; // set to http://example.com/ or whatever for added security.
function sendMessageToParent(){
parent.postMessage("button clicked", parentOrigin);
}
$('#submit-btn').click(sendMessageToParent);
Here's an example of it in action:
Parent example.com page: http://jsbin.com/hiqoyevici/1/edit?html,js,output
Child example.com/new iframe: http://jsbin.com/goferunudo/1/edit?html,js,output
When you click the button in the child page, it uses postMessage to notify the parent. Then the parent listens for the message and does whatever action you want.
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