Javascript Ajax上传并添加到数据库

Javascript Ajax上传并添加到数据库,javascript,php,jquery,ajax,Javascript,Php,Jquery,Ajax,我有一个表单可以将团队添加到数据库中,所以我想将团队插入数据库并将徽标上传到团队目录中。 HTML表单 <form action="index.php#list_teams" id="subjectForm" method="post" enctype="multipart/form-data"> <p> <label>Team name</label> <inp

我有一个表单可以将团队添加到数据库中,所以我想将团队插入数据库并将徽标上传到团队目录中。 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>
我想知道我现在如何上传徽标,我已经尝试在另一个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>";
}
}
if(isset($\u文件[“文件”][“类型”]))
{
$validextensions=数组(“jpeg”、“jpg”、“png”);
$temporary=explode(“.”,$_文件[“文件”][“名称”]);
$file_extension=end($temporary);
如果(($_文件[“文件”][“类型”]=“图像/png”)| |($_文件[“文件”][“类型”]=“图像/jpg”)| |($_文件[“文件”][“类型”]=“图像/jpeg”)
)&&($_文件[“文件”][“大小”]<100000)//可以上载大约100kb的文件。
&&在数组中($file_扩展名,$validex)){
如果($\u文件[“文件”][“错误”]>0)
{
回显“返回代码:”.$\u文件[“文件”][“错误”]。“

”; } 其他的 { 如果(文件存在(“../style/images/teams/”$\u文件[“文件”][“名称”])){ echo$\u文件[“文件”][“名称”]。“已存在。”; } 其他的 { $sourcePath=$\u FILES['file']['tmp\u name'];//将文件的源路径存储在变量中 $targetPath=“../style/images/teams/”$\u FILES['file']['name'];//存储文件的目标路径 移动上传的文件($sourcePath,$targetPath);//移动上传的文件 echo“图像上传成功…”
; echo“
文件名:“.$”文件[“文件”][“名称”]。
”; echo“Type:”.$\u文件[“file”][“Type”]。“
”; 回显“大小:”($_文件[“文件”][“大小”]/1024)。“kB
”; 回显“临时文件:”.$\u文件[“文件”][“tmp\u名称”]。
”; } } } 其他的 { 回显“***无效的文件大小或类型***”; } }

因此,我如何在ajax上调用两篇文章或在file submit上删除Encodeuri组件。

您的代码中需要更改的内容很少,例如:

  • 使用
    event.preventDefault()
    为了防止表单首先被提交,这样您就不需要从函数返回任何
    false

    $('input[type="submit"]').click(function(event){
        event.preventDefault();
        //your code
    });
    
  • 如果您是通过AJAX上传文件,请使用object。但请记住,旧浏览器不支持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');
    
    $(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');
            })
        });
    });
    
    因为这样你就不用用这个了

    data: 'ajax=1&do=addteam&name='+encodeURIComponent($('#name').val()) + ...
    
    你可以这么做

    data: formdata,
    
  • 在AJAX请求中设置以下选项,
    processData:false
    contentType:false
    。请参考了解这些功能

    contentType : false,
    processData: false,
    
因此,解决方案是,保持HTML表单不变,并按以下方式更改jQuery

// If required, change $('form')[0] accordingly
var formdata = new FormData($('form')[0]);
formdata.append('ajax', 1);
formdata.append('do', 'addteam');
$(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');
        })
    });
});
$(文档).ready(函数(){
$(“#subjectForm*”)。每个(函数(){
if(this.type=='text'| | this.type=='textarea'){
$(this.blur(function()){
validForm(this.form,this.name);
});
}
});
$('input[type=“submit”]”)。单击(函数(事件){
event.preventDefault();
if(有效形式(此.form,“”){
//如果需要,相应地更改$('form')[0]
var formdata=新的formdata($('form')[0]);
append('ajax',1);
append('do','addteam');
$.ajax({
url:'post.php',
键入:“POST”,
数据:formdata,
contentType:false,
processData:false,
成功:功能(数据){
$(“#注意”).removeClass('error').removeClass('success');
var status=data.split(“|-|”)[0];
var message=data.split(“|-|”)[1];
$('#notice').html(''+message+'').addClass(status);
$(#notice').fadeIn().animate({opacity:1},5000,'linear',function(){$(this.fadeOut();});
$('#name').val('');
$('#file').val('');
}
});
}
});
$('input[type=“reset”]”)。单击(函数(){
$('.content-box-content').find('span.input-notification').each(函数(){
$(this.remove();
});
$('.content box content*')。每个(函数(){
$(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!');     
            }
        }
    }   
?>

您需要在代码中更改的内容很少,例如:

  • 使用
    event.preventDefault()
    为了防止表单首先被提交,这样您就不需要从函数返回任何
    false

    $('input[type="submit"]').click(function(event){
        event.preventDefault();
        //your code
    });
    
  • 如果您是通过AJAX上传文件,请使用object。但请记住,旧浏览器不支持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');
    
    $(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');
            })
        });
    });
    
    因为这样你就不用用这个了

    data: 'ajax=1&do=addteam&name='+encodeURIComponent($('#name').val()) + ...
    
    你可以这么做

    data: formdata,
    
  • 在AJAX请求中设置以下选项,
    processData:false
    contentType:false
    。请参考了解这些功能

    contentType : false,
    processData: false,
    
因此,解决方案是,保持HTML表单不变,并按以下方式更改jQuery

// If required, change $('form')[0] accordingly
var formdata = new FormData($('form')[0]);
formdata.append('ajax', 1);
formdata.append('do', 'addteam');
$(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');
        })
    });
});
$(文档).ready(函数(){
$(“#subjectForm*”)。每个(函数(){
if(this.type=='text'| | this.type=='textarea'){
$(this.blur(function()){
validForm(this.form,this.name);
});
}
});
$('input[type=“submit”]”)。单击(函数(事件){
event.preventDefault();
if(有效形式(此.form,“”){
//如果需要,相应地更改$('form')[0]
var formdata=新的formdata($('form')[0]);
append('ajax',1);