Cakephp 2.x - hide/show a combobox - javascript

I try to hide/show a combobox, I have 2 combobox and I want the second to be hidden until the first change.
<?php echo $this->Form->input('combobox1'); ?>
<?php echo $this->Form->input('combobox2'); ?>
So I think I need to do something like :
$this->Js->get('#idcombobox2')->effect('hide'); to hide the combobox when the page just load.
And something like :
$this->Js->get('#idcombo1')->event('change', $this->Js->get('#idcombobox2')->effect('show')); cause if the first change I want to show the second.
but this doesn't work.
thanks for your help.

are you including jquery or other framework in the view?
echo $this->Html->script('//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js');
and in case you're outputting it into the <head> with array('inline' => false), make sure to specify the script location in the layout:
echo $scripts_for_layout;
remember you also need to output the buffer in the view:
echo $this->Js->writeBuffer();
edit: the code that actually worked for me:
$event = $this->Js->get('#combo2')->effect('show');
$this->Js->get('#combo1')->event('change', $event);
edit 2: somehow i just got to hide the combo2 using a scriptBlock. so the whole code would go like this
$hide = $this->Js->get('#combo2')->effect('hide');
echo $this->Html->scriptBlock($this->Js->domReady($hide));
$show = $this->Js->get('#combo2')->effect('show');
$this->Js->get('#combo1')->event('change', $show);
echo $this->Js->writeBuffer(array('inline' => false));

Related

PHP get information from database when echoed html code is clicked

