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?
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.
You can check it:
var op = <?php echo (isset($op) && $op) ? json_encode($op) : 'null'; ?>;
empty() is your best choice. http://php.net/manual/en/function.empty.php
var op = <?= !empty($op) ? json_encode($op) : '""' ?>;
Try like this :
var op = <?= isset($op) ? json_encode($op) : "" ?>;
Related
I need to get javascript variable value in php file.
html example:
UPDATE:
$html = '
<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
Shout I use regex ? regex is very complex to me... any help ?
<?php
$html = '<script>
window.runParams.adminSeq="3423423423423";
window.runParams.companyId="2349093284234";
</script>';
$variables = ["adminSeq", "companyId"];
$counter = 0;
foreach($variables as $variable) {
preg_match_all('/"(.*?)"/', $html, $matches);
${"$variable"} = ($matches[1])[$counter];
$counter++;
}
echo $adminSeq; // Prints out: 3423423423423
echo $companyId; // Prints out: 2349093284234
?>
You can also use GET requests to do this. The link would look like http://localhost/?adminSeq=3423423423423&companyId=2349093284234 then get out these values in PHP with:
<?php
$adminSeq = $_GET["adminSeq"];
$companyId = $_GET["companyId"];
?>
I fetch some information from DB - shown here:
$link = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handle = $link->prepare("SELECT dropAddress FROM mv_bookingEst WHERE userID='$userID'");
$handle->execute();
$result = $handle->fetchAll(\PDO::FETCH_OBJ);
//print_r($result);
$x = 0;
foreach($result as $obj){
$resultArray[$x] = $obj->dropAddress;
$x++;
}
and then in my javscript:
var count = "<?php echo json_encode($resultArray); ?>";
However I get the following error:
Syntax error: unexpected number -->
var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...
If I replace json_encode($resultArray) with echo ($resultArray[0]) the values pass fine. Not sure how to fix it because everything I've read uses this method. TIA
var count = "<?php echo json_encode($resultArray); ?>";
You are returning the result of the json_encode inside of a JavaScript string. Your syntax error shows this:
Syntax error: unexpected number --> var count = "["-33.8935642, 151.20227810000006","-33.857653, 151.20853699999998 ...
Unless there's a failure in coversion, json_encode returns valid JavaScript syntax, so you should just use it as-is without any adornments in your javascript:
var count = <?php echo json_encode($resultArray); ?>;
If you want to take into consideration the possibility of failure, then you can use this instead:
var count = <?php
$tmp = json_encode($resultArray);
echo ($tmp === false ? 'null' : $tmp);
?>;
I know this topic was already discussed a few times but I can't seem to find what I'm doing wrong.
What I'm trying to do:
The user types in a number and by clicking on the button creates a table with that number of columns.
Heres the php:
<?php
$twig = require_once('bootstrap.php');
$hostname = 'localhost';
$username = 'root';
$password = '';
$conn = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password);
echo $twig->render('index.html', array());
$numOfRows = 1;
if(isset($_POST['button'])){
$numOfRows = $_POST['num_input'];
}
html/javascript:
<html>
<head>
<script>
function insertRows(){
var numOfRows = <?php echo json_encode($numOfRows) ?>;
var out = "<table><tr><th>test</th>";
for (i = 0; i < numOfRows; i++){
out += "<th>test</th>";
}
out += "</tr></table>";
document.getElementById("table").innerHTML = out;
}
</script>
</head>
<body>
<form action="index.php" method="post">
<textarea id="num_input" name ="num_input"></textarea>
<button type="button" name="button" onclick="insertRows()"> Go </button>
</form>
<p id="table"></p>
</body>
</html>
Theres no error or anything since I'm not using a IDE, just doing it in vim but the error is that is just doesn't happen. If i change "numOfRows" in the for loop to a number it works, so I'm pretty sure the json_encode is the problem.
Thanks!
EDIT:
Just to test it, I used a string variable $str = "test"; the php file, and instead of using the for loop, I just edited javascript to
var str = <?php echo json_encode($str); ?>;
alert(str);
and I also tried
var str = <?php echo $str; ?>;
alert(str);
but nothing works.
json_encode is not necessary in this case.
Simply replace
var numOfRows = <?php echo json_encode($numOfRows); ?>;
with
var numOfRows = <?php echo (int)$numOfRows; ?>;
Edit: You are missing a ; on the
<?php echo json_encode($numOfRows) ?>
Should be
<?php echo json_encode($numOfRows);?>
And in these cases, if would be good to check the server log, this will automaticly make you better at finding these mistakes yourself.
You are mixing up ints and strings. The database will in PHP always return strings and the way you are using the variable as an int in a for loop.
The following change i believe would achieve the right result.
$numOfRows = intval($_POST['num_input']);
Where you use PHP's conversion to integer function there is at a global level.
You did not forget any $. JS does not need $ for variables.
As far as your json_encode is concerned, if you are just passing an integer from PHP to JS, there is no need to json_encode. Just pass the variable to JS as <?=$numOfRows?> in the JS source.
I'm attempting to make a comments system, and their comment gets posted in a div on submit. I need to set their username:
var session_username = <?php echo $_SESSION['username']; ?>;
var full = '<div> ...' + session_username + '...</div>';
$('#commentslice').prepend(full);
In the console it's saying:
Uncaught ReferenceError: [whatever the username is] is not defined.
Unless your PHP value (presumably a string) contains its own quotes, you should wrap it:
var session_username = "<?php echo $_SESSION['username']; ?>";
Let's say the username is "foo" and you haven't wrapped it. The replacement will come out to:
var session_username = foo;
which is a reference to the variable foo. If that's not defined (and usernames will likely be randomish strings that aren't in your code), you'll run into this error.
This won't change how the PHP behaves at all, it will still replace that snippet with the value of the session username. The JS, however, will see a string variable and treat it as a bit of text.
var session_username = "<?php echo $_SESSION['username']; ?>";
or
var session_username = <?php echo json_encode($_SESSION['username']); ?>;
I don't understand why replace() function doesn't work into my jQuery function:
jQuery(document).ready(function($){
var amount_min = <?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo '0'; ?>;
var amount_min = amount_min.replace(/[^\d]/g, "");
$('input[name=amount]').val(amount_min);
});
Whatever input I give (for example "100ab" or "10.000") it doesn't replace it with "100" or "10000".
How to do?
You forgot to put double-quotes.
var amount_min = "<?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo 0; ?>";
Because, replace works in Strings.
UPDATE #1
If for any religious reason you don't want to wrap the PHP in double quotes then output them along with the number.
var amount_min = <?php echo '"' . ($_GET['amount_min'] ? $_GET['amount_min'] : 0) . '"'; ?>;
UPDATE #2
Compulsory validation you can use:
var amount_min = <?php echo '"' . (int)($_GET['amount_min']) . '"'; ?>;
can you please try this:
$(document).ready(function(){
var amount_min = "<?php if($_GET['amount_min']){ echo $_GET['amount_min'];}else{ echo '0';} ?>";
console.log("original-> "+amount_min);
var amount_min = amount_min.replace(/\D/g,'');
console.log("replaced-> "+amount_min);
});
Your PHP code is outputting a number:
var amount_min = 100;
Since you're expecting a string, wrap it in quotes:
var amount_min = "<?php if($_GET['amount_min']) echo $_GET['amount_min']; else echo '0'; ?>";
I haven't touched PHP in years, but I think you could simplify your code a little:
var amount_min = "<?php echo($_GET['amount_min'] || '0'); ?>";
Also, why don't you just fetch the GET parameter with JavaScript?
You don't need the .replace() code (it also only works on strings); PHP can already do the proper conversion for you:
$(function() {
var amount_min = <?php echo isset($_GET['amount_min']) ? (int)$_GET['amount_min'] : 0; ?>;
$('input[name=amount]').val(amount_min);
});
You could also use filtering for this:
<?php echo filter_input(INPUT_GET, 'amount_min', FILTER_VALIDATE_INT, array('options' => array('default' => 0))); ?>
Note that filter_input would not accept a value like 100abc, so use wisely.
If you still want to use strings safely in JavaScript you should use json_encode().
Btw, any answer that involves an unmodified echo of a request variable from PHP inside JavaScript code is wrong and can cause XSS attacks! You have been warned.
Update
The regular expression based replacement can also be done in PHP:
var amount_min = <?php echo (int)preg_replace('/\D+/', '', isset($_GET['amount_min']) ? $_GET['amount_min'] : 0); ?>;
Since all non-digits are removed, you can safely apply the (int) cast.