简体   繁体   中英

Can't Upload File Using php and jquery

I have tried so many ways but still can't solve the problem. The code is able to upload the file IF I comment the submitHandler command in uploadscript.js. However, when I uncommented the line, php should return "registered" to uploadscript.js, then the successful message should appear. Instead, it shows Sorry! Unable to submit your paper !.

<!-- file: newsubmission.php -->
<script src="../../js/jquery1.11.3.min.js"></script>
<script type="text/javascript" src="../../js/validation.min.js"></script>    
<script src="../../js/uploadscript.js"></script>
<script src="../../js/jquery.additional.methods.js"></script>
<!-- html form -->
<form class="form-signin" method="post" id="upload-form" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="papers" id="papers" placeholder="File Name" class="form-control" style="width:300px">
</div>
</form>

Here is my uploadscript.js

// JavaScript Document
$('document').ready(function()
{ 
$("#upload-form").validate({
    rules: {
        papertitle: {
            required: true
        },
        authors: {
            required: true
        },
        papers: {
            required: true,
            extension: "doc|docx|pdf|DOC|DOCX|PDF"
        },
        categoryid: {
            required: true
        },
        eventid: {
            required: true
        }
    },
    messages: {
        papertitle: {
                required: "Please enter paper title"
        },
        authors: {
            required: "Please enter authors"
        },
        papers: {
            required: "Please select your paper",
            extension: "Unsupported file type"
        },
        categoryid: {
            required: "Please select category"
        },
        eventid: {
            required: "Please select colloqium"
        }
    },
    submitHandler: submitForm
}); 

function submitForm()
{
    var data = $("#upload-form").serialize();

    $.ajax({
        type: 'POST',
        url: 'submitpaper.php',
        data: data,
        beforeSend: function() {    
            $("#error").fadeOut();
            $("#btn-submit").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; sending ...');
        },
        success: function (data) {
            if(data === 1)
            {
                $("#error").fadeIn(1000, function() {
                    $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; Sorry! Your paper already exist in the database !</div>');
                    $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Submit Paper');
                }); 
            }
            else if(data === "registered")
            {
                $('#upload-form').each(function(){
                    this.reset();
                });
                $('#error').html('<div class="alert alert-success"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; Success! Sucessfully registered !</div>');
                $("#error").show().delay(10000).fadeOut();
                $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Submit Paper');  
            }
            else
            {
                $("#error").fadeIn(1000, function() {
                    $("#error").html('<div class="alert alert-danger"><span class="glyphicon glyphicon-info-sign"></span> &nbsp; Sorry! Unable to submit your paper !</div>');
                    $("#btn-submit").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Submit Paper');
                }); 
            }
        }
    }); // close ajax
    return false;
} //end submit form
});

Here is my submitpaper.php

<?php
include("../../config/dbconn.php");
include("../../config/lib.php");

if($_POST)
{
$userid = $_POST['userid'];
$papertitle = $_POST['papertitle'];
$authors = $_POST['authors'];
$categoryid = $_POST['categoryid'];
$eventid = $_POST['eventid'];
$submitted = date("Y-m-d H:i:s");
$statusid = 1; //1-submitted (default), 2-reviewing, 3-accepted, 4-rejected

$uploadpath = "/Applications/MAMP/htdocs/kolokium/files/";  
$filename = pathinfo($_FILES['papers']['name'], PATHINFO_FILENAME); 
$fileext = strtolower(pathinfo($_FILES['papers']['name'], PATHINFO_EXTENSION));
$RandNumber = rand(0, 9999999999); 

$allowedext = array("doc", "docx", "pdf", "DOC", "DOCX", "PDF");

$newfilename = $filename . '_' . $RandNumber . "." . $fileext;

if(findDuplicatePaperTitle($papertitle, $conn) === true)
{
    echo 1; //duplicate paper title
}
else
{
    if(move_uploaded_file($_FILES['papers']["tmp_name"], $uploadpath . $newfilename) === true)
    {
        //savenewpaper($userid, $papertitle, $authors, $NewFileName, $categoryid, $eventid, $submitted, $statusid); 
        $sql = "INSERT INTO papers (papertitle, paperauthors, categoryid, eventid, statusid, 
        papersubmitteddate, author_userid, paperfilename) VALUES (:papertitle, :authors, :categoryid,
        :eventid, :statusid, :submitted, :userid, :paperfilename)"; 
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':papertitle', $papertitle);
        $stmt->bindParam(':authors', $authors);
        $stmt->bindParam(':paperfilename', $newfilename);
        $stmt->bindParam(':categoryid', $categoryid);
        $stmt->bindParam(':eventid', $eventid);
        $stmt->bindParam(':statusid', $statusid);
        $stmt->bindParam(':submitted', $submitted);
        $stmt->bindParam(':userid', $userid);
        $stmt->execute();

        echo "registered";
    }
    else
        echo "failed to upload";
}
}
?>

U need to use formdata for this. supported by latest browsers may b this could help you.. How to use FormData for ajax file upload

Just replace your

var data = $("#upload-form").serialize();

with

var data = new FormData( $('#upload-form')[0] );

and add these to your ajax

contentType : false
processData : false

Here's a simple example you can play with:

uploadscript.js

function submitForm()
{
    var data = new FormData( $("#upload-form")[0] );

    $.ajax({
        type: 'POST',
        url: 'submitpaper.php',
        data: data,
        contentType : false,
        processData : false,
        beforeSend: function() {    

        },
        success: function (data) {
            alert(data);
        }
    }); // close ajax

} //end submit form

submitpaper.php

<?php
    var_dump($_FILES['papers']);
?>

newsubmission.php

<script src="jquery.min.js"></script>  
<script src="uploadscript.js"></script>
<script>
    $(function(){
        $('form').submit(function(e){
            e.preventDefault();
            submitForm();
        });
    });
</script>
<!-- html form -->
<form class="form-signin" method="post" id="upload-form" enctype="multipart/form-data">
    <div class="form-group">
        <input type="file" name="papers" id="papers" placeholder="File Name" class="form-control" style="width:300px">
    </div>
    <button type="submit">Upload</button>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM