dongxi1879 2017-09-09 22:53
浏览 84

AJAX表单Post PreventDefault不起作用

I have a simple HTML document with a form I would like to post to the server without leaving the page. I've Googled around the internet all day trying to figure out how to get this to work and I've come up with the following code:

<body>
    <script> 
    $(document).ready(function() {

        $('#newResource').submit(function (e) {

            e.preventDefault();

            $.ajax({
                type: 'post',
                url: 'scripts/script.php?new-resource=1',
                data: $('#newResource').serialize(),
                success: function () {
                    alert('form was submitted');
                }
            });
            return false;

        });

    });
    </script>

    <form id="newResource" class="form-basic" enctype="multipart/form-data" method="post" action="scripts/script.php?new-resource=1">
        <label><b>Resource Name:</b></label>
        <input class="input-text" type="text" placeholder="Enter the resource name..." name="name" id="name" autocomplete="off" required="">
        <br>

        <label><b>Resource URL:</b></label>
        <input class="input-text" type="text" placeholder="Enter the resource URL..." name="url" id="url" autocomplete="off" required="">
        <br>

        <label><b>Resource Department:</b></label>
        <p>Select the department this resource should belong to.</p>
        <select class="input-select" name="department" id="department">
            <option value="5">Human Resources</option>
            <option value="1">Information Technology</option>
            <option value="3">Marketing</option>
            <option value="0">No Department</option>
            <option value="6">Purchasing</option>
            <option value="4">Sales</option>  
        </select>
        <br>

        <label><b>Resource Icon:</b></label>
        <p>Select the icon image to be displayed with this resource.</p>
        <select class="input-select" name="icon" id="icon">
            <option value="bell.png">Alarm Bell</option>
            <option value="chat-bubbles.png">Chat Bubbles</option>
            <option value="chronometer.png">Chronometer</option>
            <option value="database.png">Database Icon</option>
            <option value="envelope.png">Envelope</option>
            <option value="folder.png">File Folder</option>
            <option value="analytics.png">Monitor with Line Graph</option>
            <option value="pie-chart.png">Monitor with Pie Chart</option>
            <option value="networking.png">Networking Heirarchy</option>
            <option value="orientation.png">Orientation Arrow</option>
            <option value="server.png">Server Rack</option>
            <option value="settings.png">Settings Gears</option>
            <option value="speedometer.png">Speedomoeter</option>
            <option value="worldwide.png">World Wide Web Globe</option>
        </select>
        <br>

        <div style="float: right;">
            <button type="button" onclick="loadPrefs('resources');" class="form-button cancel">Cancel</button>
            <button class="form-button submit" type="submit">Submit</button>
        </div>

    </form>
</body>

The code is all within the body tag.

The problem is that when I click the submit button I am redirected to the PHP action script. Does the script I have need to be in the head tag instead?

If I remove the action from the form then the script redirects to the same page but no data is submitted.

Here is the PHP script if necessary:

if(isset($_GET['new-resource'])){

    // escape the SQL input for security
    $name = mysqli_real_escape_string($conn, $_POST['name']); 
    $url = mysqli_real_escape_string($conn, $_POST['url']); 
    $department = mysqli_real_escape_string($conn, $_POST['department']); 
    $icon = mysqli_real_escape_string($conn, $_POST['icon']); 

    // Run the SQL query to add the new resource item
    $sql = "INSERT INTO Resources (ID, ResourceName, ResourceURL, IconImg, Department) VALUES (NULL, '$name', '$url', '$icon', '$department');";
    $conn->query($sql);

    // Close the SQL connection
    $conn->close();

}

I can't seem to figure out why this is not working. Any thoughts and feedback are appreciated.

  • 写回答

3条回答 默认 最新

  • dongle3217 2017-09-09 23:49
    关注

    Your event handler is bound to the submit event of the form. By the time the form has been submitted, it's too late to stop the default synchronous HTML form submission.

    Bind your handler to the to click event on the submit button, use event.preventDefault() and submit the form via Ajax:

    $(document).ready(function() {
    
            $('.submit').click(function (e) {
    
                e.preventDefault();
    
                var form = $('#newResource');
                var action = form.attr('action');
                var data = form.serialize();
    
    
                $.ajax({
                    type: 'POST',
                    url: action,
                    data: data,
                    success: function () {
                        alert('form was submitted');
                    }
                });
    
    
            });
    
        });
    

    Please note, the way this is written, it will fire for any click of an element with a class of submit. Since you may have more than one form on your web page and more than one button with a class of submit, it's not good to have the form variable use a hard-coded ID selector.

    If the HTML of all your website forms are always coded this same way, with the submit button inside of a div which is nested in the form, you could replace:

    var form = $('#newResource');
    

    with:

    var form = $(this).parent().closest('form');
    

    Now you can wrap that code in a function called "bindForms()" or whatever, and you have a generic recipe for handling all forms, provided that the HTML structure is always the same (or at least, to the extent that the submit button always has a class of submit and is always wrapped in a parent container which is a child of the form.

    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)