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!