Get error from PHP display in jQuery - php

I am trying to develop a PHP based application to upload a file to the web server
the jquery code goes like this
<form action="upload.php" method="post" enctype="multipart/form-data" name="upload">
<input name="uploaded_file" type="file"
style="border-radius:0px; width:900px; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif" required/>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
<input type="hidden" name="id" value=<?php echo $getid; ?> />
<br/>
<br/>
<input name="Upload" type="submit" value="Upload" class="btn btn-success btn-large" style="border-radius:0px;" id="uploadfile"/>
</form>
<div class="progress" id="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
$(document).ready(function(){
$('#progress').hide();
$('#uploadfile').click(function(){
$('#progress').show();
});
});
</script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html('Uploaded sucessfull');
}
});
})();
</script>
and the php code goes like this
<?php
include('connect.php');
include('antivirus.php');
$virusstatus='FALSE';
function clean($str)
{
$str = #trim($str);
if(get_magic_quotes_gpc())
{
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$filedesc= 'Enter Description';
$fname= mt_rand(1000,9999);
$id=clean($_POST['id']);
//upload random name/number
$rd2 = mt_rand(1000,9999)."_File";
//Check that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext != "exe") && ($_FILES["uploaded_file"]["type"] != "application/x-msdownload")) {
//Determine the path to which we want to save this file
//$newname = dirname(__FILE__).'/upload/'.$filename;
$newname="uploads/".$rd2."_".$filename;
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
{
$vsig=scanfile($newname);
$query=mysql_query("select * from virussig")or die(mysql_error());
while($image=mysql_fetch_array($query))
{
if($vsig==$image['vsig'])
{
$virusstatus='TRUE';
}
}
if($virusstatus=='TRUE')
{
die("This file contains some Virus signatures which is not allowed");
}
else
{
mysql_query("INSERT INTO up_files (id,fdesc,floc,fdatein,fname) VALUES ('$id','$filedesc','$newname',NOW(),'$fname')");
header("location: iconview.php?id=".$id);
}
}
}
}
?>
my problem is whenever error occurs in php during file upload,it gives file upload sucessful in jquery.
I want the solution to somhow manage the errors got in php and display in jquery
please help
Thankyou

Have something like this in your php code
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname)))
{
$result = true;
return json_encode($result);
}
else
{
$result = false;
return json_encode($result);
}
Then in your ajax success call back
complete: function(xhr,data) {
if(data === true)
status.html('Uploaded sucessfull');
else
status.html('Uploaded unsuccessful');
}
Do check the syntax and json returned as well. Have written this logically.
You can also do it without json_encode. and appropriate return type in ajax call

Related

Uploading file via ajax

