使用ajax提交表单后,请保持同一页面

时间:2017-04-13 07:10:28

标签: javascript php jquery ajax file

我正在使用ajax进行上传,但是当我调用addPost.php时,它不会返回并在同一页面上显示结果,它会重定向到addPost.php并在该页面上显示结果。

当我在ajax的成功方法中尝试提醒时,它仍会重定向到另一个页面。

为什么会这样?对于像getCategories这样的其他函数,它可以很好地返回数据。这可能是什么问题?

我想上传一个包含此表单和数据的文件。

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Post</title>
</head>
<body>

<form class="postForm" id="postForm" method="post" action="addPost.php" enctype="multipart/form-data">

    <fieldset>
        <legend>Please add the details below </legend>
        <p>
            <label for="title">Title (required, at least 2 characters)</label>
            <input id="title" name="title" minlength="2" type="text" required>
        </p>

        <p>
            <label for="desc">Description (required, at least 2 characters)</label>
            <input id="desc" name="desc" minlength="2" type="text" required>
        </p>
        <p>
            <label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
            <input id="keywords" name="keywords" minlength="2" type="text" required>
        </p>

        <select id="types" name="types" onchange="myFunction(this)">

            <option value="">Select type</option>

            <option value="2">Add Link</option>
            <option value="0">Upload Image</option>
            <option value="1">Upload Video</option>

        </select><br><br>

        <div id="link" style="display: none">

        <p>
            <label for="url">URL (required)</label>
            <input id="url" type="url" name="url" required>
        </p>

        <p>
            <label for="urlType">Select Url Type :(required)</label>
            <select name="urlType" id="urlType">
                <option value="">Select Url Type...</option>
        <!--        <option value="0">Server Image</option>
                <option value="1">Server Video</option>-->
                <option value="2">YouTube Video</option>
                <option value="3">Vimeo Video</option>
                <option value="4">Facebook Image</option>
                <option value="5">Facebook Video</option>
                <option value="6">Instagram Image</option>
                <option value="7">Instagram Video</option>
                <option value="-1">Other</option>
            </select>
        </p>

        </div>

        <div id="filediv" style="display: none">

            Select file to upload:
            <br><br>
            <input name="file1" type="file" id="fileToUpload"><br><br>

        </div>


        <p>
            <label for="postType"> Select Post Type :(required)</label>
            <select name="postType" id="postType">
                <option value="">Select Post Type...</option>
                <option value="0">Normal</option>
                <option value="1">Featured</option>
                <option value="2">Sponsored</option>
            </select>
        </p>
        <p>
            <label for="category"> Select Category :(required)</label>
            <select name="category" id="category">
                <option value="">Select Category...</option>
            </select>
        </p>
        <p>
            <input type="hidden" name="action_type" id="action_type_id"/>
            <input type="hidden" name="id" id="p_id"/>
<!--            <a href="javascript:void(0);" class="btn btn-warning" onclick="$('#postForm').slideUp();">Cancel</a>
            <a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add User</a>-->
           <input type="submit" name="submit" id="submit" value="Submit">
        </p>
    </fieldset>

    <div class="result" id="result"></div>


</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>

