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

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试