Photo Upload not working via Ajax call - javascript

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.

Related

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>

PHP MYSQL Upload Image With other data

This is what it looks like.
But when i press the submit button it wont upload the image.
Is it possible to have 2 functions in one SUBMIT?
It saves the other data in my database but the image is not uploaded nor it is in my database.
<?php
$con=mysqli_connect("localhost","root","","presyohan");
// Check connection
if (mysqli_connect_error())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
$prod_name = $_POST['prod_name'];
$prod_price = $_POST['prod_price'];
$prod_category = $_POST['prod_category'];
$sql="INSERT INTO products (prod_name, prod_price, prod_category)
VALUES('$prod_name','$prod_price','$prod_category')";
$result=mysql_query($sql);
if ($con->query($sql) === TRUE) {
session_start();
$_SESSION['users'] = $rows['prod_name'];
$_SESSION['id'] = $rows['user_id'];
header("Location: store-index.php");
die();
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
//imageupload
$filename = $_FILES['uploadfile']['name'];
$filetmpname = $_FILES['uploadfile']['tmp_name'];
$folder = 'images/products/';
move_uploaded_file($filetmpname, $folder.$filename);
$sqls = "INSERT INTO 'products' ('prod_img') VALUES ('$filename')";
$qry = mysqli_query($con, $sqls);
if ($qry) {
echo 'header("Location: store-index.php")';
}
$con->close();
}
?>
<form class="form" action="add-prod.php" method="post" enctype="multipart/form-data">
<div class="upload-btn-wrapper">
<label for="file-upload" class="custom-file-upload">
Product Image <i class="fas fa-cloud-upload-alt"></i>
</label>
<input id="file-upload" type="file" name="uploadfile" />
</div>
<div class="form__group">
<button class="btn" type="submit" name="submit">ADD</button>
</div>
</form>
enter image description here

javascript alert doesnt pop up on php echo

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

I'm trying to make an image uploading website using php, mysql and ajax..but I keep getting no output at all

I'm trying to make an image uploading website where users can post their images and other logged-in users can reply to them. I'm trying to make this using php, mysql and ajax. I'm actually following a tutorial and I have modified their code to suit my website. But everytime I click submit, the page seems to refresh because I'm redirected to the top of my website and the new comment is not posted on top of the old comments as I want it to and also there is no inserting of the information of the new comment in the commentstable in my database.
Here is the code:
This is the php file in which I display the image and print out the comments and set a textarea to input new comments by the user. In this file, I import a javascript file which contains a function called postcomment() that performs the ajax part. The comments table has a column called commentForImageId which stores the id of the image for which a particular comment is posted.
<?php
//image is displayed above this set of code with all the required data
date_default_timezone_set('Asia/Kolkata');//to set my country's timezone
?>
<form method="post" action="" onsubmit="return postcomment();">
<input type="hidden" id="imageId" value="<?php echo $imageId; ?>">
<input type="hidden" id="datetime" value="<?php echo date('Y-m-d H:i:s'); ?>">
<textarea id="comment" placeholder="Write comment"></textarea><br>
<button type="submit">post comment</button>
</form>
<div id="allcomments">
<?php
$sql= "SELECT * FROM commentstable ORDER BY datetime DESC";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
$commentForImageId=$row['commentForImageId'];
if($commentForImageId==$imageId){
$username=$row['commentByUserName'];
$comment=$row['comment'];
$datetime=$row['datetime'];
?>
<hr>
<div class="comment_div">
<p class="comment"><?php echo $comment; ?></p>
<p class="username">Posted By:<?php echo $username; ?></p>
<p class="datetime"><?php echo $datetime; ?></p>
</div>
<hr>
<?php
}}?>
</div>
Here is the function that performs the ajax part. "commentsystem.php" performs the part of storing the data in the databse:
function postcomment(){
var comment = document.getElementById("comment").value;
var datetime = document.getElementById("datetime").value;
if(comment && datetime)
{
$.ajax
({
type: 'POST',
url: 'commentsystem.php',
data:
{
comment:comment,
datetime:datetime
},
success: function (response)
{
document.getElementById("allcomments").innerHTML=response+document.getElementById("allcomments").innerHTML;
document.getElementById("comment").value="";
}
});
}
return false;
}
Here is commentsystem.php. Here, "dbh.php" is the database handling file where the connection to the database is established:
<?php
session_start();
include 'dbh.php';
if(isset($_SESSION['id'])){//if user has logged in
if(isset($_POST['comment']) && isset($_POST['datetime']) && isset($_POST['imageId']))
{
//if user has submitted the comment
$comment=$_POST['comment'];
$datetime=$_POST['datetime'];
$imageId=$_POST['imageId'];
$username=$_SESSION['username'];
$userId=$_SESSION['id'];
$sql="INSERT INTO commentstable (commentForImageId, commentByUserId, commentByUserName, likes, numberOfReplies, comment, datetime) VALUES ('$imageId', '$userId', '$username', 0, 0, '$comment', '$datetime')";
$result=mysqli_query($conn,$sql);
?>
<div class="comment_div">
<p class="comment"><?php echo $comment; ?></p>
<p class="username">Posted By:<?php echo $username; ?></p>
<p class="datetime"><?php echo $datetime; ?></p>
</div>
<?php
exit;
}
}
else{
header("LOCATION: signup.php");
}
?>
Thank you very much for your help! I'm very new to this and am completely confused about what is going wrong!
Thanks in advance once again!
I would give the button a class for example postcomment and the call this $('.postcomment').click( function(){ $.ajax.... return false;})
Also make sure you set the $imageId as in commentsystem.php you require it to be set

