Php script exit options for response in ajax

An example of a function to exit a PHP method to send a response to ajax.

Let’s say there is a method:

public function ajaxGetSomething() {}

Something is being done in it and we need to get out of it by turning on the HMTL template or just passing the value. For example, like this:

include __DIR__ . ‘/get.php’;

It would seem that on js it will be enough for us to check the answer that the answer is not empty.

method : ‘post’,
dataType: ‘json’,
url : ajax.ajaxurl,
data : {
action : ‘some_action’,
success : function (response) {

if (response.length ! == 0) {

} else {


However, sometimes this leads to an error.

die () or die (0)may return not void or 0, and line with several blank characters in the first case and a string with several blank characters and zero in the other.

You can certainly put in die (‘end’) or die (0) and check in js for compliance through a search:

But this is more like a crutch. It’s better to do differently and write the following kind of output in the php method:

$ response[[‘success’] = ‘success’;
$ response[[‘message’] = ‘one of the message options’;

include __DIR__ . ‘/get.php’;
$ response[[‘content’] = ob_get_clean();

echo json_encode($ response);

Then on the JS side we can check if the response has a status success. And if it is present, then output one, and in its absence another.

if (response.success) {

div1.innerHTML = response.content;
div2.innerHTML = response.message;


Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *