POST one _fixed_ variable to popup window - javascript

Simple question. Yet managed to spend the whole day on it and still no result. Researched S.O., Google. Countless postings. Yet none of the questions are to the point I am struggling with. Any good soul that can help answer the following question.
All I want to do is POST a single predefined/fixed variable to a POPUP window via clicking on an image. Again, no arrays, no dynamics, nothing else involved. Just a predefined/fixed variable value. That is all. I do have a working solution that gets it done via a GET, but it does not suit my needs. Therefore am on a continuous and seemingly long hunt for a solution using POST method.
mainpage.php
<form method="post" action="popup_page.php" target="popup" onclick="window.open('popup_page.php','name','width=600,height=400')">
<button type="submit" name="flower" value="lotus">
<img src="https://upload.wikimedia.org/wikipedia/commons/e/ed/Sacred_lotus_Nelumbo_nucifera.jpg" width="200px" height="200px" alt="lotus"></button>
</form>
To validate if the variable "flower" (with the pre-defined answer of "lotus") comes through, I check it on popup_page.php by doing:
popup_page.php
<? echo $_POST['flower']; ?>
And of course no variable ever makes it to the popup page. Can anyone help what am I missing in my code? Or is my whole setup wrong altogether? Really appreciate anyone help in advance!!

POST the value to server
<form action='popup_page.php' method='POST'>
<input type='hidden' name='flower' value='lotus'></input>
<button type='submit' value='Submit'></button>
</form>
Get value on server and echo back popup
<?php
if (isset($_POST['flower'])) {
echo '<script>alert("'.$_POST['flower'].'")</script>';
}
?>

Thanks to Phiter, who directed me to the duplicate page. Final missing pieces were found here:
https://www.electrictoolbox.com/post-form-popup-window-javascript-jquery/
So the full answer below (successfully posting a predefined variable specifically to a Popup page, not just a regular new tab/page).
mainpage.php
<script type="text/javascript">
function target_popup(form) {
window.open('', 'formpopup', 'width=400,height=400,resizeable,scrollbars');
form.target = 'formpopup';
}
</script>
<form action="popup_page.php" method="post" onsubmit="target_popup(this)">
<button type="submit" name="flower" value="lotus"><img src="https://upload.wikimedia.org/wikipedia/commons/e/ed/Sacred_lotus_Nelumbo_nucifera.jpg" width="200px" height="200px" alt="lotus"></button>
</form>
popup_page.php
<? echo $_POST['flower']; ?>

Related

problems using google invisible recaptcha icon

I have a form in my codeigniter project using google's invisible recaptcha like so:
HTML
<html>
<head>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
function onSubmitInvisRecaptcha(token) {
document.getElementById("contact_us-form").submit();
}
</script>
</head>
<body>
<form id="contact_us-form" method="post" action="/info/contact_us">
<div>
<label>full name</label>
<input type="text" name="full_name" value="<?php echo $this->input->post('full_name'); ?>"/>
</div>
<div>
<button type="submit"
id="submit_btn"
class="btn my-other-styles g-recaptcha"
data-sitekey="<?php echo $sitekey; ?>"
data-callback="onSubmitInvisRecaptcha">
Submit
</button>
</div>
</form>
</body>
</html>
PHP
defined('BASEPATH') OR exit('No direct script access allowed');
class Info extends MY_Controller
{
function contact_us()
{
print_r($_POST);
}
}
from my code I, I have 2 problems: (I hope it's ok to ask about multiple problems in 1 post)
the recaptcha icon is nowhere to be found in the page. I've checked the sitekey I use in the form is the same as the one I find in www.google.com/recaptcha/admin.
in the contact_us function, the print_r($_POST); there is no g-recaptcha-response..
P.S.: the form is a part of another page that is shown using ajax so the form is wrapped by another <div>.
finally I've found the answer from this SO answer. The link shows a code for multiple recaptcha/form in one page, but it's simple enough to understand and modify for my needs.
basically, if I understand correctly, the reason my code failed was because of these points:
I need to use a separate <div> element to apply the recaptcha instead of the submit button.
google recaptcha will try to find the appointed element when the page loads, otherwise, I need to render and execute the grecaptcha manually using javascript if the element only appears or added to the page after some action.

javascript submit() command not sending my post data

From this earlier thread I thought I learned that form data could be sent by POST method using javascript submit() command. But I can't get it to work. This demo doesn't make obvious sense with respect to purpose but bear with me. I just wanted to test this specific command which doesn't seem to work for me. Can you please help me? Clicking the regular submit button sends the post data ok but activating the javascript via the link does not.
<html><body>
<?php
$self = $_SERVER['PHP_SELF'];
$posttext = file_get_contents('php://input');
echo "Received input: ".chr(34).$posttext.chr(34)."<br><br>";
echo "<form id='test' action='{$self}' method='post'>";
?>
Please fill in the fields with any text:<br><br>
foo: <input type="text" name="foofield"><br><br>
bar: <input type="text" name="barfield"><br><br>
<input type="submit" value="Submit button works"><br><br>
Submitting by JS not working – why?
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
$(document).ready(function(){
$("a#submitlink").click(function(){
alert("Yes, the link has been clicked. It is not that.");
$("form#test").submit();
});
});
});
</script>
</body></html>
You need to: event.preventDefault(); the default behaviour from the <a>. The problem is if you don't do that, the page reloads cause that is what the <a> tag does. So even you submit the data you also refresh the page where the submitted data gets lost.
$("a#submitlink").click(function(event){
event.preventDefault();
$("form#test").submit();
});
The other solution is to add # in the href of the <a> tag like:
Submitting by JS not working – why?
this will also prevent the <a> tag from doing a refresh.

