dtevhgk028372 2018-04-16 17:37
浏览 75
已采纳

Ajax调用php mail()脚本成功失败,没有返回json数据

I have a problem with an ajax call to php mail() script failing on success, no json data is returned. It's basically just posting a form to a php script, validating & returning some json.

If I encounter either a validation error the json is returned correctly & my jquery executes as expected.

If NO errors are encountered, PHP processes and sends mail correctly but no data is returned to my jquery script.

Here is my code:

    <?php

require "gump.class.php";

$gump = new GUMP();

$mailto = 'me@mydomain.com';

$subject = 'A new form inquiry has been submitted.';

$output = array(
    'status' => 'success',
    'msg' => 'Mail processed successfully',
    'success' => 'success',
);



function render_email($input) {
    //error_log("render_email " . print_r($input,TRUE), 0);
    ob_start();
    include "email-template.phtml";
    return ob_get_contents();
}

$input = $gump->sanitize($_POST);

$gump->validation_rules(array(
    'first_name'    => 'required',
    'last_name'    => 'required',
    'email'    => 'required',
    //'country'       => 'required|valid_email',
    //'gender'      => 'required|exact_len,1',
    //'company' => 'required|valid_cc|max_len,2|min_len,1',
    //'bio'       => 'required'
));

$gump->filter_rules(array(
    'first_name'      => 'trim|sanitize_string',
    'last_name'       => 'trim|sanitize_string',
    'email'       => 'trim|sanitize_string',

));

$validated = $gump->run($_POST);

if($validated === false){
    error_log("GUMP: validation Error: " . print_r($gump->get_readable_errors(true),TRUE));
    $output = array(
            'status' => 'error',
            'msg' => '<strong>Validation Error: </strong>' . $gump->get_readable_errors(true),
            'error' => 'error',
        );
}else{
    error_log("GUMP: Successful Validation, processing mail",0);
    // ghead & mail the form
    $to = $mailto ;
    $subject = $subject;
    $body = render_email($input);
    $headers = "From: Metz Tea <sales@mydomain.com>" . "
";
    $headers .= "Reply-To: sales@mydomain.com
";
    $headers .= "Return-Path: info@example.com
";
    $headers .= "X-Mailer: PHP
";
    $headers .= "MIME-Version: 1.0" . "
";
    $headers .= "Content-type:text/html;charset=UTF-8" . "
";
    if(!mail($to,$subject,$body,$headers)){
        $output = array(
            'status' => 'error',
            'msg' => 'The system failed to send mail.',
            'error' => 'error',
        );
    };
    error_log("mail complete",0);
}

header("HTTP/1.1 200 OK");

header('Content-type: application/json');

$output = json_encode($output);

echo $output;

return;

and the jquery:

$('form').submit(function(event){
        event.preventDefault();
    })


    $(document).on("forminvalid.zf.abide", function(event,frm) {

        var modal = $('form').closest('.reveal').attr('id');
        $(".success").hide();
        $(".alert").show();
        console.log("Form id "+event.target.id+" is invalid");
        formToTop(modal);

      }).on("formvalid.zf.abide", function(event,frm) {

        console.log("Form id "+event.target.id+" is VALID");
        var modal = $('form').closest('.reveal').attr('id');
        var data = frm.serializeArray();

        $.ajax({
            type        : 'POST', 
            url         : 'process.php', 
            data        : data, 
            dataType    : 'json', 
            encode          : true
        }).done(function(data) {
            console.log('completed successfully '+ data);
            if (data.status != 'success') {
                console.log('AJAX returned error = ' + data.msg);
                $('.callout p').html(data.msg);
                $('.alert').show();
                formToTop(modal);
            } else {
                console.log( 'AJAX returned success = ' + data.status);
                $('.callout p').html(data.msg);
                $('#orderform').find("input[type=text], textarea, select").val("");
                $('.alert').hide();
                $('.success').show();
                $('form').slideUp('500');
                formToTop(modal);
            }
        }).fail(function(data) {
            //error
        });
        event.preventDefault();
    });

It must be the mail() function somehow, it does send mail on success, but no data is sent back to the ajax script.

what is my error here?

  • 写回答

1条回答 默认 最新

  • dongmu4591 2018-04-16 19:18
    关注

    The problem is here:

    function render_email($input) {
        //error_log("render_email " . print_r($input,TRUE), 0);
        ob_start();
        include "email-template.phtml";
        return ob_get_contents();
    }
    

    You've got side-effects both leaving the contents of your rendered template in the buffer, and leaving buffering enabled. You'll want to change this to:

    function render_email($input) {
        //error_log("render_email " . print_r($input,TRUE), 0);
        ob_start();
        include "email-template.phtml";
        $ret = ob_get_contents();
        ob_end_clean();
        return $ret;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 使用yolov5-7.0目标检测报错
  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备