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

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

Related

Pop up box with message from php file

I have been working on a php file and would like to display whether a file has been uploaded or not
I have tried:
if (move_uploaded_file($file_tmp, $file)) {
echo "<script type='text/javascript'>alert('File sucessfully uploaded');</script>";
} else {
echo "<script type='text/javascript'>alert('Upload failed');</script>";
}
But it is not producing a pop up. However I can see it in the developer options under response. Any idea how I can solve this please?
You'll have to print alert(); inside a valid html. See this example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Upload</title>
</head>
<body>
<form name="form" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>">
Upload File: <input type="file" size="30" id="userfile" name="userfile">
<?php
$upload_dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/";
if (!is_dir($upload_dir)) {
#mkdir($upload_dir, 0755, true);
}
if (isset($_FILES['userfile'])) {
$temp_name = $_FILES['userfile']['tmp_name'];
$file_name = $_FILES['userfile']['name'];
$file_path = $upload_dir.$file_name;
}
if ((isset($_FILES['userfile'])) && (is_uploaded_file($_FILES['userfile']['tmp_name']))) {
if (#move_uploaded_file($temp_name, $file_path)) {
#chmod($file_path,0755);
echo "<script type='text/javascript'>alert('File sucessfully uploaded');</script>";
} else {
echo "<script type='text/javascript'>alert('Upload failed');</script>";
}
}
?>
<input type="submit" name="submit" value="Upload">
</form>
</body>
</html>
This example works fine for me. I hope this helps.

JQuery on("submit") not executing on the 1st click

I am using JQuery to test the size of an input after submitting a form:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page 1</title>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form method="post" action="essai.php">
<input type="text" name="mail" id="email" placeholder="mail"/><br />
<input type="submit" name="submit" value="Validate" />
</form>
<?php
if (isset($_POST['submit'])){
echo($_POST['mail']);
if(isset($_POST['mail'])){
$data=789;
}
}
?>
<script>
$(function(){
var data = <?php echo json_encode($data); ?>;
$("form").on("submit", function() {
if(data.toString().length < 4) {
alert(data);
return false;
}
});
});
</script>
</body>
</html>
The problem is that the alert (if I enter only 1 caracter for instance) does not pop up after the 1st submitting but only after the others.
Thank you
First, it's terribly insecure to embed PHP code within JavaScript. I can't think of one reason why you will want to use server-side code on the client-side. As an alternative, echo the javascript code from PHP, not the other way round.
Now your problem comes up because the first time the page is loaded, nothing is posted. You have some chunk of code which executes only after something gets posted. If your PHP script can display errors, you will see an undefined variable notice thrown the first time you load the code. You can work around that by declaring the variable before using it in the condition:
$data = 0; // Initialize variable here
if (isset($_POST['submit'])){
echo($_POST['mail']);
if(isset($_POST['mail'])){
$data=789;
}
}

JQuery POST data to php, direct to php, data not exist anymore in php

