php if inside javascript - php

I am trying to use the bootstrap typehead plugin.
The idea is:
I have a Manufacturer Option
I Have a Model Option
Only once the Manufacturer option is selected, the model option is enabled.
The model option is filtered by manufacturers.
CakePHP Controller is sending me a 'findall' array of both Manufacturer and Models (Which I call Variety instead of Model for naming convention)
model_source = [];
$('#manufacturer').typeahead({
source: [
<?php
foreach($manufacturers as $manufacturer):
if($manufacturer['Manufacturer']['bow'] == true):
?>
"<?php echo $manufacturer['Manufacturer']['manufacturer']; ?>",
<?php
endif;
endforeach;
?>
]
});
$('#manufacturer').live("change", function(){
if($(this).val()){
$('#model').attr('disabled', false);
manufacturer = $(this).val();
<?php
foreach($varieties as $model):
if($model['Variety']['bow'] == true):
?>
model_source.push("<?php if($model['Variety']['manufacturer_id'] == "+manufacturer+"){echo $model['Variety']['model'];}else{ continue; } ?>");
<?php
endif;
endforeach;
?>
}else{
$('#model').attr('disabled', true);
}
});
The problem I am having is where I try to do
model_source.push("<?php if($model['Variety']['manufacturer_id'] == "+manufacturer+"){echo $model['Variety']['model'];}else{ continue; } ?>");
If I hardcode the manufacturer variable to be all in one line of PHP then it works (without the else statement, that is also giving me problems I get an ILEGAL error on my console)
Any idea in why when I concatenate the php string with the javascript variable it then doesn't work?!
http://jsfiddle.net/mmoscosa/Y6hEA/
Thank you!

Your javascript variable happens to be between <?php ?> tags. You can't use javascript manufacturer variable in your if statement. PHP is server side, JavaScript is client side.

Related

Trying to use [] to get value of parameter

I'm trying to get the value of some URL parameters in PHP and can't seem to get [] to detect this in the URL.
This works:
<?php if ($params['sms_banner'] === 'true') { ?><div id="sms-banner-legacy"> SMS Banner </div><?php } ?>
This doesn't work:
<?php if ($params['payday[sms_banner]'] === 'true') { ?><div id="sms-banner-legacy"> Legacy SMS Banner </div><?php } ?>
When I go to http://someurl.com/page?payday[sms_banner]=true it should then show the <div> on the page, but instead it can't pick up the value.
As you are passing array in url, you can get the value of same using
$_GET['payday']['sms_banner']
php translates that syntax to an array key value, try $_GET['payday']['sms_banner'] or params['payday']['sms_banner'] in your case.

Best way for form action?

I just started using Code Igniter framework and also just started learning on PHP OOP. I came across something when coding for the forms.
In a form if I have two buttons that would lead to different pages, what would be the most suitable way to do it? I found two ways. The first is to have a dynamic action/link, let's call it method A:
Method A
Variable $form_link is 'form_link'.
(View) main_user_view.php
<?php echo form_open($form_link); ?>
<?php echo form_button($add_user_button); ?>
<?php echo form_button($delete_user_button); ?>
<?php echo form_close(); ?>
(Controller) User.php
public function form_link()
{
// Value of button clicked
$form_submitted = $this->input->post('submit_form');
if($form_submitted == 'add_user')
{
redirect('User/add_user');
}
elseif($form_submitted == 'delete_user')
{
redirect('User/delete_user');
}
elseif($form_submitted == 'back')
{
redirect('User');
}
}
And the other way is instead of having a second button I would use an anchor and make an absolute path for it.
Method B
Variable $form_link is 'add_user' which is a function in the controller.
(View) main_user_view.php
<?php echo form_open($form_link); ?>
<?php echo form_button($add_user_button); ?>
<?php echo anchor('add_delete_user/delete_users_view', 'Delete', array('class'=>'btn btn-info', 'role'=>'button'));?>
<?php echo form_close(); ?>
The only problem I have with method A is that if in the form I have input fields, I cannot get the data through POST as redirect does not carry over the data to other functions. I resolved that by using method B where the anchor would lead to the function I want whereby I can get the POST data.
So my main question is, should I use method B instead whenever I have two or more buttons in a form?
You have to use button names for form post actions,
public function form_link()
{
if($this->input->post('add_user'))
{
redirect('User/add_user');
}
if($this->input->post('delete_user'))
{
redirect('User/delete_user');
}
}
What my opinion is also to use the Method B. To make the URL more nicer you can use custom routing (which is located at 'application/config/routes.php')

PHP Show menus/submenus according to the value of a variable