console.log in php backend

I did also creating a different class. but still not working...
but if I place the '<script>console.log("message here");</script>' will work..
//index.html
assuming that this is a complete code.
<form action="post.php" method="post">
<input type="text" name="name" id="name"/>
<input type="submit" value="submit"/>
</form>
//post.php
<?PHP
if(isset($_POST['name'])){
echo "<script>console.log('".$_POST['name']."');</script>";
}
?>
my problem is , i cant use console.log in submitting a form. but if I did this in redirection It will work..
The Function under my class is ...
public function console($data) {
if(is_array($data) || is_object($data)) {
echo("<script>console.log('".json_encode($data)."');</script>");
} else {
echo("<script>console.log('".$data."');</script>");
}
}
It does not work within PHP because of the missing " around the String argument of console.log.
The output would've been
<script>console.log(name);</script>
instead of
<script>console.log("name");</script>
Solution
echo '<script>console.log("'.$_POST['name'].'");</script>';
If you are trying to debug or see the value that was posted from the front end to back end then you can simply use the chrome inspector.
Right click anywhere in browser and click inspect element.
click on network tab.
submit your form with desired values.
on the left click on the post.php.
Click on the headers on the right and scroll down to find Form Data.
You will have all your post variables listed there with respective values.
You seem to be trying to debug the $_POST variable, If thats the case, then Please note, that console.log() is a frontend debugging tool used in javascript, and has nothing to do with php.
Few good way of checking the content of variables in php.
1. print_r
This will output the content of a variable that can be an array, object or string in a nice human readable format.
echo '<pre>';
print_r($_POST);
echo '</pre>';
die();
2. var_dump
This will output the content of the variable with extra respective details like datatypes and length.
var_dump($_POST);
die();

Using a php function inside javascript code

