This auto submit form doesn't work (sometimes!) - javascript

This is strange. This code works well when I open it directly --but if I run the web page that precedes it it doesn't. This code is a confirmation page that I want to jump in a checkout process -I have all my fields, and I don't need to ask the user again for confirmation, so I send her to checkout directly, sending all the values of the fields.
Again, when I arrive to this page from another form post it doesn't work --despite no other field or object sent to this page is called like the form--. Any ideas?
<?php include 'security.php' ?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Secure Acceptance - Payment Form</title>
<link rel="stylesheet" type="text/css" href="payment.css"/>
</head>
<body>
<?php
foreach($_REQUEST as $name => $value) {
$params[$name] = $value;
}
?>
<p>Redirecting to Secure Server...</p>
<form action="https://testsecureacceptance.cybersource.com/pay" method="post" id="formulario" name="formulario" />
<?php
foreach($params as $name => $value) {
echo "<input type=\"hidden\" id=\"" . $name . "\" name=\"" . $name . "\" value=\"" . $value . "\"/>\n";
}
echo "<input type=\"hidden\" id=\"signature\" name=\"signature\" value=\"" . sign($params) . "\"/>\n";
?>
<input type="submit" id="boton" name="boton" value="Ir a Checkout >>"/>
</form>
<script type = "text/javascript">
document.getElementById('formulario').submit();
</script>
</body>
</html>

You can use the JavaScript setTimeout method to delay the submit function while page loads or you can also use jQuery to wait until documents load and after that you can fire form submit function:
JS:
setTimeout(function(){
document.getElementById('formulario').submit();
},1000);
jQuery:
$(document).ready(function(){
$('#formulario').submit();
})

Related

How do I display a JavaScript alert using my PHP variables?