I passed along data via POST to php using JQuery, but when the page direct to the php file, the POST["createVal"] in php doesn't seem to exit after the call back. I showed this in demo below, notice that the $name is undefined when the callback result is clicked. Any idea how to fix this?
I'm trying to make a function that when the returned result was clicked, html page could redirect to the php page in which user input in html file could be printed out.
HTML file
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<input type="text" id="userinput">
<div id="result">
</div>
</body>
<script>
$("input").keyup(function(){
var input=$("input").val();
$.post("process.php",{createVal:input},function(data){
$("#result").html("<a href='process.php'>"+data+"</a>");
})
})
</script>
</html>
php file(process.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
echo $name;
}
?>
<?php
echo $name;
?>
change
$("#result").html("<a href='process.php'>"+data+"</a>");
to
$("#result").html("<a href='process.php?createVal="+data+"'>"+data+"</a>");
and
process.php
if(isset($_REQUEST["createVal"])){
$name=$_REQUEST["createVal"];
echo $name;
}
Use this Html Code:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
</head>
<body>
<input type="text" id="userinput">
<div id="result"> </div>
</body>
<script>
$("input").keyup(function(){
var input=$("input").val();
$.ajax({
type: "POST",
url: "http://localhost/stackoverflow/process.php",
data: {'createVal': input},
success: function(data){
$("#result").html("<a href='http://localhost/stackoverflow/process.php?createVal="+data+"'>"+data+"</a>");
}
});
});
</script>
</html>
PHP Code:
<?php
if(!empty($_REQUEST['createVal']) || !empty($_GET['createVal'])){
$name = $_REQUEST['createVal'];
echo $name;
}elseif(!empty($_GET['createVal'])){
$name = $_GET['createVal'];
echo $name;
}
return 1;
?>
I have run and checked this too.
localhost: if you are running this code on localhost
stackoverflow: is the folder name, if you have any folder in localhost for it so replace the name by this.

Trying to get value from textbox on index.php and use it on upload.php

We have a simple upload application, just trying to upload files to a location using FTP, but before uploading the files we want users to enter in a name of a folder and we would create this folder then put the files in it. We can successfully do this entering in static values, but we need to pull the text from the textbox 'foldername' on index.php and use the value of foldername on upload.php and are having no success with POST or GET. Any help would be great.
index.php
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Image upload</title>
<link href='http://fonts.googleapis.com/css?family=Boogaloo' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript" src="js/multiupload.js"></script>
<script type="text/javascript">
var config = {
support : "image/jpg,image/png,image/bmp,image/jpeg,image/gif,text/plain,text/anytext,application/csv", // Valid file formats
form: "demoFiler", // Form ID
dragArea: "dragAndDropFiles", // Upload Area ID
uploadUrl: "upload.php" // Server side upload url
}
$(document).ready(function(){
initMultiUploader(config);
});
</script>
<link href="css/style.css" type="text/css" rel="stylesheet" />
</head>
<body lang="en">
<center><h1 class="title">Multiple Drag and Drop File Upload</h1></center>
<div id="dragAndDropFiles" class="uploadArea">
<h1>Drop Images Here</h1>
</div>
<form method="POST" name="demoFiler" id="demoFiler" enctype="multipart/form-data" action="upload.php" >
Please name your folder: <input type="text" name="foldername" id="foldername"/></br>
<input type="file" name="multiUpload" id="multiUpload" multiple />
<input type="submit" name="submitHandler" id="submitHandler" value="Upload" class="buttonUpload" />
</form>
<div class="progressBar">
<div class="status"></div>
</div>
</body>
</html>
upload.php
<?php
$newdir = $_POST['foldername'];
$dir = '/1';
$connect = ftp_connect('server');
ftp_login($connect, 'user', 'password');
ftp_pasv($connect, true);
ftp_chdir($connect, $dir);
if($_SERVER['REQUEST_METHOD'] == "POST"){
if (#ftp_chdir($connect, $newdir)){
if (!empty($_FILES)) {
$tempFile = $_FILES['file']['tmp_name']; //3
$targetFile = $_FILES['file']['name']; //5
ftp_put($connect, $targetFile, $tempFile, FTP_ASCII);
}
}
else
{
ftp_mkdir($connect, $newdir);
ftp_chdir($connect, $newdir);
if (!empty($_FILES))
{
$tempFile = $_FILES['file']['tmp_name']; //3
$targetFile = $_FILES['file']['name']; //5
ftp_put($connect, $targetFile, $tempFile, FTP_ASCII);
}
}
}
ftp_close($connect);
echo($_POST['index']);
exit;
?>
The solution to this is in multiupload.js you need to add a line to the _uploader function as such :
data.append('index',ids');
data.append('foldername', $('#foldername').val());
The foldername line is the line you need to add, should be around line number 72 based on the github version.

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