I would like to run a php function from a javascript code, to be more specific I got a button that delete a record from the database. The function that does that named
delete_post($id)
Here is what I tried:
<input type="submit" name="delete" value="delete"
onClick="if(confirm('Are you sure?')) {<?php delete_post($row['id']);?>}">
When I click the button, there is no alert box. The funny thing is if I don't call a function inside the php code and I do something else such as echo the alert does pop out but the php code doesn't executed.
So, how can I do that? How can I run a php code inside my javascript onClick code.
You can't. PHP is supposed to be run before the page loads, thus giving it the name Pre-Hypertext Protocol. If you want to run PHP after a page loads via JavaScript, the best approach would be linking to a new page that runs the PHP, then returning the user back.
file1.php:
...
<input type="submit" name="delete" value="delete" onClick="if(confirm('Are you sure?')) document.location.href='file2.php';">
...
file2.php:
<!doctype html>
<html>
<head>
<?php
delete_post($row['id']);
?>
<meta http-equiv="refresh" content="0; url=file1.php" />
</head>
<body>
<p>You will be redirected soon; please wait. If you are not automatically redirected, click here.</p>
</body>
</html>
Assuming you would have multiple IDs, you can keep them all onto one redirect page:
if(confirm('Are you sure?')) document.location='file2.php?id=2'; // file1.php
delete_post($row[$_GET["id"]]); // file2.php
But do not put PHP code directly into the query string, or your site could be susceptible to PHP injection
You can't RUN php code in Javascript , but you can INVOKE it through JS/Ajax. For good practice split your php and JS , for example create a page that takes an ID and deletes it's row (i'm guessing your using REST) and invoke it through JS.
Cleaner , effective , and more secure
From your question, i would suggest you give jquery a try.
link to Jquery on your page's head section,
here is your js function
function deleteRow(id)
{
var url='path/to/page.php';
$("#loading_text").html('Performing Action Please Wait...');
$.POST(url,{ row_id: id } ,function(data){ $("#loading_text").html(data) });
}
This should do it for you.
Since its a delete, am using $.post Let me know if you find any more issues
here is a link to jQuery hosted by google CDN
//ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js
This is how your form should look like
<form>
<label for="Number"></label>
<input type="text" name="some_name" id="some_id" value="foo bar">
<input type="submit" name="delete" value="delete"
onClick="javascript: deleteRow(the_id_of_the_row);">
</form>
<br>
<div id="loader_text"></div>
now your php page that does the delete could look like this
<?php
$row_id = some_sanitisation_function($_POST['row_id']) //so as to clean and check user input
delete_post($row_id);
echo "Row deleted Successfully"; //success or failure message
?>
This should do it for you.

Displaying/passing PHP data inside javascript

After looking around on a Google without any success, i feel posting here may be a good idea as I have used this site to answer previous questions.
Anyways, I am currently working on an HTML5 canvas game using; PHP, MYSQL, Html5, and JavaScript.
I have MYSQL databases setup and an PHP page displaying player high-scores, and usernames.
My question is how would I go about displaying the high-scores inside the canvas once the game is over.
As well as saving the high score when the game ends. I've looked on W3SCHOOLS site about AJAX but I'm still unsure of what codes to use inside the JavaScript file.
These are my php/script codes. or at-least the ones that are relevant:
// Here's the savescore.php file
<?php
include 'connect.php';
$user_score = ($_POST['user_score']);
$user_name = ($_POST['user_name']);
if(mysql_query("INSERT INTO users VALUES('$user_name','$user_score')"))
echo "Score Successfully Saved";
else
echo "Score Saving Failed";
?>
// Here's some of the index.php file
<link rel="stylesheet" href="css.css">
</HEAD>
<body>
<div id="menu">
<a class="item" href="/index.php">Home</a>
<?php
include 'connect.php';
session_start();
if($_SESSION['signed_in'])
{
echo 'Hello ' . $_SESSION['user_name'] . '. Not you? Sign out';
include 'chat.php';
}
else
{
echo 'Sign in or create an account.';
}
?>
</div>
<BODY>
<canvas id="canvasGAMEOVER" width="800" height="599"> </canvas>
<script src="game.js"> </script>
// here's whats inside inside game.js... well the part I want to be able to save score
var score = 0;
function drawGAMEOVER() {
}
I have used google and looked at tutorials for AJAX, I found I have been able to connect to the server using AJAX only using:
<form action="savescore.php">
user_name: <input type="text" name="user_name"><br>
user_score: <input type="text" name="user_score"><br>
<input type="submit" value="Submit">
</form>
inside the index.php page, but I am not sure if its possible to grab the 'user_name' they logged in with (displayed on the index.php page) as well as this.score (displayed inside the javascript file.)
Could anyone tell me how this is possible... if not maybe a better way of doing this?
Any help/reply is much appreciated thanks in advance.
If you are using jquery you can use $.get to get all highscores.
http://api.jquery.com/jQuery.get/

Categories