I am trying to upload an image using ajax form. Image upload is success. But the ajax response getting alerted automatically with a blank popup saying 'The page at www.xxx.com says'.
Here is my jQuery code
$('#profileImg').die('click').live('change', function()
{
$("#profileform").ajaxForm({target: '#preview_profile',
beforeSubmit:function(){
$("#profileloadstatus").show();
$("#profileloadbutton").hide();
},
success:function(s){
$("#profileloadstatus").hide();
$("#profileloadbutton").show();
},
error:function(){
$("#profileloadstatus").hide();
$("#profileloadbutton").show();
$('#profileform').reset();
} }).submit();
if(!s)
{
$("#profileform")[0].reset();
}
});
HTML FORM
<div id="preview_profile"></div><form id="profileform" method="post" enctype="multipart/form-data" action='message_profile_ajax.php'>
<div id="preview_prof"></div>
<div id="profileloadstatus" style="display:none; text-align:center;">
<img src='images/wall_icons/ajaxloader.gif'/> Uploading....
</div>
<div id="profileloadbutton">
<input type="file" id="profileImg" name="profileImg">
</div>
<input type="hidden" id="profvalues" value="" />
</form>
Php code
<?php
include_once 'includes.php';
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function getImangeName($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,0,$i-1);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['profileImg']['name'];
$size = $_FILES['profileImg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
$imageName = getImangeName($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = $imageName.time().$uid.".".$ext;
$tmp = $_FILES['profileImg']['tmp_name'];
if(move_uploaded_file($tmp, $profile_path.$actual_image_name))
{
$data=$Wall->Profile_Image_Upload($uid,$actual_image_name);
if($data)
{
echo '<img src="'.$profile_path.$actual_image_name.'" class="img-circle" alt="User Image" />';
}
}
else
{
echo '<b>Sorry, </b>Falied to upload your file!';
}
}
else
echo '<b>Sorry, </b>Image file size must be less than 1 MB!';
}
else
echo '<b>Sorry, </b>Invalid file format!';
}
else
echo '<b>Sorry, </b>Please select image..!';
exit;
}
?>
Please help,
Thank you
Check jquery.wallform.js
//return data;
// Modification www.9lessons.info
var exp = /<img[^>]+>/i;
expResult = data.match(exp);
if(expResult == null) {
alert(data);
} else {
$(options.target).prepend(data);
}
$("#photoimg").val('');
// Modification End www.9lessons.info
Related
We are working on our own MVC framework and on edit if we unchange the image, image changes to default. We don't want image to change in edit mode unless image is re selected.
Our code is as follows:
HTML (View)
<form id="form-category" class="form-horizontal" action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<a href="" id="thumb-image" data-toggle="image" class="img-thumbnail">
<img src="<?php echo HTTP_HOST ?>/image/<?php echo $data['industry_image']; ?>" alt="<?php echo $data['industry_name']; ?>" title="<?php echo $data['industry_name']; ?>" data-placeholder="<?php echo HTTP_HOST ?>/image/<?php echo $data['placeholder']; ?>" width="100" height="100">
<input type="hidden" name="delete_image" value="<?php echo $data['industry_image']; ?>">
</a>
<input type="file" class="hidden" name="industry_image" value="<?php echo $data['industry_image']; ?>" id="input-image" onchange="readURL(this);">
</div>
</div>
</form>
jQuery for displaying image on file select
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#thumb-image').children('img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
jQuery for Bootstrap Popover
$(document).on('click', 'a[data-toggle=\'image\']', function(e) {
var $element = $(this);
var $popover = $element.data('bs.popover'); // element has bs popover?
e.preventDefault();
// destroy all image popovers
$('a[data-toggle="image"]').popover('destroy');
// remove flickering (do not re-add popover when clicking for removal)
if ($popover) {
return;
}
$element.popover({
html: true,
placement: 'right',
trigger: 'manual',
content: function() {
return '<button type="button" id="button-image" class="btn btn-primary"><i class="fa fa-pencil"></i></button> <button type="button" id="button-clear" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>';
}
});
$element.popover('show');
$('#button-image').on('click', function() {
$('#input-image').trigger('click');
// $element.parent().find('input').attr('value', '');
$element.popover('destroy');
});
$('#button-clear').on('click', function() {
$element.find('img').attr('src', $element.find('img').attr('data-placeholder'));
$element.parent().find('input').attr('value', '');
//alert($('#input-image').attr('value', ''));
$element.popover('destroy');
});
});
Controller
$data = [
'industry_image' => isset($_POST['industry_image'] ? $_POST['industry_image'] : NULL
]
if(empty($_FILES['industry_image']['size'])) {
$data['industry_image'] = 'no-image.png';
} else {
$file = $_FILES['industry_image'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('gif', 'jpg', 'jpeg', 'png');
$allowedFileSize = 2000000;
if(in_array($fileActualExt, $allowed)) {
if($fileError === 0) {
if($fileSize < $allowedFileSize) {
$fileNameNew = strtolower($data['industry_name']) . "." . $fileActualExt;
$fileDestination = DIR_IMAGE . 'industries/' . $fileNameNew;
$filePath = 'industries/' . $fileNameNew;
if(array_key_exists('delete_image', array($data['industry_image']))) {
if(file_exists($filePath)) {
unlink($filePath);
}
}
$moveResult = move_uploaded_file($fileTmpName, $fileDestination);
if($moveResult != true) {
echo "Error: File Upload Failed. Try again.";
unlink($fileTmpName);
exit;
} else {
if(file_exists($fileNameNew)) {
flash("file_alert alert-danger", "File already exists");
} else {
$data['industry_image'] = $filePath;
}
}
} else {
flash("file_alert alert-danger", "File size is $fileSize of $allowedFileSize");
}
} else {
flash("file_alert alert-danger", "Error uploading the file");
}
} else {
$a = "Please upload only ";
foreach($allowed as $ext) {
$a .= '<b>' . $ext . '</b>' . ', ';
}
$a .= " extensions";
flash("file_alert alert-danger", $a);
}
}
if($this->model->getIndustries($industry_id, $data) {
redirect("catalog/industries", $data);
} else {
redirect("catalog/industries_form", $data);
}
Model
public function editIndustry($industry_id, $data) {
# Prepare Query for category
$this->db->query("UPDATE industry SET industry_name = :industry_name, industry_description = :industry_description, sort_order = :sort_order, status = :status WHERE industry_id = '" . $industry_id ."'");
# Bind Values
$this->db->bind(':industry_name', $data['industry_name']);
$this->db->bind(':industry_description', $data['industry_description']);
$this->db->bind(':sort_order', $data['sort_order']);
$this->db->bind(':status', $data['status']);
# Execute
$this->db->execute();
if(isset($data['industry_image'])) {
$this->db->query("UPDATE industry SET industry_image = :image WHERE industry_id = '" . $industry_id . "'");
$this->db->bind(":image", $data['industry_image']);
//$this->db->execute();
}
# Execute
if($this->db->execute()) {
return $industry_id;
} else {
return false;
}
}
Bootstrap popover image
Above code works but as mentioned earlier, image gets updated even if we don't select on POST. If the image is unedited, same image should go to database. If we clear the database with the red delete button, value gets clear from input tag should send no-image.png to the database.
Hope, I could explain my problem and looking for a solution from you'll awesome guys.
Thank you.
Here is a code for uploading image using ajax. I have added jQuery library and jQuery form as well but this code neither gives me any error nor uploads image just uploading goes on and upload image starts running never to stop. Can't find whats wrong with this code.
upload.php
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img src="./img/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image <input type="file" name="photoimg" id="photoimg" />
</form>
ajaximage.php
<?php
include("/inc/connect.php");
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username'])){
$username = $_COOKIE['username'];
}
else
{
//invalid ---
}
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
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))
{
$sql=$db->prepare("UPDATE table SET profile_pic=:image_name WHERE username=:username");
$sql->execute(array(':image_name'=>$actual_image_name,':username'=>$username));
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
I've html form. Now i'm trying to upload file using php with ajax request. But I'm getting following error message when I upload the file by php with ajax request. is it my ajax request problem or anything ?
Notice: Undefined index: file in D:\Software Installed\xampp\htdocs\wix\users\insert_galary.php on line 16
html form:
<p>Add more</p>
<div id="dialog-modal2" title="Upload your galary image" style="display: none;">
<form method="post" action="insert_galary.php" id="myForm2" enctype="multipart/form-data" >
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Upload image</td>
<td><input type="file" name="file" class="tr"/></td>
</tr>
</table>
</form>
<span id="result2"></span>
<script type="text/javascript">
$("#sub2").click( function() {
$.post( $("#myForm2").attr("action"),
$("#myForm2 :input").serializeArray(),
function(info){ $("#result2").html(info);
});
clearInput();
});
$("#myForm2").submit( function() {
return false;
});
</script>
</div>
function showDialog2()
{
$("#dialog-modal2").dialog(
{
width: 610,
height: 350,
open: function(event, ui)
{
var textarea = $('<textarea style="height: 276px;">');
$(textarea).redactor({
focus: true,
autoresize: false,
initCallback: function()
{
this.set('<p>Lorem...</p>');
}
});
}
});
}
Php form:
$gid = mt_rand(100000, 999999);
$file = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = ($_FILES["file"]["size"] / 1024);
$temp = $_FILES["file"]["tmp_name"];
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$galary_pic = $gid.".".$extension;
$galary_directory = "../galary_images/";
$err = array();
if(isset($file))
{
if(empty($file))
$err[] = "Upload your picture";
elseif(!in_array($extension, $allowedExts))
$err[] = "Uploaded file must be gif, jpeg, jpg, png format";
elseif($size > 500)
$err[] = "Uploaded file must be within 500kb";
}
if(!empty($err))
{
echo "<div class='error'>";
foreach($err as $er)
{
echo "<font color=red>$er.</font><br/>";
}
echo "</div>";
echo "<br/>";
}
else
{
echo "sql query";
}
Note: I already submit this question last day but I can't get any proper answer. Sorry about it
You're not uploading a file but just making a POST request without any file attached. If you're looking for an ajax file uploader, try jquery file upload here
http://blueimp.github.io/jQuery-File-Upload
Im using a script to out put uploaded image preview. It works fine. i just like to show the image in one div and error or success massage in another div. is there any chance to do this? Here is the code.
Java script
<script type="text/javascript">
$(document).ready(function(){
$('#photoimg').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>
HTML Code
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id="output"></div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
PHP Code
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
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)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
echo "<span class=ok-msg">Image has been uploaded..!</span>";
}
else
echo "<span class=error-msg">failed<span>";
}
else
echo "<span class=error-msg">Image file size max 1 MB</span>";
}
else
echo "<span class=error-msg">Invalid file format..</span>";
}
else
echo "<span class=error-msg">Please select image..!</span>";
exit;
}
I like to show all the massages (error-msg, ok-msg) and in the div output and image in the same place div preview. can anyone tell me how to do this. thanks in advance.
Use json dataType and success callback function like,
$("#imageform").ajaxForm(
{
dataType:'json',
success:function(json){
$('#output').html(json.img);
$('#preview').html(json.msg);
}
}).submit();
In PHP
Return data like
echo json_encode(array('img'=>"<img src='...' />",'msg'=>"Message goes here"));
return;
you can use the -success: and the error: eventListner
$("#imageform").ajaxForm(
{
dataType:'json',
success:function(json){
write the success msg
}
error: function() {
write the error msg
}
}).submit();
I have a script that has the following content:
<?php
if(isset($_POST['sent-urls']) || $_POST['sent-urls'] == true)
{
session_start();
error_reporting(E_ALL);
//ini_set('display_errors', 'Off');
include('includes/functions.php');
$url = str_replace('www.', '', url());
$images = explode("\n", $_POST['remote-urls']);
if(sizeof($images) > 30) {
$url_i = $url_t = $direct = 'You have added mroe than 30 links';
}
$links = array();
foreach($images as $image)
{
$srcfile = (isset($image)) ? trim($image) : '';
$extension = remoteEx($srcfile);
$filename = rand(124588, 543354) . '.' . remoteEx($image);
$file = remote_filesize($srcfile);
if ($file <= 3000000 && !empty($srcfile) && $extension == 'png' || $extension == 'peg' || $extension == 'jpg' || $extension == 'gif' || $extension == 'bmp')
{
$copied = copy($srcfile, 'i/' . $filename);
$direct = $url . 'i/' . $filename;
$url_i = $url . 'i/' . $filename . "\n";
if ($copied)
{
// make_thumb($direct, 't/' . $filename, 150, remoteEx($direct));
generate_thumbnail($image, $filename, 110, 110, true, 'file', false, false, '');
$url_t = $url . 't/' . $filename . "\n";
}
}
else if (empty($srcfile))
{
$url_i = $url_t = $direct = 'No links added';
}
else if ($file > 3000000)
{
$url_i = $url_t = $direct = 'Maximum size of photos exceed';
}
else
{
$url_i = $url_t = $direct = 'There was an error while submitting the form';
}
$links[] = array('direct' => $direct, 'thumb' => $url_t);
}
if ($file > 3000000) { echo 'You have exceed the limit of the file size'; }
echo '<br /><br />';
echo '<div id="links">';
echo '<table>';
echo "<tr><td><span class=\"green\">Direct:</span> <textarea class=\"link-area\" readonly=\"readonly\" onMouseOver=\"this.focus(); this.select(); $(this).css('height', '50px');\" onmouseout=\"$(this).animate({ height: '25px' }, 'fast'); $(this).blur();\">";
for($i = 0; $i < count($links); $i++) { echo $links[$i]['direct'] . "\n"; }
echo '</textarea></td></tr>';
echo "<tr><td><span class=\"green\">Thumbnail:</span> <textarea class=\"link-area\" readonly=\"readonly\" onMouseOver=\"this.focus(); this.select(); $(this).css('height', '50px');\" onmouseout=\"$(this).animate({ height: '25px' }, 'fast'); $(this).blur();\">";
for($i = 0; $i < count($links); $i++) { echo $links[$i]['thumb'] . "\n"; }
echo '</textarea></td></tr>';
echo "<tr><td><span class=\"green\">BBCode:</span> <textarea class=\"link-area\" readonly=\"readonly\" onMouseOver=\"this.focus(); this.select(); $(this).css('height', '50px');\" onmouseout=\"$(this).animate({ height: '25px' }, 'fast'); $(this).blur();\">";
for($i = 0; $i < count($links); $i++) { echo '[IMG]' . $links[$i]['direct'] . '[/IMG]' . "\n"; }
echo '</textarea></td></tr>';
echo "<tr><td><span class=\"green\">HTML:</span> <textarea class=\"link-area\" readonly=\"readonly\" onMouseOver=\"this.focus(); this.select(); $(this).css('height', '50px');\" onmouseout=\"$(this).animate({ height: '25px' }, 'fast'); $(this).blur();\">";
for($i = 0; $i < count($links); $i++) { echo '<img src="' . $links[$i]['thumb'] . '" />' . "\n"; }
echo '</textarea></td></tr>';
echo '</table>';
echo '<script type="text/javascript" src="scripts/img.core.js"></script>';
echo '<script type="text/javascript" src="scripts/jquery-1.5.js"></script>';
echo '<input type="reset" id="resetbtn-remote" class="button-sub" value="Reset" />';
echo '<br />';
echo '</div>';
}
else
{
header('Location: index.php');
}
?>
And the script gets called by this form:
<div id="remote" style="display: none;">
<form action="remote.php" method="post" id="remote-upload">
<br /><br />
<textarea name="remote-urls" id="remote-urls" rows="12"></textarea><br/>
<input type="button" name="remote-start" id="remote-start" class="remote-button" value="Upload Images" />
<input type="hidden" name="sent-urls" value="1" />
<input type="reset" id="remote-reset" class="remote-button" value="Reset" style="display: none;" />
<br /><br />
<span class="normal">
Maximum <strong>20</strong> images. <strong>10 MB</strong> for one image.
</span>
</form>
<div id="remoted">
<img id="loader1" src="css/images/loader.gif" style="display: none;" />
</div>
</div>
The form is connected with a jQuery plugin that send data from a form without refreshing the page. I hit the #remote start button, loader shows, and after a few seconds the page freezes and becomes inaccessible for ~4 seconds, then the page unfreezes with the desired results.
What might be causing the page to freeze?
EDIT: The JavaScript is like this:
$('#remote-start').live('click', function() {
$('#loader1').show();
$(this).hide();
$('#remote-reset').show();
$('#remote-upload').ajaxSubmit({
target: '#remoted',
success: function(response) {
$('#remoted').html(response).hide().slideDown('fast');
$('#loader1').fadeOut('normal');
}
});
});
$('#remote-reset').live('click', function() {
$('#remote-urls').empty();
$('#remoted').slideUp('medium', function() {
$(window.location).attr('href', 'http://localhost/imagehost');
});
});
$('#resetbtn-remote').live('click', function() {
$('#remote-urls').empty();
$('#remoted').slideUp('medium', function() {
$(window.location).attr('href', 'http://imgit.org');
});
});
Hard to say but I'd guess that your "jQuery plugin that send data from a form without refreshing the page" is calling $.ajax with async:false:
Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
The plugin is using AJAX and the above excerpt from the $.ajax documentation sounds exactly like what you're seeing.