javascript - Which is the better way , die or echo for ajax response? -
i using ajax in 1 of web pages this. have specified datatype json here.
jquery.ajax({ url: "www.mydomain.com/ajax.php", type: "post", datatype: "json", data:{to_email_address:"myemail@gmail.com"}, success:function(response){ response = jquery.parsejson(response); if(response){ alert("success"); } else{ alert("failed, try again"); } } });
in ajax.php
, use echo
json_encode
function follows
<?php if(!($mail_to_address, $mail_subject, $content, $headers)) { echo json_encode(false); } else{ echo json_encode(true); } ?>
but have seen somewhere , using die
instead of echo
like
<?php if(!($mail_to_address, $mail_subject, $content, $headers)) { die(json_encode(false)); } else{ die(json_encode(true)); } ?>
can please explain better way , why? in advance ..
if echo
, don't die
, run risk of mistakenly producing more output someday required, later down lines.
if die
, prints , ends right there. that's difference.
here example using code
<?php if(!($mail_to_address, $mail_subject, $content, $headers)) { echo json_encode(false); // die stop here } else{ echo json_encode(true); } echo "oops mistakenly printed"; // breaks json ?>
if use die
instead of echo
last echo
won't break json
because never execute.
if know there nothing after conditional checks, or if confident there no special reason use die()
, can keep using echo
. answer question is: none of them superior other long output under control.
Comments
Post a Comment