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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