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条)

报告相同问题?

悬赏问题

  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题