douque9982 2016-12-23 13:42
浏览 66
已采纳

e.preventDefault / return false会中断正确的ajax脚本

I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me

JS:

$(document).ready(function() {
    var form    = $('form#edit_child_form'),
        data    = form.serializeArray();

    data.push({'parent_id': $('input[name="parent_id"]').val()});

    $('#submit_btn').on('click', function(e) {
        e.preventDefault();
        $.ajax({
            url:      form.prop('action'),
            dataType: 'json',
            type:     'post',
            data:     data,
            success: function(data) {
                if (data.success) {
                    window.opener.$.growlUI(data.msg);
                }
            },
            error: function(data) {
                if (!data.success) {
                    window.opener.$.growlUI(data.msg);
                }
            }
        });
    });
})

AJAX:

<?php
    //mysql db vars here (removed on SO)


    $descriptions = $_GET['descriptions'];
    $child_id     = $_GET['child_id'];
    $parent_id    = $_GET['parent_id'];

    $get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
    $count         = 0;
    $res           = array();

    while ($child_row = $get_child_ids->fetch_row())
    {
        try
        {
            $dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");

            $res['success'] = true;
            $res['msg']     = 'Success! DDI(s) updated';
        } catch (Exception $e) {
            $res['success'] = true;
            $res['msg']     = 'Error! '. $e->getMessage();
        }

        $count++;
    }

    echo json_encode($res);

it's probably something really small that I've just missed but not sure what - any ideas?

  • 写回答

3条回答 默认 最新

  • douweicheng5532 2016-12-23 14:19
    关注

    my solution:

    I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)