I have a navigation bar in which I am trying to show menus/buttons, according to the type of user. I get the type of user via a variable called $isManager.
The good news is that it works on every browser, except firefox.
Code looks like this:
<?php
if ($isManager === '2'){
?>
<li>View</li>
<?php
}
?>
Can you suggest an alternative to this, or is Firefox somehow ignoring or not accepting the true condition here ?
When you use ===, it is for strict checking. So make sure that your$isManager is string type. If it is integer then try
<?php
if ($isManager === 2){
?>
<li>View</li>
<?php
}
?>
You are Using === it means you want to check by its typeof too.
and after that you wrote '2', so it will missmatch the results and not going to the condition, instead try the following.
<?php
if ($isManager === 2){
?>
<li>View</li>
<?php
}
?>

Enable/disable div according to guest/user entrance using php and jquery

I want to enable or disable a div according to the session if it starts with an user or a guest. I want to do something like this:
First, i will evaluate if it is user or not by doing this:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
?>
then in jquery, i would like to say:
$('.box').click(function(){ // labBox appears when box is clicked
if(<?php $guest?>)
$("#LabBox").hide();
else
$("#LabBox").show();
});
Question: how can i use my php boolean var $guest to disable or hide some elements of my website?
Do i have to do two distinct php files? one for users and other for guest (e.g, home.php and home_guest.php)?
you could do the alternative such as
<script>
var guest = '<?php echo $guest; ?>';
$('.box').click(function(){ // labBox appears when box is clicked
if(guest === "true") {
$("#LabBox").hide();
} else {
$("#LabBox").show();
}
});
</script>
This would simply allow you to pass the PHP value to a Javascript variable, in order for you to use it within the onClick.
Remember: everything that reaches the client can be manipulated. Therefore, if you send an hidden element (say, an hidden <div>) any tech-savvy user can, and will, easily make them visible.
You MUST perform the checks about the login/guest status in your PHP script, and don't rely on jQuery to assemble the page at client side (hey, after all, the user may have disabled javascript altogether!)
You don't need two pages (eg: home.php and home_guest.php) to render different content based on the user level. Just use appropriately session/cookies and different echos.
Use a hidden input, populated by PHP, which jQuery can grab:
<?php
echo "<input type=hidden id=guestcheck value=$guest/>"
?>
if ("#guestcheck").val()) {
}
I personally like this method because it allows me to check the source when debugging to find out where any errors may be (for instance you can plainly see in the source when viewing the page whether or not GUEST is true)
It depends on contents of those files. If the only difference is visibility of the block, it's more reasonable to do the check inline.
<?php if (isset($_SESSION['idUser'])) { ?>
$('.box').click(function() { $("#LabBox").show(); }
<?php } ?>
Personally I would do it in the HTML rather than the JS file...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$loggedin=true;
} else {
$loggedin=false;
}
?>
Then later on..
<?php if($loggedin===true){?>
<div>User is logged in</div>
<?php }else{?>
<div>Guest is viewing page</div>
<?php }?>
This means that the div for the user is not shown to the guest, whereas your currently solution only hides it from view (user could just use firebug/viewsource!
Why don't you just show/hide your div in the php depended on if they are a guest or not...
So...
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
}
if($guest===true){
echo "<div></div>";
}
else{
//dont echo div
}
?>
PHP / server-side:
<?php
if(!isset($_SESSION['idUser'])) // If it is Guest doesn't have id.
{
$guest=true;
} else {
$guest=false;
// add #LabBox element from here to avoid junk/hidden elements for guests
}
?>
JQuery / client-side:
$('.box').click(function(){ // labBox appears when box is clicked
if (!<?php echo $guest?> && $('#LabBox').length > 0) {
$('#LabBox').show();
}
});
Then it is critical that any action requested by the user pass the "guest or not?" test before being granted from the server-side.

show hide div based on mysql table row value

hi guys im trying to show and hide div according to mysql value but i couldnt do it can you help me what im doing wrong
here is my code thanks a lot for your ideas
var Value = <?php echo json_encode($valuek) ?>;
if (Value==1){
$('#show_hide').show();
}
else{
$('#show_hide').hide();
}
<?php
$valuek = $session->userinfo['vcc'];
?>
<div id="show_hide">
some code
</div>
<?php echo json_encode($valuek) ?>
will return a json string, instead try just using "echo"
<?php echo $valuek ?>
If all you are going for is a boolean value then there is simply no need for JSON.
Echo the value directly into the JavaScript. Remember to ensure you are passing a valid boolean value.
PHP code -
<?php
$showDiv = ($dbValue == 1? 'true' : 'false');
?>
JavaScript + PHP injection -
<script>
var value = '<?php echo $showDiv; ?>';
<script>
Don't forget to wrap the PHP injected value with quotes.
$valuek = $session->userinfo['vcc'];
I'm not sure if you have the code in this order in your php file, or just showed pieces of code in this order, but Should go BEFORE your js code. It has no value when js code is run.
To see what $valuek is, just echo it on top of the screen
<?php echo "<h1>$valuek</h1>" ?>.
Or just look at the source - at your js function, to see what is printed after 'var Value ='
That's the main thing really - to make sure that you getting what you expect from session.
And as been said, you don't need jason_encode, but you do need a semi-colon after echo command.
Also, I hope your jquery code is within $(document).ready function, not as is.

Categories