0

I know this has been asked before and I have looked at every post I could find that deals with this. I still cannot get the jQuery.post function to correctly receive the error from a php script. Here are both.
PHP:

<?php 
##CONFIGURATION
# LIST EMAIL ADDRESS
$toemail = "email here";

# SUBJECT (Subscribe/Remove)
$subject = "Someone has contacted International Designs";

# RESULT PAGE
$location = "../thank-you.php";

## FORM VALUES ##
$myname = $_REQUEST['myname'];
$myemail = $_REQUEST['myemail'];
$mymessage = $_REQUEST['mymessage'];

if ( empty($myname) || empty($myemail) || empty($mymessage) ) {

    exit('{"error":"That value was invalid!"}')

} else {

    # SENDER
    $email = $myname . " <" . $myemail . ">";

    # MAIL BODY
    $body .= "Name: " . $myname . " \n\n";
    $body .= "Email: " . $myemail . " \n\n";
    $body .= "Message: " . $mymessage . " \n\n";
    # add more fields here if required

    ## SEND MESSGAE ##

    mail( $toemail, $subject, $body, "From: $email" ) or die ("Mail could not be sent.");

}

?>

JS:

if (verify(myname, myemail, mymessage, human, hash, patt)) {
  $.post(myform.attr('action'), myform.serialize(), function() {
    $('#email-success').fadeIn();
    myform[0].reset();
    setTimeout("$('#email-success').fadeOut();", 5000);
  }, 'json')
  .fail(function() {
    alert('An error has occurred. Please try again later.')
  });
}

I have tried about 5 different methods already, none of which have worked. When I put 'json' as the datatype in the .post function the .fail always fires, no matter what's in the php script. If I leave datatype out, then .fail never fires under any circumstance. I have a feeling the problem is with the php commands and datatype. Any help is appreciated.

preahkumpii
  • 1,301
  • 4
  • 21
  • 36
  • Have you checked what is the actual response of the php script? Use some tool like firebug for example. – Eggplant May 17 '13 at 08:03
  • Thanks for the tip Eggplant about Firebug. It does give insight. Help me understand, pls. If I completely remove the data string from the .post function, what kind of data is .post expecting to return from the php script? Another thing, when I try to set the header to code 400, firebug is telling me that I cannot change the header. That might be because I am not leaving the page when I submit the form, but am using the post function in jquery instead and showing divs to communicate with the user. – preahkumpii May 17 '13 at 08:20
  • 2
    Starting from the easiest: make sure you set the headers **before** any other output in the php script, this will fix the `headers can't be modified` issue. The .post handler is expecting the PHP script to return some data in the `dataType` you specify, in this case some JSON. If nothing is returned, it should not be an issue, a 200 status is returned and it's enough. But again, check with firebux what is happening under the hood. You might return a conventinoal confirmation JSON like `{"response":"ok"}` if you like. – Eggplant May 17 '13 at 08:37

3 Answers3

2

Perhaps it's because you don't change the http header code of your response and don't specify your data type response.

You're php code response to front (jQuery) code with a "200 – OK" status in any case, but you expect an error in some case with an 'HTTP/1.0 400 – Bad Request' response Or a 'HTTP/1.0 500 Internal Server Error'.

And, like say Eggplant, you have to specify your response data type as 'Content-Type: application/json'.

So, the final code would be something like this :

<?php 
...

header('HTTP/1.0 204 – No Content', true, 204);
header('Content-Type: application/json');

if ( empty($myname) || empty($myemail) || empty($mymessage) ) {

    header('HTTP/1.0 400 – Bad Request', true, 400);
    exit('{"error":"That value was invalid!"}')

} else {

    ...

    $send = mail( $toemail, $subject, $body, "From: $email" );
    if (!$send)
        header('HTTP/1.0 500 – Internal Server Error', true, 500);
        exit ('{"error":"Mail could not be sent."}');
    }
}
return;
?>

For the Warning Cannot modify header information - headers already sent by (output started at /homepages/.../design/contact.php:1) you can examine this answer on the same problem.

Output can be:

  • Unintentional:
    • Whitespace before
    • UTF-8 Byte Order Mark
    • Previous error messages or notices
  • Intentional:
    • print, echo and other functions producing output (like var_dump)
    • Raw areas before

Update after chat session : it's was a UTF-8 BOM problem

Community
  • 1
  • 1
palmplam
  • 707
  • 9
  • 20
  • 1
    Yep, this is the cause why the .fail handler is never called under any circumstances. About the other part of the problem, it would be necessary to set the correct content-type header like `header('Content-Type: application/json');`, but it seems nothing is returned by the script in case of success. – Eggplant May 17 '13 at 08:07
  • When I implement this, Firebug shows an error that Headers cannot be modified. – preahkumpii May 17 '13 at 08:25
  • @Eggplant : a header set with a 204 code will solve the no return case – palmplam May 17 '13 at 09:05
  • @preahkumpii : i update my response with more explanations integrate part of your code into – palmplam May 17 '13 at 09:06
  • @palmplam, Here is the response when I do what you said:
    Warning: Cannot modify header information - headers already sent by (output started at /homepages/.../design/contact.php:1) in /homepages/.../design/contact.php on line 3

    Warning: Cannot modify header information - headers already sent by (output started at /homepages/.../design/contact.php:1) in /homepages/.../design/contact.php on line 4
    – preahkumpii May 17 '13 at 11:10
  • 1
    @preahkumpii You have to call the header() function before any return to view (or any print), that why you have this warning. Did you print data before the call of this function ? – palmplam May 17 '13 at 11:22
  • `header('HTTP/1.0 204 – No Content', true, 204);` is the first line of the php script, that is after ` – preahkumpii May 17 '13 at 11:36
  • Let me clarify something. This form is submitted, NOT by `action="contact.php"` in the html form, but by jquery in the js using the .post method. I have `e.preventDefault();` in my js code in the `.submit()` method. So, when you say 'return to view', the browser is never leaving the page the form is on. Not sure if that helps. – preahkumpii May 17 '13 at 11:40
  • @preahkumpii No problem with that, i understand the process. But make sure you don't have any print into the stack of response before the header() call. Did this php file directly call or contact.php include this file and print something before the final flush of the response ? See this => http://stackoverflow.com/questions/1793482/php-error-cannot-modify-header-information-headers-already-sent – palmplam May 17 '13 at 11:59
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/30124/discussion-between-preahkumpii-and-palmplam) – preahkumpii May 17 '13 at 12:02
  • 1
    This advice was sound. My problem was the UTF-8 file had the BOM. This was causing the _headers cannot be modified_ error. Thanks @palmplam – preahkumpii May 17 '13 at 13:27
0

Although, yours is a valid JSON data, I always recommend to use json_encode() function to create JSON string.

exit(json_encode(array("error" => "That value was invalid!")));

Another is make sure you send correct headers to ensure the script knows its a json data. So

header('Content-Type: application/json');
exit(json_encode("error" => "That value was invalid!"));
Starx
  • 77,474
  • 47
  • 185
  • 261
0

try this

if (verify(myname, myemail, mymessage, human, hash, patt)) {
    $.ajax({
        type    :'POST',
        data    :$("#myformid").serialize(),
        beforeSend:function(){

        },
        success:function(res){
            if(res=='ok'){
                setTimeout("$('#email-success').fadeOut();", 5000);
            }else{
                //read respon from server
                alert(res)
            }
        },
        error:function(){
            //error handler
        }
    });
}

and just example

$send = mail(....);//your mail function here
echo ($send) ? "ok" : "Error";
Khairu Aqsara
  • 1,321
  • 3
  • 14
  • 27