duanhuizhe6767 2012-09-25 00:04
浏览 21
已采纳

有了jQuery,AJAX和PHP的这个组合,我如何捕获来自PHP的错误?

I handle it if the PHP returns successfully, but as far as errors go I'm a little confused as to what I should be doing.

What I was thinking of doing since the following code for error: doesn't work, was in my PHP setting the mail function equal to a variable in order to save the result of the function. Then in my jQuery, testing the result of the variable to find whether or not it's true.

However this would all occur under success: when it seems like clearly error should be handling this.

How do I have it so success: handles the successes correctly and displays a message while error: will handle the errors by returning the errors then I'll be able to display them to the user.

Also bonus points if you can tell me if my .html() function is done well? It looks messy formatting-wise, but I can't seem to figure a nicer way to do it.

jQuery:

// Following section submits form without refreshing page
var dataString = "name=" + nameVal + "&email=" + emailVal + "&message=" + messageVal;  
$.ajax({  
    type: "POST",  
    url: "mail.php",  
    data: dataString,  
    success: function() { 
        $(".contact-form").hide();
        $(".alt-contact").hide();
    // Inserts divs making up the success message for the form submission
        $(".contact-form").html("<div class='success-message'><div class='success-image'></div><div class='success-title'>Success! The message has been sent!</div><div class='success-body'>I'll get back to you right away.</div></div>");
        $(".contact-form").fadeIn(500);
    }
    error: function() {
        $(".contact-form").hide();
        $(".alt-contact").hide();
        // Inserts divs making up the success message for the form submission
        $(".contact-form").html("<div class='error-message'><div class='error-image'></div><div class='error-title'>Success! The message has been sent!</div><div class='error-body'>I'll get back to you right away.</div></div>");
        $(".contact-form").fadeIn(500);
    }
});
return false;

PHP:

<?php

    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    $recipient = 'me@christianselig.com';
    $subject = 'Message From Website';
    $body = '<b>From:</b> ' . $name . '

' . $message;
    $headers = 'From: ' . $email . '
';
    $headers .= 'Content-type: text/html; charset=UTF-8' . '
';

    mail($recipient, $subject, $body, $headers);

?>
  • 写回答

1条回答 默认 最新

  • douren1928 2012-09-25 00:18
    关注

    Any error messages will stil be pumped back to "success" in the ajax call. (Error function is for "call did not work" or "unexpected response from server")

    You should check your script to report both success and error status to the script. This is easiest handled in JSON, but for that you need to write a custom error handler that spits out JSON.

    For now, make it simple with:

    if (@mail($recipient, $subject, $body, $headers)) {
         return json_encode(array('success' => 1));
    } else {
         return json_encode(array('success' => 0));
    } 
    

    then change you JS to

    // Following section submits form without refreshing page
    var dataString = "name=" + nameVal + "&email=" + emailVal + "&message=" + messageVal;  
    $.ajax({  
        type: "POST",  
        url: "mail.php",  
        data: json,    // CHANGED TYPE HERE
        success: function(data) { 
              if (data.success) {
                    // WORKED
               } else {
                    // FAILED TO SEND
               }
            $(".contact-form").fadeIn(500);
        }
        error: function() {
               // was not JSON, you got some other error
        }
    });
    return false;
    

    Edit in response to comment question

    By default error will be called if there is an invalid response (e.g. 404 page not found, 500 server error). As I added "datatype: json" then error will also be returned if the response can't be parsed as JSON. if you left datatype as 'dataString' then you may of may not hit error so adding the JSON type makes it more reliable. Regardless, JSON is easier to handle in Javascript and a known structure is best - so always try to return JSON (unless you need HTML, XML or another known structure). Strings are least reliable.

    It's a litle more complicated at first as regular PHP errors will also be sent back as "strings" and not valid JSON; so these go to error where you have to handle it. I've avoided this in hte exampel above by hiding errors from the mail call in your code with @, and handled it specifically. For my projects I have custom error handler that traps errors and spits back the response in JSON in a known structure - this then returns in success, all my AJAX calls check for 'data.error' which means it went though the error handler, and can be handled accordingly. But for now, just handle via the error in the AJAX and use Charles (Mac OS) or Fiddler (Windows) or the network sniffers in the browsers for debugging.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了