i am trying to upload file using ajax.
form enctype="myltipart/form-data" id="pastTest-form" method="POST" action="upload.php">
<div class="feedback-form-inputs col-5">
<div class="input-field">
<select id="type" required>
<option value="quiz">Quiz</option>
<option value="midterm">Midterm</option>
<option value="final">Final</option>
</select>
</div>
<div class="input-field">
<input type="text" id="professor"/>
</div>
<div class="input-field">
<input type="text" id="name"/>
</div>
<div class="input-field">
<input type="file" id="uploaded_file" name="file" accept="" required />
</div>
</div><!-- END feedback-form-inputs -->
<div class="clear"></div>
<input type="submit" value="submit" onclick="submit() />
<div id="upload-status"> </div>
</form>
my function for opening ajax are in the external file.
function addPastTest1(cid){
// form variables
var type = _("type").value;
var professor = _("professor").value;
var name = _("name").value;
var fileSelect = _('uploaded_file');
var status = _('upload-status');
event.preventDefault();
// Update status text.
status.innerHTML = 'Uploading...';
// Get the selected files from the input.
var file = fileSelect.files[0];
var FileName = file.name;
var FileSize = file.size;
var allowed = ["msword", "pdf","pages"];
var found = false;
// check if the extension of the file match the allowed ones
allowed.forEach(function(extension) {
if (file.type.match('application/'+extension)) {
found = true;
}
})
if (FileSize >10204){
status.innerHtml = 'File must be less than 1mb in size';
}
if (found==true){
// Create a new FormData object.
var formData = new FormData();
// Add the file to the request.
formData.append('file', file, FileName);
// Set up the request.
var ajax = ajaxObj("POST", "ajaxResponse.php");
ajax.onreadystatechange = function(){
if (ajaxReturn(ajax)==true){
if (ajax.responseText=='failed'){
status.innerHtml = "failed to upload file";
}
else {
status.innerHtml = 'uploaded';
alert(ajax.responseText);
}
}
}
ajax.send(formData); //ajax.send("f="+formData+"&t="+type+"&p="+professor+"&n="+name+"&cid="+cid+"&fn="+FileName);
}
}
so i am sending formData to the php. but at this point i can not take the file from form data and upload it to the server.
here is my php
// Ajax calls this code to add a past test
if (isset($_FILES['file']){
$file = $_FILES['file'];
$path = 'files/'.$type.'/'.$fileName;
$moveResult = move_uploaded_file($file, $path);
if ($moveResult != true) {
echo "ERROR: File not uploaded. Try again.";
//unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
exit();
}
$path = 'files/'.$type.'/'.$fileName;
$sql = "INSERT into past_papers VALUES ('$name', '$type', '$cid', '$professor','$path')";
$query = mysqli_query($db_conx,$sql);
if (mysqli_affected_rows($db_conx)>0){
echo "success";
exit();
}
else {
echo "failed sql";
exit();
}
}
?>
Also i want to grab inputs with the file and process them together. Upload file, and insert inputs into database.
The simplest one I can find. :)
jQuery code
$("#form-id").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "file-to-call.php",
type: "POST",
data: new FormData(this),
cache: false,
processData: false,
success: function(data) {
//handle success
}
});
}));
HTML code
<form name='form1' method='post' enctype='multipart/form-data' id='form-id'>
<input type='submit' id='input' value='Upload' />
</form>

Form does not post data

