如何从php检索布尔值到javascript文件

is that possible to retrieve Boolean value from php to javascript?

All I want to do is simple: Retrieve Boolean value from php variable $x into js

  1. Should be true when emails are sent

  2. And False when emails are not sent

Then take that Boolean value with javascript print the appropriate message

Complete code of my work can be found here, on my other case I had opened yesterday

PHP:

if (!$mail->send()) {
   $x = false; //when email is not sent
} else {
    $x = true; //when email is sent
}

JS Pseudocode

.done(function (data) {
    if(php Boolean variable is false) { 
        ("$formText").html("Message sent");
    } else (if php Boolean variable is true) {
        ("$formText").html("Message not sent");
    }
});

I am assuming you are already passing data (via AJAX) you just don't know how to encode it.

Use: json_encode()

PHP:

if (!$mail->send()) {
$x = true;

} else {
 $x = false;
}
header("Content-type: application/json");
echo json_encode(array('x'=>$x));

Javascript:

 .done(function (data) {
           if (data.x) { 
               $("#formText").html("Message sent");
           } else {
               $("#formText").html("Message not sent");
           }
        } //end function data      
  );//end done function

While returning bool value from PHP code use json_encode(). It convert from native PHP types to native Javascript type.

http://php.net/manual/en/function.json-encode.php

using response code and handling them with done and fail

PHP

<?php
  // ...

  $success = '{"message": "your mail is send"}';
  $error = '{"message": "failed sending mail"}';

  $code;
  $out;
  if(mailSend){
    $code = 200;
    $out = $success;
  } else {
    $code = 400;
    $out = $error;
  }

  http_response_code($code);
  echo $out;

JS

// ...
var data = 'yourData';

$.ajax({
  url: 'yourApiUrl'M,
  data: data,
  method: 'POST',
  xhrFields: {withCredentials: true},
  crossDomain: true,
  dataType: 'json'
}).done(function() {
  // mail was send
}).fail(function() {
  // error on sending
});

a list of status codes you can find on https://en.wikipedia.org/wiki/List_of_HTTP_status_codes