PHP form open new window [duplicate] - javascript

This question already has answers here:
Submit form to popup window?
(3 answers)
Closed 2 years ago.
I have a PHP website that i am building where i am adding a basic product order form. I have created the form elements and once a user selects an option, i would like to open a new window (not tab), have that new window present as the focus and have variables delivered to the newly opened window through the GET method.
Currently when i submit the form, the target form opens per js, however the url variables are not passed to the new window. My code somehow concurrently also opens a new tab and transfers the GET url to the new tab and not the new window resulting in a new tab with the correct url and a new window without the correct url.
I appreciate there are many similar questions like this and i have spent hours trying to fix to no avail.
Thanks in advance for your time
Source form HTML:
<div class="prdContainer">
<form method="GET" target="_blank" action="members_order.php" onsubmit="openMemberOrder()" id='bcpot002' class="prdInput">
<div class="prodDiv">
<button type="submit" id="catOrder" class="catOrder"><img id="prdImgThumb" name="bcpot002" src="../../../Images/Product_Catalogue/bcpot002/bcpot002_thumb.jpg" ></button>
</div>
<div class="formDiv">
<label for="cat_ID" value="">Product Name:</label>
<input type="text" id="catID" name="cat_ID" value="bcpot002" readonly><br>
<label for="cat_Desc">Product Description:</label>
<input type="text" id="catDesc" name="cat_Desc" value="Red_Pot" readonly><br>
<label for="cat_val">Per unit price $:</label>
<input type="number" id="catVal" name="cat_val" value="" readonly>
<input type="hidden" id="divHeight" name="DivHeight" value="1036" readonly>
<input type="hidden" id="divWidth" name="DivWidth" value="1543" readonly>
</div>
</form>
</div>
Source form JS:
function openMemberOrder(url) {
newwindow = window.open('members_order.php', 'members_order', 'width=1600px,height=2000px,toolbar=no,scrollbars=no,resizable=no');
if (window.focus) {newwindow.focus()}
if (!newwindow.closed) {newwindow.focus()}
return false;
}
Receiving page HTML:
<?php require_once('xxxxx/initialize.php');
$catID = $_GET['cat_ID'];
$catDesc = $_GET['cat_Desc'];
$DivHeight = $_GET['DivHeight'];
$DivWidth = $_GET['DivWidth'];
echo "ID: " . $catID . "<b>";
echo "Desc: " . $catDesc . "<b>";
echo "Val: " . $catVal . "<b>";
echo "H: " . $DivHeight . "<b>";
echo "W: " . $DivWidth . "<b>";
?>
<body>
<header id="memOrderHead" ></header>
<div class="gridContainer" id="gridContainer" ></div>
<article class="article" >
<div class="orderDiv">
<h3>Order Item</h3>
<form class="orderInput">
<label for="cat_ID">Product name:</label>
<input type="text" id="catID" name="cat_ID" value="<?php echo $catID; ?>" readonly>
<label for="cat_Desc">Product description:</label>
<input type="text" id="catDesc" name="cat_Desc" value="<?php echo $catDesc; ?>" readonly>
<label for="cat_val">Per unit price $:</label>
<input type="number" id="catVal" name="cat_val" value="<?php echo $catVal; ?>" readonly>
<label for="cat_quant">Quantity ordered:</label>
<input type="number" id="orderQuant" name="cat_quant" min="0" placeholder="0">
<label for="cat_Total">Total Price $:</label>
<input type="number" id="orderTotal" name="cat_Total" min="0" placeholder="0" readonly>
<button type="button" class="orderButton" onclick="clearForm()">Clear</button>
<button type="button" class="orderButton" onclick="total()">Calculate Total</button>
<button type="button" class="orderButton" onclick="orderConfirm()" id="confirmReset">Submit</button>
</form>
</div>
</article>

You can pass data from the webpage to a new window using HTML 5 local storage. Some other alternatives are given in the post below
JavaScript - How do I open a new page and pass JSON data to it?

Related