I am trying to bring up a javascript alert with my variables from php. My upload.php file so far is:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+')');
</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
I then have my html code which looks like (only the relevant part included):
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
The purpose of this script is to upload a picture to a server and then display the markdown code for the user to use that image. I am aiming to output the following if the file uploads correctly:
![Alternative Text](http://www.example.com/folder/photo.jpg)
I have tried the following:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+.$folder.'/'.$pic.')');</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
This results in a working webpage that uploads the file but does not show the js alert.
I have also tried the following:
<?php
if(isset($_POST['btn-upload']))
{
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder="uploaded_files/";
<script>var folder = "<?php echo $folder ?>";</script>
<script>var pic = "<?php echo $pic ?>";</script>
if(move_uploaded_file($pic_loc,$folder.$pic))
{
?><script>alert('File successfully uploaded.\n![File Upload]('+window.location.href+folder+'/'+pic+')');</script><?php
}
else
{
?><script>alert('Sorry, error while uploading file. Please try again');</script><?php
}
}
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Photo Uploader for use in markdown</title>
</head>
<body>
<h2>Photo Uploader & Markdown generator</h2>
<p>Click 'Choose file' to choose the file to be uploaded. The filename should appear. Then click 'upload'. <br>A popup should show you what to copy and paste.</p>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="pic" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>
This results in an http error 500
Any advice?
Many thanks,
You can create a function in php and call it where ever you need to call alert.
Function :
function alertMsg($str) {
print("<script>alert('$str')</script>");
}
And call in php as
//string
alertMsg("Success");
//php variable
$alertMsg = "Some alert message";
alertMsg($alertMsg);
//even you can concatenate both
alertMsg("This is an alert. ".$alertMsg);
Hope this helps.
Thanks.
In both attempts you're trying to mix PHP, HTML, and JavaScript as though they were all the same language. They are not. From the perspective of any one of them, code in another one of them is nothing but a string. They can't directly share variables and logic.
See how this line:
alert('File successfully uploaded.\n![File Upload]('+window.location.href+.$folder.'/'.$pic.')');
is attempting to use PHP code (both the variables and the syntax) directly in JavaScript. This is simply resulting in syntax errors in your JavaScript, which your browser's development console is pointing out to you. Instead, enclose the PHP code in <?php ?> tags and echo the result:
alert('File successfully uploaded.\n![File Upload]('+window.location.href+'<?php echo $folder.'/'.$pic ?>'+')');
The second attempt has the same problem, you're putting HTML/JavaScript directly in your PHP:
$folder="uploaded_files/";
<script>var folder = "<?php echo $folder ?>";</script>
This is resulting in PHP syntax errors, which your PHP logs are telling you about (as well as the 500 Internal Server Error you're getting).
PHP code needs to be in <?php ?> tags. Always. So this would be something like:
$folder="uploaded_files/";
?>
<script>var folder = "<?php echo $folder ?>";</script>
<script>var pic = "<?php echo $pic ?>";</script>
<?php
if(move_uploaded_file($pic_loc,$folder.$pic))
Note also that in HTML/JavaScript you don't need a <script> tag for every line of JavaScript code. You can have multiple lines of code in a single <script> element.
Using variable PHP in JS
<?php
if (isset($_POST['btn-upload'])) {
$pic = rand(1000,100000)."-".$_FILES['pic']['name'];
$pic_loc = $_FILES['pic']['tmp_name'];
$folder = "uploaded_files";
if (move_uploaded_file($pic_loc, $folder . '/' . $pic)) { ?>
<script>
alert("File successfully uploaded! " +
"\n" +
location.hostname +
"<?php echo '/' . $folder . '/' . $pic; ?>");
</script>
<?php
} else { ?>
<script>alert("Sorry, error while uploading file. Please try again");</script>
<?php
}
}
?>
location.hostname = $_SERVER['HTTP_HOST'] // localhost

CKEditor with Simple Image Browser plugin

I'm trying to use CKEditor with the Simple Image Browser plugin on wampserver, but I'm sorry, I really do not understand what to put in this line:
CKEDITOR.config.simpleImageBrowserURL
In the video he putted a php file, what to put in this file ?
(video: https://www.youtube.com/watch?v=WB5Y8XNQlgE)
I'd like to show the pictures that are in a variable directory 'images/$id/'
Thanks for your help. 
Page of the plugin:
http://ckeditor.com/addon/simple-image-browser
For simpleImageBrowserURL you need to provide a URL (e.g. a php script) which delivers the content as JSON.
You can start with a URL to a static .txt file with a content like this:
[{"url": "/images/1234/image1.png"},{"url": "/images/1234/image2.png"}]
Or a very simple php script:
<?php
header('Content-Type: application/json');
$id = '1234';
echo '[';
echo '{"url": "/images/' . $id . '/image1.png"},';
echo '{"url": "/images/' . $id . '/image2.png"}';
echo ']';
?>
UPDATE
With the above php script the simple image browser plugin does not load the images. This is caused by the jQuery $.get function the plugin uses. While jQuery already parses the JSON and passes objects to the function the plugin tries to parse the objects (here the images variable):
$.get(CKEDITOR.config.simpleImageBrowserURL, function(images) {
var json;
console.log(images);
json = $.parseJSON(images); // this will not work if the images parameter contains objects
It may be that this worked that way with older versions of jQuery...
So to make this work the php script has to deliver a text/plain mime type:
<?php
header('Content-Type: text/plain');
$id = '1234';
echo '[';
echo '{"url": "/images/' . $id . '/image1.png"},';
echo '{"url": "/images/' . $id . '/image2.png"}';
echo ']';
?>
<!doctype html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="scripts/ckeditor/ckeditor.js"></script>
<script src="scripts/ckeditor/plugins/simple-image-browser/plugin.js"></script>
<link href="styles/knacss.css" rel="stylesheet" type="text/css" />
<link href="styles/ui.css" rel="stylesheet" type="text/css" />
<link href="styles/fonts.css" rel="stylesheet" type="text/css" />
<link href="styles/styles.css" rel="stylesheet" type="text/css" />
<script>
$(function () {
CKEDITOR.config.extraPlugins = 'simple-image-browser';
CKEDITOR.config.simpleImageBrowserURL = 'images-liste.php';
CKEDITOR.replace('details');
});
</script>
</head>
<body>
<p><label for="description">Descripção:</label></p>
<p><textarea class="ckeditor" name="description" id="description"></textarea></p>
</body>
</html>
images-liste.php:
<?php header('Content-Type: application/json');
echo '[';
echo '{"url": "http://andrewprokos.com/wp-content/uploads/22346-brasilia-cathedral-night-2.jpg"},';
echo '{"url": "https://upload.wikimedia.org/wikipedia/commons/6/6c/Brazil.Brasilia.01.jpg"}';
echo ']';
?>
Errors:
ckeditor.js:327 Uncaught TypeError: Cannot read property 'getEditor' of undefined
ckeditor.js:610 Uncaught TypeError: Cannot read property 'title' of undefined

PHP echoing a table, appending it to a specific element in the DOM?

I have this code, which checks a database and returns some rows to my PHP code containing 4 values (id, playerA, playerB, turn, all INT).
I would like to use that array to build up a table and then append the table to a specific location in the DOM, but i dont know how i could do that.
I could do it another way (get the rows via JS Ajax and then use JS to build and append the table), which i know how, but i dont want to do that.
Is it possible to create a table and append it to a div using php/html/css ?
thanks
<?php
if (isset($_SESSION["userid"])){
$dbManager = DBManager::app();
$manager = new Manager($_SESSION["userid"]);
$gameList = $manager->getGames();
if ($gameList) {
Debug::log("got active games: ".sizeof($gameList);
}
else {
Debug::log("no games");
}
}
else {
Debug::log("no user id");
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script src="jquery-2.1.1.min.js"></script>
<script src='script.js'></script>
<script src='ajax.js'></script>
</head>
<body>
<input type="button" value="createGame" onclick="createGame()">
<divid="gameListDiv">
<div>LOGOUT</div>
</body>
</html>
EDIT
<?php
$table = "";
if ($gameList) {
foreach ($gameList as $game){
$table += "<tr>";
$table += "<td>";
$table += $game["name"];
$table += "</td>";
$table += "</tr>";
}
$table += "</table>";
}
?>
<body>
<input type="form" id="gameName" placeholder="Enter Game Name here"></input>
<input type="button" value="createGame" onclick="createGame()"></input>
<div>
<span>Active Games</span>
<?php echo $table; ?>
</div>
<div>LOGOUT</div>
</body>
You need to understand that the DOM does not yet exist - it is created by the browser, and the browser builds it based on the output of your combined PHP & HTML.
There are many ways to solve this problem without resorting to Ajax calls etc.
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'/>
<script src="jquery-2.1.1.min.js"></script>
<script src='script.js'></script>
<script src='ajax.js'></script>
</head>
<body>
<input type="button" value="createGame" onclick="createGame()">
<div id="gameListDiv">
<?php
if (isset($_SESSION["userid"])){
$dbManager = DBManager::app();
$manager = new Manager($_SESSION["userid"]);
$gameList = $manager->getGames();
if ($gameList) {
Debug::log("got active games: ".sizeof($gameList);
echo '<table style="width:100%">';
//assuming we can iterate over the $gameList value
foreach($gameList as &$game)
{
//here i assume that the result returned is an object with these properties - it might be the case that you need to do something like $game['playerA'] or $game->getData('playerA') - i am not sure what database lib you are using.
echo '<tr>
<td>'.$game->playerA.'</td>
<td>'.$game->playerB.'</td>
<td>'.$game->turn.'</td>
</tr>';
}
echo '</table>';
}
else {
Debug::log("no games");
}
}
else {
Debug::log("no user id");
}
?>
</div>
<div>LOGOUT</div>
</body>
</html>
In this example we are just running the PHP in-line with the HTML.
You could also do something like this if you wanted to keep all of your database logic at the top of the page and not in-line with the HTML:
<?php
/* Database logic here */
$variable = '<span>this variable could contain any old html that came from the database logic</span>';
?>
<html>
<head>
</head>
<body>
<php echo $variable; ?>
</body>
</html>
If you want to build the list before page load, you can just insert something like this where you want the table to go:
<table>
<?php foreach($gamelist as $game){ ?>
<tr>
<td><?=$game.id></td>
<td><?=$game.playerA></td>
<td><?=$game.playerB></td>
<td><?=$game.turn></td>
</tr>
<? } ?>
</table>
This will work because with PHP, the page hasn't been built and displayed to the user yet when you've got your data in $gamelist. All of your PHP code will be run before the page is actually sent to the user--which means you don't need to "update" the page later, you can just build it now.
If you're looking to collect or update your data after page load (it's unclear from your comments), this is impossible with only PHP as it's a server-side language. You would need to either reload the page or use AJAX for that.

PHP: send post to div on same page instead of another page

I have a page called login.php loaded into a div on another page (index.php). login.php includes a form with action pointing to login.php
Once I press the submit button, the page will open either in a new tab (if no target is specified), or as the whole page (if target is _top, overwriting index.php). what I want is to have index.php open while login.php is loaded into it's div, and the post data to go to login.php which is inside the div. is that even possible?
LOGIN.PHP
<!DOCTYPE html>
<html>
<head>
<link href="others.css" rel="stylesheet">
</head>
<body>
<?php
require_once('funcs.php');
if (!empty($_POST['user']) && !empty($_POST['pass']))
{
$username=cleanInput($_POST['user']);
$password=cleanInput($_POST['pass']);
if (login($username,$password)) { show_login_form("Invalid username or password!"); }
else
{
// login...
echo "okay boss!";
}
}
else { show_login_form(null); }
?>
</body>
</html>
FUNCS.PHP
<?php
function cleanInput($data)
{
$data=trim($data);
$data=htmlspecialchars($data,ENT_QUOTES, "UTF-8");
return $data;
}
function show_login_form($err)
{
echo '<h4>Enter username and password:</h4>';
if (isset($err)) { echo "<span style='color:red'>Error: $err</span><br>"; }
echo '
<br><form method="post" action="login.php">
username: <br><input name="user" type="text"><br>
password: <br><input name="pass" type="password"><br><br>
<input id="button" type="submit" value="Login"></form>
';
}
?>
INDEX.PHP
<!DOCTYPE html>
<html>
<head>
<title>Dating Site</title>
<link href="site.css" rel="stylesheet">
</head>
<body>
<?php require_once ("header.php"); ?>
<div id="mainframe" class="mainframe">
<?php require_once ("home.php"); ?>
</div>
<?php require_once ("footer.php"); ?>
</body>
</html>
and to load a page into the "mainframe" div,I use this code:
function loadsel(page)
{
if (page == 1)
$("div#mainframe").load('login.php');
}
What you need to do is use ajax to submit your form . Try this plugin and add the following code
http://jquery.malsup.com/form/#ajaxSubmit
download the plugin
function login(){
$('#login_form').ajaxSubmit({
target:'#output_login',
url:'./php/login.php'
});
return false;
}

using php code inside html page

I have problem I use several php codes inside html page and it gave me wrong result like this code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Form</title>
</head>
<body>
<form method="post">
<input type="text" name="int1" />
+
<input type="text" name="int2" />
=
<?php
if (isset($_POST)) {
$int1 = $_POST['int1'];
$int2 = $_POST['int2'];
echo $int1 + $int2;
}
?>
<br />
<input type="submit" value="Get Sum" />
</form>
</body>
</html>
the right result is calculate the numbers and display it here is no thing display
the other code
<html>
<head></head>
<body>
<ul>
<?php for($i=1;$i<=5;$i++){ ?>
<li>Menu Item <?php echo $i; ?></li>
<?php } ?>
</ul>
</body>
</html>
the right result to display like this
Menu Item 1
Menu Item 2
Menu Item 3
Menu Item 4
Menu Item 5
but when I display the page just display like this
Menu Item
that is meaning the php code didn't work in the page
I don't know what is the solution I want to use php code and php functions inside html page
because phonegap.com not accept php page
You cannot run PHP in PhoneGap. PhoneGap loads a local html file in a native webview. You need to have PHP installed to run PHP and this not possible from a mobile device, even if you use native code.
You need to use JavaScript for the typr of processing you are looking for.
PHP code is processed only in PHP files ( files with .php extentions). If your file is .html, try to rename it. In your case the PHP not processed and you see anly first li.
Also I recommend to you set error_reporting = E_ALL in php.ini config and restart server. And then you will see what happened with your script
and better use:
<html>
<head></head>
<body>
<ul>
<?php for ($i=1; $i<=5; $i++) : ?>
<li>Menu Item <?php echo $i; ?></li>
<?php endfor; ?>
</ul>
</body>
</html>
Your first code does not return anything because your isset is not set.
First code:
<?php
if (isset($_POST['int1']) && isset($_POST['int2'])) {
$int1 = $_POST['int1'];
$int2 = $_POST['int2'];
echo $int1 + $int2;
}
?>
Second code:
<html>
<head></head>
<body>
<ul>
<?php
for($a = 1; $a <=5; $a++){
echo "<li>Menu Item ".$a."</li>";
}
?>
</ul>
</body>
</html>
EDIT: After closer inspection it looks as though your code is not being parsed, rename your index.html to index.php
If you view the source you can see the PHP code.
It could be your first section failing..
$_POST is always set but it can be empty
Try this
<?php
if (isset($_POST['int1'], $_POST['int2'])) {
$int1 = $_POST['int1'];
$int2 = $_POST['int2'];
echo $int1 + $int2;
}
?>
isset() can take multiple arguments

Categories

Resources