dousao8152
2017-04-13 07:10
浏览 75

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

I am doing a post upload using ajax, but as I make a call to addPost.php it dose not return back and show result on same page it redirects to addPost.php and shows the result on that page.

As I tried alert in success method of ajax still it redirects to the another page.

Why is this happening so? For my other function like getCategories it returns the data well. What can be the problem in this?

I want to upload a file with this form,and data as well.

    <!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>

EDIT :

   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();
            }

Tried like this still it redirects to the next page.

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';
                }
            }

}
?>

Here I dont understand, if I write data: $('#postForm').serialize(), to send the form in userAction function for ajax then I get the $_FILES array as empty, but the same code if I am doing directly in else part of validate function then the files array is not empty the file gets uploaded successfully but it redirects to next page. And From userAction function it dose not redirect to next page but I get $_FILES array empty so can not upload the file.

Please, can anyone help with this? I am a beginner in web development so not getting hoe to do this. Thank you.

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsgw3315 2017-04-13 11:50
    已采纳

    run this file in seperate

    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();
    
    
     ?>
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题