dtyqeoc70733 2015-07-01 13:26
浏览 12

Ajax调用(之前/成功)在php文件中不起作用

I have a form that when clicked the submit button makes a call via ajax. This ajax is inside a php file because I need to fill in some variables with data from the database. But I can not use the calls before / success. They just do not work, I've done tests trying to return some data, using alert, console.log and nothing happens. Interestingly, if the ajax is isolated within a file js they work. Some can help me please?

File:

<?php

$var = 'abc';

?>

<script type="text/javascript">
    $(document).ready(function() {

        $('#buy-button').click(function (e){

            var abc = '<?php echo $var; ?>';

            $.ajax({  
                type: 'POST',
                data: $('#buy-form').serialize(),
                url: './ajax/buy_form.php',
                dataType: 'json',
                before: function(data){
                    console.log('ok');
                },
                success: function(data){

                },
            });
        });

    });
</script>

HTML:

<form id="buy-form">
  <div class="regular large gray">
      <div class="content buy-form">
          /* some code here */
          <div class="item div-button">
            <button id="buy-button" class="button anim" type="submit">Comprar</button>
          </div>
      </div>
  </div>
</form>

---- EDIT ----

Problem solved! The error was in the before ajax. The correct term is beforeSend and not before. Thank you all for help.

  • 写回答

2条回答 默认 最新

  • dongnong3019 2015-07-01 13:30
    关注

    You said it was a submit button and you do not cancel the default action so it will submit the form back. You need to stop that from happening.

    $('#buy-button').click(function (e){
        e.preventDefault();
        /* rest of code */
    

    Now to figure out why it is not calling success

            $.ajax({  
                type: 'POST',
                data: $('#buy-form').serialize(),
                url: './ajax/buy_form.php',
                dataType: 'json',
                before: function(data){
                    console.log('ok');
                },
                success: function(data){
    
                },
                error : function() { console.log(arguments); }  /* debug why */
            });
        });
    

    My guess is what you are returning from the server is not valid JSON and it is throwing a parse error.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大