duanhuizhe6767 2012-09-24 16: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-24 16: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.

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部