How to add button instead of error status and success message in php?

I have been created subscribe button using php,
Html:
<div id="newsletterform">
<h2>Get Email Update</h2>
<form action="send.php" method="post" id="newsletter" name="newsletter">
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
<input type="submit" value="Subscribe" name="signup-button" id="signup-button">
<span class="arrow"></span>
</form>
<div id="response"></div>
</div>
Now i had been found some click effect of buttons, here is the link, http://tympanus.net/Development/CreativeButtons/
In the above, 7th section[green color section], it has two submit form buttons.
One for success and one for error, so i need to use them in my subscribe form, i mean move to my send.php.
So when i click subscribe button without enter email, it shows button says, "error" instead, notification.
May i know, is it possible to achieve this?
Any help would be highly appreciated.
there is an easy way to ding so you place both two button and give error button to css display:none;
as in jquery
else {
$status = "error";
$message = "An error occurred, please try again";
$('.button-error').show();
$('.button-success').hide();
}
in this way you can achieve what you want
Download and place component.css in css folder, then add this to <head>:
<link rel="stylesheet" type="text/css" href="css/component.css" />
HTML :
<div id="newsletterform">
<h2>Get Email Update</h2>
<form method="post" id="newsletter" name="newsletter">
<input type="email" name="signup-email" id="signup-email" value="" placeholder="Insert email here" />
<input type="submit" value="Subscribe" name="signup-button" id="signup-button" class="btn btn-7 btn-7h icon-envelope">
<span class="arrow"></span>
</form>
<div id="response">
<?php if (isset($_POST['signup-button']) { ?>
<span color="<?=($status=='success')?'green':'red';?>"><?=$message;?></span>
<?php } ?>
</div>
</div>
And place just before closing </body>:
<?php if ($status == "error") { ?>
<script>
document.getElementById('signup-button').className = "btn btn-7 btn-7h icon-envelope btn-error";
setTimeout(function() {
document.getElementById('signup-button').className = "btn btn-7 btn-7h icon-envelope";
}, 1000);
</script>
<?php } ?>
Put the following at the top of your footer.php or index.php (in which you include() the footer.php)
<?php
if (isset($_POST['signup-button'])) {
try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
if (empty($email)) {
$status = "error";
$message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[#][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
$status = "error";
$message = "You must fill the field with a valid email address";
} else {
$existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
$existingSignup->execute();
$data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;
if (!$data_exists) {
$sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
$q = $db->prepare($sql);
$q->execute(
array(
':email' => $email,
':datetime' => $datetime
));
if ($q) {
$status = "success";
$message = "You have been successfully subscribed";
} else {
$status = "error";
$message = "An error occurred, please try again";
}
} else {
$status = "error";
$message = "This email is already subscribed";
}
}
$data = array(
'status' => $status,
'message' => $message
);
echo json_encode($data);
$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
?>
Also have a look here :
http://jsfiddle.net/8ft0ye6k/3/
Hope it helps.
Use this Demo Here
Add this css and js this should works
<link rel="stylesheet" type="text/css" href="http://tympanus.net/Development/CreativeButtons/css/default.css" />
<link rel="stylesheet" type="text/css" href="http://tympanus.net/Development/CreativeButtons/css/component.css" />
<script src="http://tympanus.net/Development/CreativeButtons/js/modernizr.custom.js"></script>
<script src="http://tympanus.net/Development/CreativeButtons/js/classie.js"></script>
$status = "<button class="btn btn-1 btn-1a">Button</button>";
$message = "An error occurred, please try again";
$status = "<button class="btn btn-1 btn-1a">Button</button>";
$message = "This email is already subscribed";

Categories