Tomas Lucena
Tomas Lucena

Reputation: 1526

Javascript check if PHP variable is defined or not

I can not find an answer to my problem and I am also not sure if this is possible or not.

Is there any way to check if a PHP variable is defined or not with javascript?

This is an example:

var op = <?PHP echo json_encode($op); ?>;

if $op is not defined I got an error in javascript:

Events:362 Uncaught SyntaxError: Unexpected token )

I understand this is normal because this variable does not exist in PHP. But there is a way to avoid the error if the variable does not exist?

Upvotes: 3

Views: 6156

Answers (4)

lalithkumar
lalithkumar

Reputation: 3540

Try like this :

var op = <?= isset($op) ? json_encode($op) : "" ?>;

Upvotes: 0

CodeGodie
CodeGodie

Reputation: 12132

empty() is your best choice. http://php.net/manual/en/function.empty.php

var op = <?= !empty($op) ? json_encode($op) : '""' ?>;

Upvotes: 2

Enstage
Enstage

Reputation: 2126

Change:

var op = <?PHP echo json_encode($op); ?>;

To:

var op = <?PHP echo (!empty($op) ? json_encode($op) : '""'); ?>;

PHP is executed on the server, before the response is even sent to the user. Javascript is executed on the browser, once the user receives the response. So "communicating" in the way you describe is not possible. Just test in PHP if $op is empty, and output accordingly.

Upvotes: 9

Mohammad Hamedani
Mohammad Hamedani

Reputation: 3354

You can check it:

var op = <?php echo (isset($op) && $op) ? json_encode($op) : 'null'; ?>;

Upvotes: 2

Related Questions