Ajax上传并添加到数据库

时间:2016-09-16 21:27:04

标签: javascript php jquery ajax

我有一个表单将团队添加到数据库,所以我想将团队插入数据库并将徽标上传到团队目录。 HTML表格

        <form action="index.php#list_teams" id="subjectForm" method="post" enctype="multipart/form-data">
        <p>
            <label>Team name</label>
            <input class="text-input medium-input" type="text" id="name" name="name" maxlength="20" />
        </p>
        <br>
        <p>
            <label>Team Logo (50x50px) </label>   
            <div id="image_preview"><img id="previewing" src="images/preview.png" /></div>
            <div id="selectImage">
            <label>Select Your Image</label><br/>
            <input type="file" name="file" id="file" />
            <h4 id='loading' >loading..</h4>
            <div id="message"></div>
            </div>
        </p>
        <br />
        <br />
        <br />
        <p>
            <input class="btn" type="submit" value="Add" />&#32;
            <input class="btn" type="reset" value="Reset" />
        </p>
    </form>

THE JS

$(document).ready(function(){
    $('#subjectForm *').each(function(){
        if(this.type=='text' || this.type=='textarea'){
            $(this).blur(function(){
                validForm(this.form,this.name);
            });
        }
    });
    $('input[type="submit"]').click(function(){
        if(validForm(this.form,'')){
            $.ajax({
                url: 'post.php',
                type: 'POST',
                data: 'ajax=1&do=addteam&name='+encodeURIComponent($('#name').val()) + '&file=' + encodeURIComponent($('#file').val()),
                success: function(data) {
                    $('#notice').removeClass('error').removeClass('success');
                    var status = data.split('|-|')[0];
                    var message = data.split('|-|')[1];
                    $('#notice').html('<div>'+ message +'</div>').addClass(status);
                    $('#notice').fadeIn().animate({opacity:1}, 5000, 'linear', function(){$(this).fadeOut();});
                    $('#name').val('');
                    $('#file').val('');
                }
            });
        }
        return false;
    });
    $('input[type="reset"]').click(function(){
        $('.content-box-content').find('span.input-notification').each(function(){
            $(this).remove();
        });
        $('.content-box-content *').each(function(){
            $(this).removeClass('error');
        })
    });

这是POST.php

if ($_POST['do'] == 'addteam')
{
$name = urldecode($_POST['name']);
$file = urldecode($_POST['file']);
$db->query_write('INSERT INTO teams(name,image) VALUES ("' .
    $db->escape_string($name) . '","' . $db->escape_string($file) . '")');
if ($db->affected_rows() > 0)
{
    display('success|-|Team has been added into database.');
}
display('error|-|Something went wrong with database!');     
}

我想知道我现在如何上传徽标,我试图在另一个上传文件的php文件上发帖但是在提交时不能发两个ajax帖子。

这是我的上传代码

    if(isset($_FILES["file"]["type"]))
{
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 100000)//Approx. 100kb files can be uploaded.
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
}
else
{
if (file_exists("../style/images/teams/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <span id='invalid'><b>already exists.</b></span> ";
}
else
{
$sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "../style/images/teams/".$_FILES['file']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
echo "<span id='success'>Image Uploaded Successfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
}
}
}
else
{
echo "<span id='invalid'>***Invalid file Size or Type***<span>";
}
}

那么如何在ajax上调用两个帖子或者在文件提交时删除encodeURIComponent。

1 个答案:

答案 0 :(得分:2)

您需要在代码中更改一些内容,例如:

  • 使用event.preventDefault();来阻止您的表单首先被提交,这样您就不需要从函数中返回任何false值。

    $('input[type="submit"]').click(function(event){
        event.preventDefault();
        //your code
    });
    
  • 如果您是通过AJAX上传文件,请使用FormData对象。但请记住,旧浏览器不支持FormData对象。 FormData支持从以下桌面浏览器版本开始:IE 10 +,Firefox 4.0 +,Chrome 7 +,Safari 5 +,Opera 12+。您可以通过以下方式在代码中使用FormData,

    // If required, change $('form')[0] accordingly
    var formdata = new FormData($('form')[0]);
    formdata.append('ajax', 1);
    formdata.append('do', 'addteam');
    

    因为通过这种方式,您不必使用它,

    data: 'ajax=1&do=addteam&name='+encodeURIComponent($('#name').val()) + ...
    

    你可以这么做,

    data: formdata,
    
  • 在AJAX请求中设置以下选项processData: falsecontentType: false。请参考the documentation了解这些操作。

    contentType : false,
    processData: false,
    

所以,解决方案是,保持您的 HTML 表单不变,并按以下方式更改 jQuery

$(document).ready(function(){
    $('#subjectForm *').each(function(){
        if(this.type=='text' || this.type=='textarea'){
            $(this).blur(function(){
                validForm(this.form,this.name);
            });
        }
    });
    $('input[type="submit"]').click(function(event){
        event.preventDefault();
        if(validForm(this.form,'')){
            // If required, change $('form')[0] accordingly
            var formdata = new FormData($('form')[0]);
            formdata.append('ajax', 1);
            formdata.append('do', 'addteam');

            $.ajax({
                url: 'post.php',
                type: 'POST',
                data: formdata,
                contentType : false,
                processData: false,
                success: function(data) {
                    $('#notice').removeClass('error').removeClass('success');
                    var status = data.split('|-|')[0];
                    var message = data.split('|-|')[1];
                    $('#notice').html('<div>'+ message +'</div>').addClass(status);
                    $('#notice').fadeIn().animate({opacity:1}, 5000, 'linear', function(){$(this).fadeOut();});
                    $('#name').val('');
                    $('#file').val('');
                }
            });
        }
    });
    $('input[type="reset"]').click(function(){
        $('.content-box-content').find('span.input-notification').each(function(){
            $(this).remove();
        });
        $('.content-box-content *').each(function(){
            $(this).removeClass('error');
        })
    });
});

post.php 上,处理您的表单数据:

<?php
    if(isset($_POST['ajax']) && isset($_POST['do']) && isset($_POST['name']) && is_uploaded_file($_FILES['file']['tmp_name'])){

        // add team to the database
        if ($_POST['do'] == 'addteam'){
            $name = $_POST['name'];
            $db->query_write('INSERT INTO teams(name,image) VALUES ("' . $db->escape_string($name) . '","' . $db->escape_string($file) . '")');
            if ($db->affected_rows() > 0){

                // now upload logo
                // and when you successfully upload the logo, just do this:
                // display('success|-|Team and logo have been added into database.');


            }else{
                display('error|-|Something went wrong with database!');     
            }
        }
    }   
?>