javascript alert doesnt pop up on php echo - javascript

I want to show a popup alert when user uploaded a file
I have 1 php file that contains php script and html form, when I click the submit button the file was saved. But the echo function that contains javascript alert doesnt pop up. Can anyone help me?
here's my code
<?php
if(isset($_POST["btnSubmit"]))
{
if($_FILES["photo"]["name"])
{
$name = $_FILES["photo"]["name"];
$size = $_FILES["photo"]["size"];
$type = $_FILES["photo"]["type"];
if(!$_FILES["photo"]["error"])
{
move_uploaded_file($_FILES["photo"]["tmp_name"], "uploads/coba2.jpg");
$msg = "Upload Berhasil\nFile Name: $name\nSize: $size bytes\nType: $type";
}
else
{
$msg = "Upload ERROR: " . $_FILES["photo"]["error"];
}
}
else
{
$msg = "No File Uploaded";
}
if(isset($msg))
{
echo "<script type=\"text/javascript\">alert(".$msg.");</script>";
}
}?>
<!DOCTYPE html>
<html>
<head>
<title>Coba Upload</title>
</head>
<body>
<h3>Select File to Upload</h3><br>
<form method="POST" action="#" enctype="multipart/form-data">
<input type="file" name="photo" size="50"><br>
<input type="submit" name="btnSubmit" value="Unggah Foto">
</form>
</body>
</html>
I'm wondering why the echo that contains javascript alert doesnt pop up.
Thanks in advance.

You msg needs to be contained within quotes to alert correctly, so change:
{
echo "<script type=\"text/javascript\">alert(".$msg.");</script>";
}
To:
{
echo '<script type="text/javascript">alert("'.$msg.'");</script>';
}
Or, to continue using escaped quotes (urgh!):
{
echo "<script type=\"text/javascript\">alert(\"".$msg."\");</script>"
}

Related

Embedded JavaScript in PHP can not manipulate DOM in HTML

I have a PHP to verify the HTML form (post method). If the value doesn't match, the error message should be added at the HTML page. I test the embedded JS script in console, it works. But it doesn't work in PHP. How can I fix it? Thank you
Here is my code
<!DOCTYPE html>
<body>
<form action="http://localhost/submitTest.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<div id="submitField">
<input type="submit">
</div>
</form>
</body>
</html>
<?php
if ($_GET["name"] == 1 && $_GET["email"] == 2) {
header('Location: http://localhost/table.html');
} else {
$url = 'http://localhost/submitTest.html';
echo "<meta http-equiv='Refresh' content='0;URL=$url'>";
echo "
<script>
var messageP = document.createElement('span');
messageP.style.color = 'red';
var parent = document.getElementById('submitField');
parent.appendChild(messageP);
messageP.innerHTML = 'not match';
</script>";
}
?>
I want to do something like thiserror message

Preventing page refresh after form submission (e.preventDefault();) doesn't work

I want to stop page refresh after the user submits the form. The problem is that it doesn't seem to work.
PHP:
<?php
function displayimage() {
$con = mysqli_connect("localhost", "root", "", "cookbook");
$result = mysqli_query($con, "SELECT * FROM product");
while ($row = mysqli_fetch_array($result)) {
echo "<img src='uploads/".$row['image']."' class='imageaaa'>";
}
mysqli_close($con);
}
function addrecipe() {
$con = mysqli_connect("localhost", "root", "", "cookbook");
if (isset($_POST["Add"])) {
if (!empty($_POST["Name"])
){
$name = $_POST["Name"];
$type = $_POST["Type"];
$image = $_FILES['Image']['name'];
$date = date("d.m.Y, G:i");
$sql = "
INSERT INTO
product(`name`, `type`, `image`, `date`)
VALUES('$name', '$type', '$image', '$date');
// More Insert Into queries
";
$target = "uploads/".basename($image);
if (move_uploaded_file($_FILES['Image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
} else {
$msg = "Failed to upload image";
}
$var = mysqli_multi_query($con,$sql);
if($var){
echo "good";
} else {
echo "bad";
}
} else {
echo "Fill in the form";
}
}
mysqli_close($con);
}
?>
HTML:
<?php
addrecipe();
displayimage();
?>
<form method="POST" id="form" enctype='multipart/form-data'>
Name:
<input type="text" name="Name" value="<?php echo isset($_POST['Name'])?htmlspecialchars($_POST['Name'], ENT_QUOTES):'';?>"><br>
Type:
<select name="Type" required>
<option value="dishes" disabled selected hidden required>Wybierz typ</option>
<option value="dishes">Dania</option>
<option value="desserts">Desery</option>
<option value="snacks">Przekąski</option>
</select><be>
Image (jpg, png):
<input type="button" id="loadFileXml" value="loadXml" onclick="document.getElementById('upload_image').click();" />
<input type="file" style="display:none;" id="upload_image" name="Image">
<br><be>
<!-- More text inputs -->
<button name="Add" id="add">sdfsdfsd</button>
<script>
$("#add").submit(function(e) {
e.preventDefault();
});
</script>
</form>
I've tried a few things, but nothing seems to work. Everything works ok, data is sent to the database, but I can't get rid of this page reload. Did I do something wrong? If there is a better solution I'd love to know it. Also, I have this js code:
<script>
if (window.history.replaceState){
window.history.replaceState(null, null, window.location.href);
}
</script>
After my HTML tag, deleting it changes nothing. It disables the resubmit form pop-up before you refresh the page.
Is there any way I can disable page refresh after form submission?
The <script> tag should be outside of the <form> tag and should contain #form instead of #add
...
</form>
<script>
$("#form").submit(function(e) {
e.preventDefault();
});
</script>
The .submit() method is applied on the form element.
You can also achieve the same by simply returning false from the handler as mentioned in the spec.
...
</form>
<script>
$("#form").submit(() => false);
</script>

I want to load a get.php file in iframe on index.html once the Submit button is pressed

Ok so I'm facing this problem here
I've got 2 files :
index.html
get.php
On index.html I've got a form :
<form method="POST" action="get.php">
<input name="x" placeholder="first value" type="text">
<input name="y" placeholder="second value" type="text">
<input value="send" type="submit">
</form>
<br>
<iframe id="frame" class="right" width="100%" height="300" src="get.php"></iframe>
and here is the get.php file
<?php
if(isset($_POST['x'])==false)
{
echo "<h3>First variable is required...</h3>";
exit;
}
if(isset($_POST['y'])==false)
{
echo "<h3>Second variable is required...</h3>";
exit;
}
echo "<a style='padding:15px;background:#eee;color:#fff;border-radius:5px;' href='index.html'>Go back to the main page</a><br><br><br>";
$x=0;
$y=0;
$x=$_POST["x"];
$y=$_POST["y"];
echo "Values entered were $x and $y respectively<br><br><br>";
echo "Sum of $x+$y= ".($x+$y)."<br><br>";
echo "Multiplication of $x*$y= ".($x*$y)."<br><br>";
echo "Division of $x/$y= ".($x/$y)."<br><br>";
echo "Power of of $x<sup>$y</sup>= ".pow($x,$y)."<br><br>";
echo "power of $y<sup>$x</sup>= ".pow($y,$x)."<br><br>";
echo "Table of $x<br><br>";
for($i=1;$i<=10;$i++){
echo "$x * $i = ".($x*$i)."<br>";
}
echo "<br><br>Table of $y<br><br>";
for($i=1;$i<=10;$i++){
echo "$y * $i = ".($y*$i)."<br>";
}
?>
Now what is needed is that I put 2 values in both fields and once I click the submitted button it should show result of the get.php in the <iframe> placed on index.html rather then loading a new page of get.php
You could set iframe content using following snippet. The data are send using ajax and you need to prevent form submit behaviour. Try e.g:
$(function() { // document ready handler
$('form[action="get.php"]').on('submit', function(e) {
e.preventDefault();
$.post(this.action, $(this).serialize(), function(data) {
var iframeDoc = $('#frame')[0].contentDocument;
iframeDoc.open();
iframeDoc.write(data);
iframeDoc.close();
})
})
});

Photo Upload not working via Ajax call

I am trying to upload a photo using Ajax so that photo can be posted after clicking of submit button.
Flow:
user uploads image -> Ajax call is made to upload photo,
user clicks submit -> Post is shown to the user along with photo
Here is my php file for upload image:
<div class="box-footer">
<div id='preview' style="max-width:50px;max-height:60px;padding:5px;></div>
<div id="button_bar">
<!-- <div id="icons">
<div class="filebutton" title="Image Upload"> -->
<form id="imageform" method="post" enctype="multipart/form-data" action='WallPost1/ajax_image.php'>
<span><input type="file" name="photoimg" id="photoimg" onchange= PhotoUpload()></span>
</form>
</div>
<button type="submit" class="btn btn-primary" id="tweet_submit" onclick=TweetSubmit()>Submit</button>
</div>
</div>
Here is my JS code:
function PhotoUpload(){
alert ('got photo');
$("#preview").html('');
$("#preview").html('<small>Loading...</small>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
}
Here is my ajax_image.php code
<?php
include('includes/dbconnection.php');
include("session.php");
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif","JPG","JPEG","jpeg","PNG");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$command="Insert into uploads(image_name) values('$actual_image_name')";
if (!mysqli_query($con,$command))
{
die('Error: ' . mysqli_error($con));
}
else
{
$msg ="<br> 1 record added";
}
//echo "-----Images here----".$msg;
$query=mysqli_query($con,"Select upload_id,image_name from uploads where image_name='$actual_image_name'");
$result=mysqli_fetch_array($query);
$id=$result['upload_id'];
echo "<img src='BootStrapProject/WallPost1/uploads/".$actual_image_name."' class='preview' id='$id'>";
}
else
echo "failed";
}
else
echo "Image file size max 250k";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
Whenever i select a file using the input form, JS is called and i see 'loading...' message on UI but nothing happens after that.
Can somebody help me to understand why my ajax_image.php file is not being called.
Thanks in advance!
I was ale to solve the problem, i beleive the issue was that JQuery library was somehow overridden with older version which did not support ajaxForm.
Thanks for all your valuable inputs.

javascript location.replace doesn't work

I have this code:
<?php
include 'theme.php';
css();
if($_POST['wget-send'])
{
$formdir=$_POST['dir'];
$formlink=$_POST['link'];
$filelink = fopen('/root/wget/wget-download-link.txt',a);
$filedir = fopen('/root/wget/wget-dir.txt',w);
fwrite($filedir, $formdir);
/*
fwrite($filelink, $formlink."\n");
exec('touch /root/wget/wget-download-link.txt',$out);
exec('echo "'.$dir.'" > /root/wget/wget-dir.txt',$out);
*/
exec('echo "'.$formlink.'" > /root/wget/wget-download-link.txt');
exit();
}
echo "<form action=\"".$PHP_SELF."\" method=\"post\" id=\"WgetForm\">";
echo "Download directory:<br><input type=\"text\" name=\"dir\" size=\"15\" value=\"/mnt/usb/\"/><br>";
echo '<br>Download link:';
echo ("<textarea name=\"link\" rows=\"13\" cols=\"62\"></textarea><br><br>");
echo '<input type="submit" onclick="LinkAdded()" name="wget-send" value="Send" id="WgetID"/>';
echo "</form></div>";
echo <<<HTML
<script type="text/javascript">
function LinkAdded()
{
alert("Link has been sucessfully sent to wget, it'll be downloaded soon, check the wget log for the download progress");
location.replace("wget_log.php");
}
</script>
HTML;
foot();
echo '
</div>
</body>
</div>
</html>';
?>
the alert part works it gives me a pop up but after the pop up, it just gives me a blank page. How do I make the location.replace("wget_log.php"); work?
stackoverflow keeps telling me that I should add more details on my post but I think that's all the details I can give.
You need to prevent the default action of submitting the form by returning false from the click handler
echo '<input type="submit" onclick="LinkAdded(); return false;" name="wget-send" value="Send" id="WgetID"/>';

Categories