Pop up box with message from php file - javascript

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.

Related

Browser does not response to header redirect

please help... i am new to php. Thanks
php1 is to send a data ('1234') via method Post to php2. php2 is supposed to redirect using Header Location to php3 with a data ('invalid').
Developer Tools of Chrome indicate that everything went well (Post data sent and received. Get data sent and received).
Somehow, the browser does not response and stay at php1. I have tried Safari and Firefox. No response.
Would be really grateful if you could advise. Thanks
The 3 php files are:
php1
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
}
);
});
});
</script>
</head>
<body>
<div>
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>
php2
<?php
session_start();
ob_start();
error_reporting(E_ALL);
if (!empty($_POST)){
$Email = $_POST['email'];
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Location: php3.php?m=invalid');
exit();
}
} else {
header('Location: php1.php?m=nodata');
exit();
}
ob_end_flush();
?>
php3
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<?php echo $M; ?>
</div>
</body>
</html>
Here is a screenshot of chrome developer:
You should change the code for php1.php like this
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
$("#content").html(data); // <----- ADDED
}
);
});
});
</script>
</head>
<body>
<div id="content">
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>

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

PHP fails to get $_POST from JS

I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>

How to catch an Isset, or POST information, with a form in JQuery?

So I am trying to do something simple. There is a form, it does a self post and I want to get that post information from JQuery and put it into a div.
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
JQuery here to catch button click and do a "PHP_self":
<script>
$(document).ready(function(){
$(".gettingpostbutton").click(function(){
$.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>", function( data ) {
$("#add_post_information_html_here").append(data+" number from $_POST");
});/**/
});
});
</script>
</head>
<body>
<?php
// define variables and set to empty values
$number = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = test_input($_POST["number"]);
}
For SQL Injection:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Basic Form:
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
put a number: <input type="text" number="number">
<br><br>
<input type="button" name="action" class="btn btn-success gettingpostbutton" value="Add Number" />
</form>
Put info to page either through PHP but prefer to do it through JQuery:
<?php
echo "<h2>Your Input:</h2>";
echo $number;
?>
<div id="add_post_information_html_here"></div>
</body>
</html>
Result:

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;
}

Categories

Resources