In my code, I am retrieving data from the database using a while loop so i can have all the $FormData['fullname'] in the db.
What i want to do is, have each name display on the page and also have clickable so when someone clicks a name, it gets their user_id and pulls up information about them.
The problem i am having is that I can't figure out a way to make a it so where i can get the user_id when the user clicks a name. I tried putting a "name" in the button attribute and I checked if isset() but that didn't work.
If someone can properly figure out a way for me to basically, display all the fullnames in my database and when someone clicks a name, it pulls up information about them that is stored in the database. Here is my code
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch()){
echo "<button name='name'>$formData[fullname]</button>";
if($_SERVER['REQUEST_METHOD'] =="POST"){
if(isset($_POST['name'])){
echo "ok";
}else{
echo "bad";
}
}
}
As far i can see you are trying hit a button inside the while loop , i would not say its a bad approach , but i will suggest you not to do that . and from your code i can see you have lack of understanding post and get request learn from here . and other than this you need to know the transition of web url . how its actually works . anyway , i have given a sample code without . i hope it will help you understanding this concept.
$stmtGet = $handler->prepare("SELECT * FROM formdata");
$stmtGet->execute();
while($formData = $stmtGet->fetch(PDO::FETCH_ASSOC)){
$id = $formData['formdataid'];
echo "<a href='somepagename.php?infoid={$id}'>". $formData['fullname']."</a></br>";
}
now in the somepagename.php file or in the same page you can actually show the details information for instance
if(isset($_GET['infoid'])){
$stmt = $handler->prepare("select * from formdata where formdataid='"$_GET['infoid']"'");
$qry = $stmt->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
echo "<p>id =".$row['formdataid']."</p></br>";
echo "<p>id =".$row['name']."</p></br>";
echo "<p>id =".$row['email']."</p></br>";
echo "<p>id =".$row['address']."</p></br>";
code is not executed , it may have semicolon or comma error warning . you have to fix those on your own . this example above shown you only the way it works .
if still you have problem ask , or see the documentation
I should stress that this is not production code and you should totally validate the data input coming in before posting queries to your DB. You can do something like this.
<?php
// Connect
$connection = mysqli_connect('localhost', 'username', 'password', 'database','port');
// Grab all users
$sql = 'SELECT * FROM users';
$users = mysqli_query($connection, $sql);
if (($_SERVER['REQUEST_METHOD'] == 'POST') && !empty($_POST['user_id'])) {
$query = "SELECT * FROM users WHERE user_id = {$_POST['user_id']};";
$user = mysqli_fetch_assoc(mysqli_query($connection, $query));
}
?>
// This only runs if our $user variable is set.
<?php if (isset($user)) : ?>
<?php foreach ($user as $key => $value) : ?>
<span><?= print_r($value) ?></span>
<?php endforeach; ?>
<?php endif; ?>
// Display all users in a dropdown and when the button is clicked
// submit it via post to this page.
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select name="user_id">
<?php foreach ($users as $user) : ?>
<option value="<?= $user['user_id'] ?>"><?= $user['name'] ?></option>
<?php endforeach; ?>
</select>
<button type="submit">Submit</button>
</form>
This is going to refresh your page every time. If you want to have an interactive page you are going to need to use JavaScript/AJAX to update the page elements without reloading the page. This example just demonstrates how you can achieve this with PHP and HTML.
you need to know about server-side language(php) and client-side language(javascript).
php runs before page loaded. it cannot runs when click something by itself(with ajax, it can).
most interactions without page move runs with javascript.
in your case, there are two methods.
store all information into hidden input or button's attribute. and get them by user_id via javascript.
use ajax to call another php that can select informations you need by user_id.
both use javascript or jquery. so you must learn about them.

JQuery Data attributes getting stripped out in Kohana ajax

I'm working on an app where they have gone with jquery data to pass variables to html
it works in one aspect of the site when the data attributes are attached to a tr tag. This code works
<tr class="js-instructions-row documents__table-row
<?=$ix.'row';?><?php //$ix==0 ? 'documents__table-row--active' : '' ?>"
data-product-title="<?= $sheet->name ?>"
data-instructions-image="<?= $serverpath.$thisImage ?>"
data-instructions-file="<?= $serverpath.'Instructions/'.$sheet->file ?>"
>
when I try to put those attributes on a select tag or option tag in another view, it doesn't come through. This code doesn't work.
<?php
foreach($instructions as $ix => $sheet) {
$thisImage = ($sheet->image?$sheet->image:'Image_holder_thumb.png');
?>
<option test="" data-product-title="<?= $sheet->name ?>" data-instructions-image="<?= Kohana::$config->load('aws.s3-baseurl-www-customercare').$thisImage ?>" data-instructions-file="<?= Kohana::$config->load('aws.s3-baseurl-www-customercare').'Instructions/'.$sheet->file ?>" value="<?=$sheet->id?>"><?=$sheet->name?></option>
<?php
}
?>
and offending javascript:
$('.js-product-selector').on('change',function(e){
var selected = $(this).find('option:selected');
console.log(selected.attr('value'))
console.log(selected.data('product-title'));
$(".documents__product-title").text(selected.data('product-title'));
$(".documents__preview img").attr('src',selected.data('instructions-image'));
$(".documents__download").attr('href',selected.data('instructions-file'));
});
value attribute comes through just fine in the log but data-product-title does not
here is how my view is called in the Controller.
$this->response->body(View::factory($this->folder."/instruction-sheets")->set('brands',ORM::factory('Brand')->with('Customercare_Instruction')->find_all())->set('postbrand',$brand));
The view that works is nested inside of a view that is called like this:
$this->page=View::factory($this->folder.'/index');
$this->page->breadcrumb = 'Instruction Sheets';
$this->page->content = View::factory($this->folder."/instruction-sheets")->set('brands',ORM::factory('Brand')->with('Customercare_Instruction')->find_all());
and the sub-view is called like this
<?= View::factory('customer-care/instruction-sheets-filtered')->set('instructions',$instructions)->render() ?>
I appreciate your input.
You wouldn't by any chance be styling your select element with something like Selectize or Select2, would you? That's probably what's stripping the data attributes from your options.

How do I embed Javascript in PHP code?

I have a HTML form and PHP code. In my form, I have a textbox and a textarea. Within both, I have included the "disabled" option. I want both textboxes to remain disabled until the user decides to click the "Edit" button, in which case both textboxes should be enabled so changes can be made and the output once again saved. According to the research I have done, the only way to do this is to use javascript, so I have included the following code within my PHP;
if (isset($_POST['edit']))
{
echo "<script type=\"text/javascript\">";
echo "var oldnotes = document.getElementById('oldnotes');";
echo "oldnotes.disabled = false;";
echo "var record = document.getElementById('record');";
echo "record.disabled = false;";
echo "</script>";
}
I have also tried;
if (isset($_POST['edit']))
{
echo "<script type=\"text/javascript\">";
echo "$('#oldnotes').removeAttr('disabled')";
echo "$('#record').removeAttr('disabled')";
echo "</script>";
}
But no luck :(
I am not receiving any errors, the textboxes just remain disabled after I click the Edit button. Could anyone help me with this? Thanks in advance.
This is a better approach for these kind of problems :
if (isset($_POST['edit'])){
?>
<script type="text/javascript">
var oldnotes = document.getElementById('oldnotes');
oldnotes.disabled = '';
var record = document.getElementById('record');
record.disabled = '';
</script>
<?php
}
<?
<script language='javascript'>
(javascript code here)
</script>
?>
Try use onclick on your Button
<input type="button" name="edit" id="edit" onclick="document.getElementById('oldnotes').disabled=false; document.getElementById('record').disabled=false; return false;">
I hope it helps.
The second approach seems correct, but you're missing ; there. Also, you haven't put any newline characters.
Here's what I suggest:
<?php
if (isset($_POST['edit'])) {
?>
<script type="text/javascript">
alert("Check entry"); // Use this for checking if your script is reaching here or not
$('#oldnotes, #record').removeAttr('disabled');
</script>
<?php
}
?>
You don't need to echo the whole thing. You can simply put it out of the PHP and keep it inside a if block.
Also, I've kept the alert to check if your code structure is proper. If you're getting the alert on clicking the edit button, means you're on the right path. You just need to workout on the JS.
If not, something wrong with your edit button and the form POST
Use single quotes for script type
echo "<script type='text/javascript'>\n";
//javascript goes here
echo "</script>";
use this jquery code:
<script>
$('#oldnotes,#record').attr('disabled','')
</script>
If you want to use JS with PHP you can read here:
how to write javascript code inside php
However: it seems you want the JS to be called on it own accord upon evaluation in the php logic as per the implementation provided.
Technically speaking your JS simply states it should re-enable the controls. Rather add the JS functionality to the OnClick of the submitting control and it should work fine. This is a quicker way of testing the functionality as well.
<a href="javascript:void(0);" onclick="document.getElementById('oldnotes').disabled=false;" >
Once it is clicked it will hide the appropriate control instead of trying to write new JS on the fly that is not executed. This is tried and tested and should work fine for you.
Hope it helps!
you can always make a cookie
use document.cookie()
set the onclick=“” to changing the cookie
and make a script that runs and gets the cookie when you open the site (use window.onload = function(){/*code goes here*/})

Changing URL and retaining values on dropdown onChange event

I have created a Magento site that has Japanese and English store. For both of these stores, I have almost the same products. I just added additional attributes to add the english texts where necessary such as the name. So for example, in my Japanese store, the product's name is "靴" then in English store it's "Shoes". Given this, I have to make adjustments to my url and breadcrumbs to accommodate both languages.
Anyway, I added a currency selector for my English store which works perfectly. The only problem I'm having with it is that it reloads my page completely and the changes I made in the url and breadcrumbs disappear and goes back to default. My url and breadcrumbs should look like this in the English store:
url: http://mywebsite.com/mycategory/shoes.html?cat=mycategory&prod=shoes
breadcrumbs: Home > My Category > Shoes
But whenever I try to change the currency, it reloads my page and I end up with this url and breadcrumb:
url: http://mywebsite.com/mycategory/shoes.html
breadcrumbs: Home > My Category > 靴
The code for my currency dropdown looks like so:
<?php $_product = Mage::registry('current_product');
$root = Mage::app()->getStore()->getRootCategoryId();
//UPDATE:
$currency = Mage::app()->getRequest()->getParam('currency');
Mage::app()->getStore()->setCurrentCurrencyCode($currency);
//if I try to echo these two, it both returns the correct current currency
$cats = $_product->getCategoryCollection()
->addAttributeToSelect('name')
->addAttributeToFilter('parent_id', $root);
foreach($cats as $_cat):
$cat_name = $_cat->getName();
endforeach;
//UPDATE:
$productUrl = $_product->getProductUrl."?cat=".urlencode($cat_name)."&prodname=".urlencode($_product->getName_en());
if($this->getCurrencyCount() > 1): ?>
<label for="custom-currency-selector"><?php echo $this->__('Select Currency:') ?></label>
//UPDATE: changed window.location.href to setLocation
<select onchange="setLocation('<?php echo $productUrl ?>' + '&currency=' + this.value") name="custom-currency-selector" id="custom-currency-selector">
<?php foreach ($this->getCurrencies() as $_code => $_name): ?>
//UPDATE: option value
//if I echo $this->getCurrentCurrencyCode(), its value is different from the current. It returns the previously selected currency
<option value="<?php echo $_code; ?>"
<?php if($_code == $this->getCurrentCurrencyCode()): ?>
selected="SELECTED"
<?php endif; ?>>
<?php echo $_code ?>
</option>
<?php endforeach; ?>
</select>
<?php endif; ?>
I tried changing the onchange event value to window.location.href=this.value+'' but that isn't working at all. My url is not retained. So my question is, how can I change the currency while retaining the changes I created for my url and breadcrumbs?
Update:
As per Natalie's suggestion, I've changed $this->getSwitchCurrencyUrl($_code) to simply $_code and made some more change to my currency.phtml to accommodate my needs. I am now able to retain my url params and change the currency. The problem now is that even though I am able to set the currency programmatically, the select option and currency would not change immediately. For example if my current currency is $ and I try to change to JPY, what happens is it remains $ then for the second time, I select EUR, JPY currency is used instead then the next currency used would be EUR. Basically, my code seems to get the previously selected currency instead of the current one. Why is this happening and how can I fix this?
Are you using Magentos default language/store switcher? If you do, have you created different category names for the Japanese and the English store view? Because then this shouldn't be an issue, magento will save the language/store choice in cookie and then show the categories connected to that store.
Edit: I'm going to add this here instead because a comment is too short:
Sorry. I missed that you hade trouble with adding the params to the original value. You could do what I did when I wanted to change store view and currency on the same button click.
You can set the currency manually yourself instead. If you change the value of the currency dropdown to only contain the currency code like this:
<option value="<?php echo $_code?>" ...
And instead of going to this.value go to the following url on change
onchange="setLocation('?cat=mycategory&prod=shoes&currency='+this.value)"
At the top of your header.phtml file add the following to get the currency param and set the new currency.
if($currency = Mage::app()->getRequest()->getParam('currency')){
Mage::app()->getStore()->setCurrentCurrencyCode($currency);
}
I haven't tested this exact code so I can't guarantee it will work perfectly. But I have myself done a version of it that works great.

JQuery custom alert box dosnt run automatically

I'm using a jquery alert library named Apprise2, it works fine when im using it for alerts in my form validation function. all i want is to show alert on page load, i call it at the end of the page, but it dont work, this is what i use at the end of page :
<?php if ($_SESSION['lasterror'] == '1') {?>
<script>
Apprise('error-occured');
</script>
<?php } ?>
when im using "alert" instead of "apprise" it works and shows the alert, i linked to the library bellow and i hope you can help me with this problem. thanks and sorry for my english.
You can try to do this in doc ready handler:
<?php if ($_SESSION['lasterror'] == '1') {?>
<script>
$(function(){
Apprise('error-occured');
});
</script>
<?php } ?>
Point 2: this might be the issue:
You are testing a string which might be a number here:
<?php if ($_SESSION['lasterror'] == '1') {?>
//-----------------------------------^-------here

Categories