i have the following html code:
<form class="dropzone" id="msform" enctype="multipart/form-data"> <!-- multistep form -->
<!-- progressbar -->
<ul id="progressbar">
<li class="active">Account Setup</li>
<li>Post an Image</li>
</ul>
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Fill in Some General Details</h2>
<h3 class="fs-subtitle">As Simple As This</h3>
<input type="text" name="update" id="title" placeholder="Update Title" />
<textarea name="description" id="description" placeholder="Short Description/Add On"></textarea>
<input type="date" name="expire" id="expire" placeholder="Expire By" value="Expire By" />
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset>
<h2 class="fs-title">Upload Image</h2>
<h3 class="fs-subtitle">We currently only support images.</h3>
<div class="dropzone-previews dz-message" id="dropzonePreview">
</div>
<input type="button" name="previous" class="previous action-button" value="Previous" />
<input type="submit" name="submit" class="submit action-button" value="Submit"/>
</fieldset>
</form>
</div>
</div>
<script>
Dropzone.options.msform = { // The camelized version of the ID of the form element
// The configuration we've talked about above
url: "filepostupload.php",
autoProcessQueue: false,
autoDiscover: false,
addRemoveLinks: true,
uploadMultiple: false,
parallelUploads: 5,
maxFiles: 5,
paramName: "file",
previewsContainer: '.dropzone-previews',
clickable:'#dropzonePreview', //used for specifying the previews div
//used this but now i cannot click on previews div to showup the file select dialog box
// The setting up of the dropzone
init: function() {
var myDropzone = this;
this.element.querySelector("input[type=submit]").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
e.preventDefault();
e.stopPropagation();
if (myDropzone.getQueuedFiles().length === 0) {
var update = $('#title').val();
var description = $('#description').val();
var expiry = $('#expire').val();
var groupid = <?php echo $groupid ?>;
var request = $.ajax({
url: "updatesnofile.php",
type: "POST",
data: { update:update, description:description, expiry:expiry, groupid:groupid},
dataType:"text",
success: function(data) {
if (data=="success") {
alert('success');
} else {
alert(data);
}
},
error: function(request, err){
alert(err);
}
});
}else {
myDropzone.processQueue();
}
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sending", function() {
// Gets triggered when the form is actually being sent.
// Hide the success button or the complete form.
});
this.on("success", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
alert(response);
});
this.on("error", function(files, response) {
alert("error");
});
}
}
</script>
And my php script that does the file upload is :
<?php
session_start();
require 'config.php';
//I'm using mysql_ as an example, it should be PDO
$ds = DIRECTORY_SEPARATOR;
$foldername = "updatefiles/";
if (isset($_POST['update']) && isset($_POST['description']) && isset($_POST['expiry']) && isset($_POST['groupid'])){
$title= mysqli_real_escape_string($mysqli,trim($_POST['update']));
$description= mysqli_real_escape_string($mysqli,trim($_POST['description']));
$expire= mysqli_real_escape_string($mysqli,trim($_POST['expiry']));
$groupid= mysqli_real_escape_string($mysqli,trim($_POST['groupid']));
$fileupload = basename($_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath. $fileupload;
move_uploaded_file($tempFile,$targetFile);
$fileupload = mysqli_real_escape_string($mysqli,basename($_FILES['file']['name']));
$fileType = mysqli_real_escape_string($mysqli,$_FILES['file']['type']);
$fileSize = mysqli_real_escape_string($mysqli,$_FILES['file']['size']);
mysqli_query($mysqli,"START TRANSACTION;");
$ins = mysqli_query($mysqli,"INSERT INTO posts (category, description, posttitle, userid, expire, group_id) VALUES ('updates','".$description."', '".$title."','{$_SESSION['userid']}', '".$expire."','".$groupid."' )");
if (!$ins) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with first insert";
return FALSE;
}
$upd = mysqli_query($mysqli,"SET #post_id_in_posts = LAST_INSERT_ID()");
if (!$upd) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo"error with setting postid";
return FALSE;
}
$del = mysqli_query($mysqli, "INSERT INTO files (post_id,f_name, f_type, f_size) VALUES (#post_id_in_posts,'".$fileupload."', '".$fileType."', '".$fileSize."')");
if (!$del) {
// fail
mysqli_query($mysqli,"ROLLBACK");
echo "Error with Second Insert!";
return FALSE;
}
// All succeeded
mysqli_query($mysqli,"COMMIT");
echo"success";
return TRUE;
}else {
echo"formwasnotsubmitted";
}
?>
However, it keeps telling me that the form was not submitted (which means the posting of the form by drop zone fails, and therefore the data isn't posted over when there are files, the ajax works though when there are NO files), can anyone find out why? thanks!
I have managed to find the mistake, it is something to do with the way Dropzone sends the form data!

PayPal Button is not clickable link in Prestashop

I have installed the PayPal module and added all of the API details. It appears on the page, however it cannot be clicked. Why could this be? The code, as viewed in the source, is this:
It looks a bit odd to me. Like the image should be linked to the form somehow?
Also tried it in sandbox mode and that doesn't work either.
<div id="HOOK_SHOPPING_CART_EXTRA">
<div id="container_express_checkout" style="float:right; margin: 10px 40px 0 0">
<img id="payment_paypal_express_checkout" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" alt="" />
<form id="paypal_payment_form" action="http://mydomain.com/store/modules/paypal/express_checkout/payment.php" data-ajax="false" title="Pay with PayPal" method="post" data-ajax="false">
<!-- Change dynamicaly when the form is submitted -->
<input type="hidden" name="quantity" value="1" />
<input type="hidden" name="id_p_attr" value="" />
<input type="hidden" name="express_checkout" value="cart"/>
<input type="hidden" name="current_shop_url" value="http://mydomain.com/store/index.php?controller=order&multi-shipping=0" />
<input type="hidden" name="bn" value="FR_PRESTASHOP_H3S" />
</form>
</div>
</div>
Fixed it myself. The required code that makes the button work was missing the header. If anyone else finds this page in the future, the code you need is:
$(document).ready( function() {
$('#payment_paypal_express_checkout').click(function() {
$('#paypal_payment_form').submit();
return false;
});
$('#paypal_payment_form').live('submit', function() {
var nb = $('#quantity_wanted').val();
var id = $('#idCombination').val();
$('#paypal_payment_form input[name=quantity]').val(nb);
$('#paypal_payment_form input[name=id_p_attr]').val(id);
});
function displayExpressCheckoutShortcut() {
var id_product = $('input[name="id_product"]').val();
var id_product_attribute = $('input[name="id_product_attribute"]').val();
$.ajax({
type: "GET",
url: baseDir+'/modules/paypal/express_checkout/ajax.php',
data: { get_qty: "1", id_product: id_product, id_product_attribute: id_product_attribute },
cache: false,
success: function(result) {
if (result >= '1')
$('#container_express_checkout').slideDown();
else
$('#container_express_checkout').slideUp();
return true;
}
});
}
$('select[name^="group_"]').change(function () {
displayExpressCheckoutShortcut();
});
$('.color_pick').click(function () {
displayExpressCheckoutShortcut();
});
var modulePath = 'modules/paypal';
var subFolder = '/integral_evolution';
var fullPath = baseDir + modulePath + subFolder;
var confirmTimer = false;
if ($('form[target="hss_iframe"]').length == 0) {
if ($('select[name^="group_"]').length > 0)
displayExpressCheckoutShortcut();
return false;
} else {
checkOrder();
}
function checkOrder() {
confirmTimer = setInterval(getOrdersCount, 1000);
}
function getOrdersCount() {
$.get(
fullPath + '/confirm.php',
{ id_cart: '7' },
function (data) {
if ((typeof(data) != 'undefined') && (data > 0)) {
clearInterval(confirmTimer);
window.location.replace(fullPath + '/submit.php?id_cart=7');
$('p.payment_module, p.cart_navigation').hide();
}
}
);
}
});

PHP AJAX Image Upload Example Not Uploading

My code produces no errors on the console. When I click the upload button, nothing happens. There is a post sent to itself, as instructed in the tutorial I used but the image is not uploaded to my folder and it is not displayed on my page. Barring the fact I know I should use jquery (I will make the transition once I get it to upload to the folder) what is wrong with my code?
<?php
if (!empty($_FILES)) {
$name = $_FILES['file']['name'];
if ($_FILES['file']['error'] == 0) {move_uploaded_file($_FILES['file']
['tmp_name'], "post_images/" . $name))}
}
?>
<script type="text/javascript">
var handleUpload = function (event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('file', fileInput.files[1]);
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if (event.lengthComputable)
{
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +
'%'));
}
});
request.upload.addEventListener('load',function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed');
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
};
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
</script>
<div id="uploaded">
<?php
if (!empty($name)) {
echo '<img src="post_images/' . $name . '" width="100" height="100" />';
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file" />
<input type="submit" id="submit" value="upload" />
</div>
</form>
</div>
There is only one file in a non- multiple file input element, fileInput.files[1] attempts to use the second file.
data.append('file', fileInput.files[0]);

Upload progress option in file upload does not work in I.E

I am uploading image file using ajax and php.
Here is the code,
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<form action="fileup.php" method="post" enctype="multipart/form-data">
<input type="file" id="fileup" name="file" accept="image/*" style="position:relative; left:-105px; top:30px; opacity:0; z-index:10; cursor:pointer;" >
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status" style = "position:relative; top:-20px; left:150px;"></div>
Ajax:
$jq(function() {
var bar = $jq('.bar');
var percent = $jq('.percent');
var status = $jq('#status');
$jq('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
status.html("Uploading...");
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
status.html("Upload complete");
isrc = xhr.responseText;
handleFiles(files);
}
});
$jq("#fileup").change(function () {
files = this.files;
$jq('form').submit();
});
});
PHP code,
<?php
$target_path = "uploaded_images/";
$file_name = $_FILES["file"]["name"];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$target_path = $target_path . basename( $new_file_name);
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
echo basename( $new_file_name);
} else{
echo "There was an error uploading the file, please try again!";
}
?>
It is working fine and it shows the progress in chrome and firefox. But in i.e it doesn't enter upload progress. I even put an alert there and it doesn't show up in i.e...

Categories