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 关于哈夫曼树应用得到一些问题
  • ¥15 使用sql server语句实现下面两个实验(需要代码和运行结果截图)
  • ¥20 用web解决,要给我一个完整的网页,符合上述的要求
  • ¥20 求个sql server代码和结果的图 两道题
  • ¥15 银河麒麟操作系统无法使用U盘
  • ¥100 寻找:光电二极管电路设计服务
  • ¥15 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