jquery get specific input value from clicked button on form when multiple forms on page

I have multiple forms on the same page but need to get the values of the input element when a particular form is clicked i.e
However the jquery returns undefined query i
MY SCRIPT to get the values
jQuery(function($) {
$('.theform').submit(function(e) {
e.preventDefault();
var user = $(this).find(".product").val();
alert(user);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
$product='productOne';
<form class="theform">
<input id="" class='product' name="product" value="<?php echo $product; ??>" style="display: none">
<input type="hidden" class="userName" name="userName" value="john759">
<button class="action">Click</button>
</form>
$product='productTwo';
<form class="theform">
<input id="" class='product' name="product" value="<?php echo $product; ?>" style="display: none">
<input type="hidden" class="userName" name="userName" value="dDuck">
<button class="action">Click</button>
</form>
instead of this:
var user = $(this).find(".product").val();
use:
var user = $(this).parent().find(".product").val();
Use jquery closest function to get closset form value;
$(this).closest('form').find(".product").val();
Try to change type of button
<button class="action" type="submit">Click</button>

passing php data/variable to a modal

I have some data being created(generated from database) using a while loop. Each set of data carries some form of id and its corresponding button is added to it. Now, when I click a button, I'd like to pass the id(single php variable) of the data related to this button to a modal window(that has a form) that pops and also make it the value of an input field. Here's my code so far:
The data from database:
<?php while ($data = mysqli_fetch_assoc($data_set)) { ?>
<div class="w3-section w3-row w3-card-2">
<div class="w3-half">
<div class="apartment-image w3-card-4">
<header class="w3-container">
<h4><?php echo $data['data_name']; ?></h4>
</header>
<div class="w3-container">
<img src="<?php echo "images/".$data['Image1']; ?>" class="w3-image" alt="<?php echo $data['dataimgname']; ?>">
</div>
<footer class="w3-contanier w3-border-top">
<div class="w3-border-right">
<button class="w3-btn w3-btn-block" type="button" name="btnBook" id="modalOpener" onclick="document.getElementById('book').style.display='block';">
Book or Request Tour
</button>
</div>
The Modal:
<div id="book" class="w3-modal">
<div class="w3-modal-content">
<header class="w3-container">
<span onclick="document.getElementById('book').style.display='none'" class="w3-closebtn">
×
</span>
<h2>Book or Request Tour</h2>
</header>
<div class="w3-container">
<form class="w3-form" action="bookntour-handler.php" method="post">
<div class="w3-group">
<label class="w3-label" for="fullname">Full Name:</label>
<input class="w3-input" type="text" name="fullname" value="">
</div>
<label class="w3-label" for="email">E-mail:</label>
<input class="w3-input" type="email" name="email" value="">
<label class="w3-label" for="telephone">Telephone:</label>
<input class="w3-input" type="text" name="telephone" value="">
<label class="w3-label" for="dataname">Data Name:</label>
<input class="w3-input" type="text" name="dataname" value="">
<div class="w3-group">
<input class="w3-btn" type="submit" name="btnSubmit" value="Submit">
</div>
</form>
</div>
<footer>
</footer>
</div>
Like I said earlier, I want to pass the id associated with the button but from my code there is nothing that mentions about "id" so let's use.
<?php echo $data["data_name"]; ?>
When I open the modal window, I'd like this variable to be made as the value for input:
<label class="w3-label" for="dataname">Data Name:</label>
<input class="w3-input" type="text" name="dataname" value="">
I have looked at a couple of options so far but most of them seem unnecessary in my case or I simply don't understand them. Like this and this and this. This seems like a workable solution but it requires me to fetch the whole data again, from the database(using AJAX) which I do not want. I just want that one value.
I am using W3CSS for my layouts and creating the modal. A solution in jQuery/JavaScript or PHP(or both) will be appreciated. Thank you!
Update
So, I somehow managed to solve part of the problem. I added this function to my external JavaScript file:
function showModal() {
document.forms["bookntourForm"]["apartmentno"].value = document.getElementsByClassName("modalOpener")[0].getAttribute("value");
document.getElementById('book').style.display='block';
}
Then the code for the button that calls the above function looks like this:
<button class="w3-btn w3-btn-block modalOpener" type="button" name="btnBook" onclick="showModal()" value="<?php echo $data['data_name']; ?>">
Book or Request Tour
</button>
This brings up a new problem. Whenever I open the modal, the value for <input class="w3-input" type="text" name="dataname" value=""> on the modal is the same for all modals although they are different when each button is generated.
You can pass your id through ajax to the backend and retrieve necessary data regarding that ID by using a query,
Then set values to the necessary place inside the success method.
As you say, I don't think as a good suggestion to use data_name instead of id.
you can set your id in hidden field and use it. because "data_name" will not be good solution to retrieve data by unique field.
I don't know if I have done this in a proper manner, but it was as simple as this. I changed the value of onclick attribute of the button to:
<button class="w3-btn w3-btn-block modalOpener" type="button" name="btnBook" onclick="showModal('<?php echo $apartment["ApartmentNo"]; ?>')">
Book or Request Tour
</button>
The showModal() function in the external JS now looks like this:
var aptNo;
function showModal(aptNo) {
document.forms["bookntourForm"]["apartmentno"].value = aptNo;
document.getElementById('book').style.display='block';
}
It now works the way I wanted.

Append forms dynamically based on PHP-Array

I'm developing a module for my clan, where the user can automatically generate a BBCode formatted text.
As there are multiple groups in our team, i want them also seperated by <h1> Tags
For each Group from $groups there should be an individual amount of clones.
Here's my HTML + JS. Instead of the <h1> there sould be the name of the group from the PHP array $groups=array("Group 1", "Group 2",...)
http://jsfiddle.net/yq2jjn9z/1/ (form.js)
My index.php looks at the moment like this:
<?php
[...] //some DB stuff
<script>js/form.js</script>
<form name="groups" action="" method="post">
<?php foreach($groups as $key): ?>
<div class="field_wrapper">
<div>
<h2><?php echo($key)?></h2>
<input type="text" name="field_rank[]" placeholder="Rank" value=""/>
<input type="text" name="field_name[]" placeholder="Name" value=""/>
+
</div>
</div>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
?>
Sadly, it clones everything, not only within the selected group.
But the remove button works exactly as intended. Did I miss something?
Also, can I do this without PHP and HTML mixed?
Any ideas, how i can improve this?
Edit: http://techtreedev.de/muster.php this it what it's looks like at the moment (But with German words)
PS: Before downvoting, please consider writing what's wrong with my question. Thanks in advance
var wrapper = $('.field_wrapper');
...
$(wrapper).append(fieldHTML);
wrapper contains all elements with class "field_wrapper". If you add an element to it, it is added to all elements with this class.
You need to find the correct wrapper div for the + button that was clicked
$(addButton).click(function(){
$(this).parents(".field_wrapper").append(fieldHTML);
});
the question is a bit confusing, but a few things to note,
at the moment, you are using an array to parse the data the the server, but not grouping the arrays together at all, try the below code as a starting point.
<?php $groups = array("group 1","group 2"); ?>
<form name="groups" action="" method="post">
<?php foreach($groups as $key=>$text): ?>
<div class="field_wrapper">
<div>
<h2><?php echo($text)?></h2>
<div class="rowDiv_<?= $key ?>">
<input type="text" name="field_rank[<?= $key ?>][0][Rank]" placeholder="Rank" value=""/>
<input type="text" name="field_name[<?= $key ?>][0][Name]" placeholder="Name" value=""/>
+
</div>
</div>
</div>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
<script>
$("body").on("click",".add_button",function(){
myKey = $(this).attr("data-group-key");
rowCount = $(".rowDiv_"+myKey+":last a").attr("data-rowCount");
rowCount = parseInt(rowCount) + 1;
html = '<div class="rowDiv_'+myKey+'">';
html += '<input type="text" name="field_rank['+myKey+']['+rowCount+'][Rank]" placeholder="Rank" value=""/> ';
html += '<input type="text" name="field_name['+myKey+']['+rowCount+'][Name]" placeholder="Name" value=""/> ';
html += '-';
html += '</div>';
$(this).parent().parent().append(html);
})
$("body").on("click",".remove_button",function(){
$(this).parent().remove();
})
</script>
You need to make a unique wrap for each group like this
<script>js/form.js</script>
<form name="groups" action="" method="post">
<?php foreach($groups as $key): ?>
<div class="field_wrapper_<?php echo $key;?>">
<div>
<h2><?php echo($key)?></h2>
<input type="text" name="field_rank[]" placeholder="Rank" value=""/>
<input type="text" name="field_name[]" placeholder="Name" value=""/>
+
</div>
</div>
<?php endforeach; ?>
<input type="submit" name="submit" value="Submit"/>
</form>
And put this code in your JS file
<script>
function append_more(key)
{
var wrapper = $('.field_wrapper_'+key);
var fieldHTML = '<div><input type="text" name="field_rank[]" placeholder="Rang" value=""/> <input type="text" name="field_name[]" placeholder="Name" value=""/> -</div>';
$(wrapper).append(fieldHTML);
}
</script>

How to pass variable between php pages correctly where javascript is interactive?

I am new in this field, and I am currently working on small eCommerce website. Therefore, it would be very much appreciated if somebody can give me any advice or tip, or link the similar question as the answer to this question.
I know this post is pretty long one...however, I wanted to share my situation as precisely as possible so that people understand correctly what I am struggling with. That's why it became long post......
I have a flow and codes as you can see below.
And, where I am stack is that I don't know how I can make "Edit" button works correctly in revieworder.php page while other functions works properly together....
So, my question is how can I achieve following things simultaneously ?
passing variables from revieworder.php to options.php and deliveryinformation.php page when user press “Edit” button in revieworder.php page
after user jump to deliveryinformation.php page from revieworder.php page, javascript for country selection still works properly (by changing the country, javascript returns shippingfee, retrieved from DB, depending on the selected country in the same page(deliveryinformation.php).)
shippingfee, totalfee and country data are passed in following flow properly
revieworder.php → delieveryinformation.php → revieworder.php
revieworder.php → options.php → delieveryinformation.php → revieworder.php
Could you please teach me how I can archive that ?
Flow of my website is here;
1st page(options.php): User can choose the detail of product that they would like to order
2nd page(deliveryinformation.php): User is supposed to input information for delivery such as their name, address, and so on. Besides, by changing the country, javascript returns shippingfee, retrieved from DB, depending on the selected country in the same page(deliveryinformation.php).
3rd page(revieworder.php): User can review the detail of product and information for delivery. And user can press “Edit” button to go back to options.php page or deliveryinformation.php page to change their input
Codes;
options.php
<form name="selection" method="POST" action="deliveryinformation.php">
<div class="form-group">
<select id="dropdownforoption" name="options" class="form-control">
<option value="" select="selected">Option</option>
<option value="babysname">Baby's name</option>
</select>
</div>
<div>
<textarea id="request" name="request" placefolder="please type your request"></textarea>
</div>
<div class="form-group">
<select id="dropdownforsize" name="size" class="form-control">
<option value="" select="selected">Size</option>
<option value="27cm x 24cm">27cm x 24cm</option>
<option value="specialsize">special size</option>
</select>
</div>
<button id="delivery" type="submit" onclick="return onclickvalidation()">Proceed to develivery information</button>
</form>
deliveryinformation.php
<?php
$options = $_POST['options'];
$request = $_POST['request'];
$size = $_POST['size'];
>
<html>
<head>
<script type="text/javascript" src="toppage.js"></script>
</head>
...
<form name="delivery" method="POST" action="revieworder.php">
<input type="hidden" name="options" value="<?= $options; ?>"/>
<input type="hidden" name="request" value="<?= $request; ?>"/>
<input type="hidden" name="size" value="<?= $size; ?>"/>
<div class="row">
<div class="col-md-4">
<p>Name</p>
<p>Country</p>
</div>
<div class="col-md-4">
<input id="name" name="name" placeholder="please type your name">Name</input>
<div class="form-group">
<select id="countryselection" name="country" class="form-control">
<option value="" select="selected">Choose your country</option>
<option value="germany" select="selected">Germany</option>
<option value="other" select="selected">Other</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="col-md-6">
<p>shipping fee</p>
<p>total fee</p>
</div>
<div class="col-md-6">
<p class="shippingfee">EUR <input type="hidden" name="shippingfee" id="shippingfees2"><span id="shippingfees">xxx</span></input></p>
<p class="totalfee">EUR <input type="hidden" name="totalfee" id="totalfees2"><span id="totalfees">xxx</span></input></p>
</div>
</div>
</div>
..
</html>
toppage.js
$(document).ready(function(){
$('#countryselection').change(function(){
if($('#countryselection').val()!='Germany'){
var country = 'Other'
}else{var country = 'Germany'}
var priceforframe = document.delivery.framefees.value;
$.ajax({
type: 'GET',
url: '/shippingfee.php',
data: {'countryforshippingfee': country},
dataType: 'json',
success: function (data) {
document.getElementById("shippingfees2").value = data;
$('#shippingfees').html(data);
var total = data + 50;
document.getElementById("totalfees2").value = total;
$('#totalfees').html(total);
}
});
});
});
function submitForm(action){
document.getElementById('forminreviewpage').action = action;
document.getElementById('forminreviewpage').submit();
}
revieworder.php
<?php
$options = $_POST['options'];
$request = $_POST['request'];
$size = $_POST['size'];
$name = $_POST['name'];
$country = $_POST['country'];
$shippingfee = $_POST['shippingfee'];
$totalfee = $_POST['totalfee'];
?>
<html>
..
<form id="forminreviewpage" name="confirmation" method="POST">
<input type="hidden" name="options" value="<?= $options; ?>"/>
<input type="hidden" name="request" value="<?= $request; ?>"/>
<input type="hidden" name="size" value="<?= $size; ?>"/>
<input type="hidden" name="name" value="<?= $name; ?>"/>
<input type="hidden" name="country" value="<?= $country; ?>"/>
<input type="hidden" name="shippingfee" value="<?= $shippingfee; ?>"/>
<input type="hidden" name="totalfee" value="<?= $totalfee; ?>"/>
</form>
<div class="row">
<div class="col-md-4">
<div class="col-md-4">
<p><?= $options; ?></p>
<p><?= $request; ?></p>
<p><?= $size; ?></p>
</div>
<div class="col-md-4">
<button id="editbutton" onclick="submitForm('options.php')">Edit</button>
</div>
</div>
<div class="col-md-4">
<div class="col-md-4">
<p><?= $name; ?></p>
<p><?= $country; ?></p>
<p><?= $shippingfee; ?></p>
<p><?= $totalfee; ?></p>
</div>
<div class="col-md-4">
<button id="editbutton" onclick="submitForm('deliveryinformation.php')">Edit</button>
</div>
</div>
<div>
<button id="orderbutton" onclick="submitForm('ordered.php')">Order</button></br>
</div>
</div>
Thank you so much for your help and best regards,
Hiro
Using sessions will enable pages within your site to access a 'pool' of data - providing you set session variables yourself. This can easily be done in PHP - see this page on W3 for basic details, there are plenty of other sites on the net with easy walkthroughs of sessions once you've got the basic concept.
I'm not quite sure what you're asking in question two. Is it that you want the second page to automatically know the user's country? If so, this could be achieved by assigning a session variable on the previous page, or by using geo-location - see help here
As for question three, achieving proper flow is an architectural issue - you'll need to ensure that the pages visited by the user structured to only allow the through-flow that you want. Without spending hours working through your code, I should imagine this can again be achieved through assigning session variables when a page is successfully 'completed' and ready to move to the next page.
Sessions are powerful, and will allow you to control a lot of user data to ease their experience of your site throughout their period of use. Just be careful about what session data you record though - it should always be the minimum amount possible, and not containing any data that could compromise the user's personal details, or their account - i.e. don't store their username and password, just store an int of '1' or '0' if they pass authentication.
Hope that helps.

Javascript function call on wrong pages

Heyo,
Having a few issues with JavaScript function calls. Basically I am using php to create a table, and then on page init JavaScript is called to click a button which is labelled correct answer.
Now this all works fine, however when I return to the main page and try to do the same thing again it fails due to an "Uncaught TypeError: Cannot call method 'click' of null". This is happening because for some reason the script is being incorrectly called again and is then trying to click on something which isn't there, hence the 'null' error.
If I reload the page it works fine again as the JavaScript function is then not loaded until called.
The main issue seems to be that the JavaScript is remaining loaded (probably because jquerymobile uses ajax calls to load the page, and thus the data is never properly refreshed. Other than forcing the page to load without ajax, any suggestions?
JavaScript function:
function showCorrectAnswer(correctAnswer) {
$(document).on("pageinit", function() {
document.getElementById(correctAnswer).click()
})
}
PHP function:
function populatedQuestionUI ($topicID, $questionID, $actionSought) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM questions WHERE Topic = ? and QNo = ?");
$query->bindValue(1, $topicID);
$query->bindValue(2, $questionID);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
?>
<form name="questionUI" action="/MCExamSystemV2/Admin/manageQuestion.php" method="post">
<input type="hidden" name="TopicID" value="<?php echo $_POST['topic']; ?>"/>
<input type="hidden" name="QuestionNo" value="<?php echo $_POST['question']; ?>"/>
<label for="QText">Question Text</label>
<input type="text" name="QText" value="<?php echo $results[0]['QText']; ?>"/>
<label for="AnswerText-1">First Answer</label>
<input type="Text" name="AnswerText-1" value="<?php echo $results[0]['AText1']; ?>"/>
<label for="AnswerText-2">Second Answer</label>
<input type="Text" name="AnswerText-2" value="<?php echo $results[0]['AText2']; ?>"/>
<label for="AnswerText-3">Third Answer</label>
<input type="Text" name="AnswerText-3" value="<?php echo $results[0]['AText3']; ?>"/>
<label for="AnswerText-4">Fourth Answer</label>
<input type="Text" name="AnswerText-4" value="<?php echo $results[0]['AText4']; ?>"/>
<label for="CorrectAnswer">Correct answer:</label>
<div data-role="controlgroup" data-type="horizontal">
<input type="button" name="Answer-1" id="Answer-1" value=1 onClick="document.getElementById('CorrectAnswer').value='1'"/>
<input type="button" name="Answer-2" id="Answer-2" value=2 onClick="document.getElementById('CorrectAnswer').value='2'"/>
<input type="button" name="Answer-3" id="Answer-3" value=3 onClick="document.getElementById('CorrectAnswer').value='3'"/>
<input type="button" name="Answer-4" id="Answer-4" value=4 onClick="document.getElementById('CorrectAnswer').value='4'"/>
</div>
<input type="hidden" name="CorrectAnswer" id="CorrectAnswer" value='0'/>
<input type="submit" value="Confirm <?php echo $actionSought; ?>">
<input type="button" value="Cancel" onClick="location.href='/MCExamSystemV2/Admin'"/>
</form>
<script src="/MCExamSystemV2/includes/scripts.js"></script>>
<script>showCorrectAnswer('Answer-<?php echo $results[0]['CorrectA']; ?>')</script>
<?php
}
The main problem is because you're doing this:
document.getElementById(correctAnswer).click();
You're not checking if the element is on the page. Change it to:
var el = document.getElementById(correctAnswer);
if (el) {
el.click();
}

Categories

Resources