<script>
    window.onerror = function(error, url, line) {
        controller.sendLog({acc:'error', data:'ERR:'+error+' URL:'+url+' L:'+line});
    };

    $(document).ready(function(){
        getCategories();
/*

        $("#postForm").submit(function(e){
            e.preventDefault();
        });
*/

        $('#postForm').validate({ // initialize the plugin
            rules: {
                title: {
                    required: true,
                    minlength : 2
                },
                url: {
                    required: true
                },
                desc: {
                    required : true,
                    minlength : 2
                },
                keywords : {
                    required : true,
                    minlength : 2
                },
                urlType :
                    {
                        required : true
                    },
                postType :
                    {
                        required : true
                    },
                category :
                    {
                        required : true
                    },
                file1 :
                    {
                        required : true
                    }
            },
            submitHandler: function (form) {


                var url = document.getElementById('urlType').value;

                if(validate_url(document.getElementById('url').value) == 'facebook' && url == 6)
                {
                    alert('Please enter valid facebook image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 7)
                {
                    alert('Please enter valid facebook image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 3)
                {
                    alert('Please enter valid facebook image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 2)
                {
                    alert('Please enter valid facebook image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 3)
                {
                    alert('Please enter valid instagram image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 2)
                {
                    alert('Please enter valid instagram image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 4)
                {
                    alert('Please enter valid instagram image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 5)
                {
                    alert('Please enter valid instagram image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'vimeo' && url != 3)
                {
                    alert('Please enter valid vimeo video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'youtube' && url != 2)
                {
                    alert('Please enter valid youtube video url or select valid url type.');
                }
                else {


                    userAction('add');

                  /*  var data = new FormData();
                    jQuery.each(jQuery('#file')[0].files, function(i, file) {
                        data.append('file-'+i, file);
                    });

                    $.ajax({
                        type: "POST",
                        url: 'addPost.php',
                        dataType: 'text',
                        data: $('#postForm').serialize(),
                        async: false,
                        cache: false,
                        success: function (result) {
                            //alert(report);
                            $(".result").html(report);
                            $("#postForm").trigger('reset');
                        }
                    });
*/

                    /*             jQuery.ajax({
                                     url: 'addPost.php',
                                    // data: data,
                                     data: $('#postForm').serialize(),
                                     cache: false,
                                     contentType: false,
                                     processData: false,
                                     encctype: "multipart/form-data",
                                     type: 'POST',
                                     success: function(report){
                                         alert(report);
                                        // $(".result").html(report);
                                         $("#postForm").trigger('reset');
                                     }
                                 });*/
                 //   e.preventDefault();
                }
            }
        });

    });

    function getCategories() {

        $.ajax({
            type: "POST",
            url: 'getCategories.php',
            dataType: 'text',
            async: false,
            cache: false,
            success: function (result) {

                $('#category').html(result);
            }
        });

    }


    function userAction(type,id){

    /*    var statusArr = {add:"added",edit:"updated",delete:"deleted"};

*/
        var form = $('#fileUploadForm')[0];

        // Create an FormData object
        var data = new FormData(form);

        if (type == 'add') {

            $('#action_type_id').val(type);
            $('#p_id').val(id);
        }

        $.ajax({
            type: 'POST',
            url: 'addPost.php',
            enctype: 'multipart/form-data',
         //   data : data,
         //   data: $(this).serialize(),
            data: $('#postForm').serialize(),
            cache: false,
            success:function(report){
                // replace data to report

            $(".result").html(report);
            $("#postForm").trigger('reset');
            }
        });
     //   e.preventDefault();

/*
    $("form#data").submit(function(){

        var formData = new FormData($(this)[0]);

        $.ajax({
            url: 'addPost.php',
            type: 'POST',
            data: formData,
            success: function (data) {
                $(".result").html(report);
                $("#postForm").trigger('reset');
            },
            cache: false,
            contentType: false,
            processData: false
        });*/

      /*  var data = new FormData();
        jQuery.each(jQuery('#file')[0].files, function(i, file) {
            data.append('file-'+i, file);
        });


        jQuery.ajax({
            url: 'addPost.php',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(report){
                $(".result").html(report);
                $("#postForm").trigger('reset');
            }
        });*/

    }

    function myFunction(obj) {

        var type = obj.value;
        var x = document.getElementById('link');
        var y = document.getElementById('filediv');


        if(type == "2")
        {
            x.style.display = 'block';
            y.style.display = 'none';
        }
        else {
            x.style.display = 'none';
            y.style.display = 'block';
        }

    }

    function validate_url(url)
    {
        if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
            return 'facebook';

        if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
            return 'facebook';

        if (/^(https?:\/\/)?((w{3}\.)?)instagram.com\/.*/i.test(url))
            return 'instagram';

        if (/^(https?:\/\/)?((w{3}\.)?)vimeo.com\/.*/i.test(url))
            return 'vimeo';

        if (/^(https?:\/\/)?((w{3}\.)?)youtube.com\/.*/i.test(url))
            return 'youtube';

        return 'unknown';
    }

</script>

</body>
</html>

编辑:

   else {
               // userAction('add');

                var data = new FormData();
                jQuery.each(jQuery('#file')[0].files, function(i, file) {
                    data.append('file-'+i, file);
                });
                e.preventDefault();

                jQuery.ajax({
                    url: 'addPost.php',
                   // data: data,
                    data: $('#postForm').serialize(),
                    cache: false,
                    contentType: false,
                    processData: false,
                    encctype: "multipart/form-data",
                    type: 'POST',
                    success: function(report){
                        alert(report);
                       // $(".result").html(report);
                        $("#postForm").trigger('reset');
                    }
                });
             //   e.preventDefault();
            }

这样做仍然会重定向到下一页。

addPost.php

    <?php

include 'Database.php';
ini_set('display_errors', 1);
error_reporting(1);
ini_set('error_reporting', E_ALL);
ini_set('post_max_size', '1.8G');
ini_set('upload_max_filesize', '1.8G');


if(isset($_POST['submit']))
{

         $database = new Database(Constants::DBHOST, Constants::DBUSER, Constants::DBPASS, Constants::DBNAME);
        $dbConnection = $database->getDB();
        $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $stmt = $dbConnection->prepare("insert into keywords(keyword) 
                                    values(?)");
        $stmt->execute(array($_POST['keywords']));

        $file_result = "";

        if(strcmp($_POST['types'],"2") == 0)
        {

            //insert data into posts table
            $stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type) 
                                    values(?,?,?,?,?,?,?)");
            $stmt->execute(array($_POST['category'], $_POST['title'], $_POST['url'], $_POST['urlType'], $_POST['desc'], $_POST['keywords'],$_POST['postType']));

            $count = $stmt->rowCount();

            if ($count > 0) {

                echo "Post submitted.";
            } else {

                echo "Could not submit post.";
            }


        }
      else {

                if (isset($_FILES["file1"]["name"])) {

                    $file_result = "";

                    if ($_FILES["file1"]["error"] > 0) {
                        $file_result .= "No file uploaded or invalid file.";
                        $file_result .= "Error code : " . $_FILES["file1"]["error"] . "<br>";
                    } else {

                        if (strcmp($_POST['types'], "0") == 0) {
                          //  $target_dir = "./agtvapp/images/";
                            $target_dir = "images/";
                        } else {
                           // $target_dir = "./agtvapp/videos/";
                            $target_dir = "videos/";
                        }

                        $newfilename = preg_replace('/\s+/', '',
                            $_FILES["file1"]["name"]);
                        $target_file = $target_dir . basename($newfilename);

                     /*   $target_file = $target_dir . basename($_FILES["file1"]["name"]);*/

                        $file_result .=
                            "Upload " . $_FILES["file1"]["name"] . "<br>" .
                            "type " . $_FILES["file1"]["type"] . "<br>" .
                            "temp file " . $_FILES["file1"]["tmp_name"] . "<br>";

                        if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file)) {

                            $stmt = $dbConnection->prepare("insert into posts(category_id,title,url,url_type,description,keywords,post_type) 
                                    values(?,?,?,?,?,?,?)");
                            $stmt->execute(array($_POST['category'], $_POST['title'], $newfilename, $_POST['types'], $_POST['desc'], $_POST['keywords'], $_POST['postType']));

                            $count = $stmt->rowCount();

                            if ($count > 0) {

                                echo "The file " . basename($_FILES['file1']['name']) . " has been uploaded, and post submitted.";

                            } else {

                                echo "Could not submit post.";
                            }

                        }
                    }

                }
                else{

                    echo 'empty file';
                }
            }

}
?>

这里我不明白,如果我写数据:$('#postForm')。serialize(),在ajax的userAction函数中发送表单然后我得到$ _FILES数组为空,但是相同的代码如果我我直接在其他部分验证功能,然后文件数组不为空文件成功上传,但它重定向到下一页。并且从userAction函数开始,它不会重定向到下一页,但是我将$ _FILES数组设为空,因此无法上传文件。

拜托,有人可以帮忙吗?我是网络开发的初学者,所以不要锄头这样做。谢谢。

1 个答案:

答案 0 :(得分:1)

单独运行此文件

的index.php

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Post</title>
</head>
<body>

<form class="postForm" id="postForm" method="post" action="addPost.php" enctype="multipart/form-data">

    <fieldset>
        <legend>Please add the details below </legend>
        <p>
            <label for="title">Title (required, at least 2 characters)</label>
            <input id="title" name="title" minlength="2" type="text" required>
        </p>

        <p>
            <label for="desc">Description (required, at least 2 characters)</label>
            <input id="desc" name="desc" minlength="2" type="text" required>
        </p>
        <p>
            <label for="keywords">Keywords (eg:#facebook)(required, at least 2 characters)</label>
            <input id="keywords" name="keywords" minlength="2" type="text" required>
        </p>

        <select id="types" name="types" onchange="myFunction(this)">

            <option value="">Select type</option>

            <option value="2">Add Link</option>
            <option value="0">Upload Image</option>
            <option value="1">Upload Video</option>

        </select><br><br>

        <div id="link" style="display: none">

        <p>
            <label for="url">URL (required)</label>
            <input id="url" type="url" name="url" required>
        </p>

        <p>
            <label for="urlType">Select Url Type :(required)</label>
            <select name="urlType" id="urlType">
                <option value="">Select Url Type...</option>
        <!--        <option value="0">Server Image</option>
                <option value="1">Server Video</option>-->
                <option value="2">YouTube Video</option>
                <option value="3">Vimeo Video</option>
                <option value="4">Facebook Image</option>
                <option value="5">Facebook Video</option>
                <option value="6">Instagram Image</option>
                <option value="7">Instagram Video</option>
                <option value="-1">Other</option>
            </select>
        </p>

        </div>

        <div id="filediv" style="display: none">

            Select file to upload:
            <br><br>
            <input name="file1" type="file" id="fileToUpload"><br><br>

        </div>


        <p>
            <label for="postType"> Select Post Type :(required)</label>
            <select name="postType" id="postType">
                <option value="">Select Post Type...</option>
                <option value="0">Normal</option>
                <option value="1">Featured</option>
                <option value="2">Sponsored</option>
            </select>
        </p>
        <p>
            <label for="category"> Select Category :(required)</label>
            <select name="category" id="category">
                <option value="s">Select Category...</option>
            </select>
        </p>
        <p>
            <input type="hidden" name="action_type" id="action_type_id"/>
            <input type="hidden" name="id" id="p_id"/>
<!--            <a href="javascript:void(0);" class="btn btn-warning" onclick="$('#postForm').slideUp();">Cancel</a>
            <a href="javascript:void(0);" class="btn btn-success" onclick="userAction('add')">Add User</a>-->
           <input type="submit" name="submit" id="submit" value="Submit">
        </p>
    </fieldset>

    <div class="result" id="result"></div>


</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>

<script>
    window.onerror = function(error, url, line) {
        controller.sendLog({acc:'error', data:'ERR:'+error+' URL:'+url+' L:'+line});
    };

    $(document).ready(function(){
        getCategories();
/*

        $("#postForm").submit(function(e){
            e.preventDefault();
        });
*/

        $('#postForm').validate({ // initialize the plugin
            rules: {
                title: {
                    required: true,
                    minlength : 2
                },
                url: {
                    required: true
                },
                desc: {
                    required : true,
                    minlength : 2
                },
                keywords : {
                    required : true,
                    minlength : 2
                },
                urlType :
                    {
                        required : true
                    },
                postType :
                    {
                        required : true
                    },
                category :
                    {
                        required : true
                    },
                file1 :
                    {
                        required : true
                    }
            },
            submitHandler: function (form) {


                var url = document.getElementById('urlType').value;

                if(validate_url(document.getElementById('url').value) == 'facebook' && url == 6)
                {
                    alert('Please enter valid facebook image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 7)
                {
                    alert('Please enter valid facebook image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 3)
                {
                    alert('Please enter valid facebook image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'facebook' && url == 2)
                {
                    alert('Please enter valid facebook image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 3)
                {
                    alert('Please enter valid instagram image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 2)
                {
                    alert('Please enter valid instagram image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 4)
                {
                    alert('Please enter valid instagram image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'instagram' && url == 5)
                {
                    alert('Please enter valid instagram image,video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'vimeo' && url != 3)
                {
                    alert('Please enter valid vimeo video url or select valid url type.');
                }
                else if(validate_url(document.getElementById('url').value) == 'youtube' && url != 2)
                {
                    alert('Please enter valid youtube video url or select valid url type.');
                }
                else {


                    userAction('add');

                  /*  var data = new FormData();
                    jQuery.each(jQuery('#file')[0].files, function(i, file) {
                        data.append('file-'+i, file);
                    });

                    $.ajax({
                        type: "POST",
                        url: 'addPost.php',
                        dataType: 'text',
                        data: $('#postForm').serialize(),
                        async: false,
                        cache: false,
                        success: function (result) {
                            //alert(report);
                            $(".result").html(report);
                            $("#postForm").trigger('reset');
                        }
                    });
*/

                    /*             jQuery.ajax({
                                     url: 'addPost.php',
                                    // data: data,
                                     data: $('#postForm').serialize(),
                                     cache: false,
                                     contentType: false,
                                     processData: false,
                                     encctype: "multipart/form-data",
                                     type: 'POST',
                                     success: function(report){
                                         alert(report);
                                        // $(".result").html(report);
                                         $("#postForm").trigger('reset');
                                     }
                                 });*/
                 //   e.preventDefault();
                }
            }
        });

    });

    function getCategories() {

        $.ajax({
            type: "POST",
            url: 'getCategories.php',
            dataType: 'text',
            async: false,
            cache: false,
            success: function (result) {

                $('#category').html(result);
            }
        });

    }


    function userAction(type,id){

    /*    var statusArr = {add:"added",edit:"updated",delete:"deleted"};

*/


        var form = $('#postForm')[0];

        // Create an FormData object
        var data = new FormData(form);

        if (type == 'add') {

            $('#action_type_id').val(type);
            $('#p_id').val(id);
        }

        $.ajax({
            type: 'POST',
            url: 'add.php',
            processData: false,
            contentType: false,
            data : data,
            success:function(report){
                // replace data to report

            $(".result").html(report);
            $("#postForm").trigger('reset');
            }
        });
     //   e.preventDefault();

/*
    $("form#data").submit(function(){

        var formData = new FormData($(this)[0]);

        $.ajax({
            url: 'addPost.php',
            type: 'POST',
            data: formData,
            success: function (data) {
                $(".result").html(report);
                $("#postForm").trigger('reset');
            },
            cache: false,
            contentType: false,
            processData: false
        });*/

      /*  var data = new FormData();
        jQuery.each(jQuery('#file')[0].files, function(i, file) {
            data.append('file-'+i, file);
        });


        jQuery.ajax({
            url: 'addPost.php',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function(report){
                $(".result").html(report);
                $("#postForm").trigger('reset');
            }
        });*/

    }

    function myFunction(obj) {

        var type = obj.value;
        var x = document.getElementById('link');
        var y = document.getElementById('filediv');


        if(type == "2")
        {
            x.style.display = 'block';
            y.style.display = 'none';
        }
        else {
            x.style.display = 'none';
            y.style.display = 'block';
        }

    }

    function validate_url(url)
    {
        if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
            return 'facebook';

        if (/^(https?:\/\/)?((w{3}\.)?)facebook.com\/.*/i.test(url))
            return 'facebook';

        if (/^(https?:\/\/)?((w{3}\.)?)instagram.com\/.*/i.test(url))
            return 'instagram';

        if (/^(https?:\/\/)?((w{3}\.)?)vimeo.com\/.*/i.test(url))
            return 'vimeo';

        if (/^(https?:\/\/)?((w{3}\.)?)youtube.com\/.*/i.test(url))
            return 'youtube';

        return 'unknown';
    }

</script>

</body>
</html>

add.php

<?php

echo "<pre>"; print_r($_FILES); 
exit();


 ?>