Best way to separate PHP and Javascript code - javascript

Is there a best way to separate javascript and php code. for example:
//php code
if(condition1)
{
?>
// javascript code
$card_typej = $(this).val().trim();
if(condition2)
{
$("#id1").html('<?php echo($var1); ?>');
}
else
{
$("#id1").html('<?php echo($var2); ?>');
}
<?php
}
?>
If yes then, how to separate the above code?

First store required PHP variables in Javascript vars and then manipulate it.
<script>
var var2 = <?php echo json_encode($var2); ?>;
var var1 = <?php echo json_encode($var1); ?>;
if(condition1)
{
?>
// javascript code
$card_typej = $(this).val().trim();
if(condition2)
{
$("#id1").html(var1);
}
else
{
$("#id1").html(var2);
}
<?php
}
?>
</script>
You can see, complicated php+js code mixture is not there now.

Related

append PHP code to HTML input placeholder?

I want to append a PHP function that shows the user his/her IP within an inputs' placeholder. I've never seen anything like this been done before so I'd like to just see if it's possible or not.
My thoughts right now is to do something along these lines:
$('input').attr(placeholder,function(){
$('input').append('<?php $variable ?>');
});
then run the PHP code through here some how. If someone can shed some light on this I would be very grateful!
try this:
$('#inputID').attr("placeholder","<?php echo $variable; ?>");
And if you want to append to all inputs:
$(":input").attr("placeholder","<?php echo $variable; ?>");
should do the work
If you want to do it in PHP you can make a function to retrieve the IP of the user then echo the script in your page:
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
echo "<script type='text/javascript'>
$('input').attr(placeholder,function(){
$('input').append('".getUserIP()."');
});
</script>";
?>

PHP variable with a value of string is not equal in PHP variable with a value of html id from javascript?

This is my example code
<script>
var item = "yooow";
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
echo $str_html; //it will output "yooow"
?>
but...
when i'm trying to compare this into another php variable
<?php $str_php ="yooow";
if($str_html == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>
but it returns to false
how can they be an equal?
PHP is run serverside which means it's not aware of any changes you make in the DOM using Javascript.
<script>
var item = "yooow";
Value set only in clinet side, PHP don't know about changes here
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
WRONG, it will output "<p id="view"></p>"
echo $str_html; //it will output "yooow" ?>
<?php $str_php ="yooow";
Comparing "<p id="view"></p>" and "yoow" and that is not equal!
if($str_html == $str_php)
Better, you give the item value in cookie/session. And, compare the cookie value with $str_php.
<?php session_start(); ?>
<script>
$(document).ready(function(){
var item = "<?php echo $_SESSION['html']="yooow"; ?>";
$("#view").html(item);
});
</script>
<?php
$str_html = '<p id="view"></p>';
$strHtml=$_SESSION['html'];
$str_php ="yooow";
if($strHtml == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>

PHP isset variable than jquery and javascript should work

I want to know if my php variable does not exists, then I want to execute my javascript.
For example-
<?php
if(!isset($_REQUEST['myVar'])){
?>
<script>
alert('variable not exist');
</script>
<?php
}
?>
Is this right way to use javascript code in php extension file
I know all other answers solve your issue but i prefer it to do this way
<script>
<?php
$isset = !isset($_POST['myVar']) ? 'true' : 'false';
echo "var isset = $isset;";
?>
if(isset) {
alert('variable not exist');
}
</script>
when php render your page it will give this output
<script>
var isset = true;
if(isset) {
alert('variable not exist');
}
</script>
Do it like this and it will work:
if (!isset($_REQUEST['myVar'])) {
echo "<script>alert('variable not exist');</script>";
}
you can try writing this piece of code where you want the script to be placed:
<?php
if (!isset($_REQUEST['myVar'])) {
echo '<script>
alert("variable not exist");
</script>';
}
?>

How to know if a PHP variable is being retrieved by JavaScript?

I'm having some trouble in JS function for combobox. It functions well if there is a PHP variable being passed, but if there's nothing, the whole block of code doesn't work. I've tried using if(typeof(<?php echo json_encode($information['day']) ?>)!='undefined') but it still doesn't work. Is there another way on how to determine if the PHP variable is set or passed?
There are more ways to do this than I can think of. Here is one.
<script>
<?php if( isset($information) && isset($information['day']) ) { ?>
var myJson = <?php echo json_encode($information); ?>;
<?php } else { ?>
var myJson = null;
<?php } ?>
if(myJson != null) {
// do something
}
</script>
Change this line of code
if(typeof(<?php echo json_encode($information['day']) ?>)!='undefined')
to this
if(typeof("<?php echo json_encode($information['day']); ?>") != 'undefined')

How to pass PHP (index.php file ) Variable value to external JAVASCRIPT .js File?

Actually this code is wrote in index.php file but now i want to pass this javascript array value to external js file.
<?PHP
$qry2 = mysql_query("SELECT table_no FROM table_info");
while($res2 = mysql_fetch_array($qry2))
{
static $i = 0;
$i++;
$reg_table[$i] = $res2['table_no'];
}
?>
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
I want the bookedSeats variable to be in the external table.js file.
You have jQuery tag in there, so I am going to give you this... use Ajax:
test.php
<?php
// Handle Ajax Request
if (isset($_GET['loadData']))
{
// Query your db here, im building dummy data
$results = array();
for ($i = 0; $i < 10; $i++) {
$results[] = 'Data '. $i;
}
// Return Data
exit(json_encode($results));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
// Load Data Via Ajax
$.getJSON("test.php?loadData", function(bookedSeats)
{
console.log(bookedSeats);
});
</script>
When the page loads, we get the result like this:
<script>
var bookedSeats = new Array();
<?php foreach($reg_table as $key => $val)
{ ?>
bookedSeats.push('<?php echo $val; ?>');
<?php }?>
</script>
This can be greatly simplified and made immune to XSS:
<script>
var bookedSeats = <?php echo json_encode(array_values($reg_table)); ?>;
</script>
You can now refer to bookedSeats in your external .js file, but only if that file is being run after this inline script has been placed. In other words, putting:
<script src="external.js"></script>
after the <script>...<?php ... ?>...</script> is okay, but putting it before is only okay if you are deferring its execution - it's just safer to put it after ;)
I have an alternative solution for you eventually even if Latheesan Kanes's one is right.
Mine is just given as a trivial exemple if you have access to a constructor in your Javascript object in the table.js file.
<script>
var bookedSeats = new Array();
person=new Object();
<?php foreach($reg_table as $key => $val)
{
// here a javascript object
?>
person.firstname="John"; // of course replace firstname and John by your informations
<?php }?>
// then call table.js constructor
var objectInTableDotJS = new YourConstructor(person); // now in table.js you need to make modification :)

Categories