Changing URL and retaining values on dropdown onChange event - javascript

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.

Related

How to use JS to hold a variable from a PHP form before submit

I'm quite new to PHP so apologies for not being fully aware of code structures.
In a PHP file I have a form with the options in a drop-down menu being populated from a database query (how many rounds for a tournament based on the number of entrants). Once a user has selected an option for the round of fixtures they want to view that option gets passed as a variable to determine what to display on form submit. On form submit the rest of the page changes to display the fixtures from the database that relate to the Round that the user selected from the drop-down.
My challenge is that after selecting the Round number from the drop-down menu I have to click the submit button twice - once to assign the variable and then the second press of submit to be able to use the variable as part of the process to display the fixture information from the database.
I'm aware that it is possible to use JS to store a variable that can then be used on form submit but I'm not sure how to integrate it with the way the form / has been written.
After looking at a few places on the web (like W3Schools) I've got some basic JS and have tried that but I think there's still a disconnect between the user selecting and storing the variable ready to be used when the submit is clicked.
//Basic JS
<script>
function getFormIndex() {
document.getElementById($_POST['roundselect']).innerHTML =
document.getElementById("roundselect").selectedIndex;
}
</script>
//PHP Elements
if(isset($_POST['submit'])){
$roundnum = $_POST['roundselect']; }
<?php
function setround(){
$roundnum = $_POST['roundselect'];
echo $roundnum;
}
?>
//Form
<div class="h2_select">
<? if($fnum) {
$select_opt = (isset($_GET['round'])) ? $_GET['round'] : 1;
?>
<form method="post" action="/tournaments/<?=$lid; ?>/fixtures/<?= $roundnum; ?>" name="rf">
<!--<input type="hidden" name="id" value="/<?=$lid; ?>" />
<input type="hidden" name="page" value="/fixtures" /> -->
<span class="minput">Select Round
<select size=1 class="mselect" name="roundselect" onChange=getFormIndex();>
<? for($i=1; $i <= $total_rounds; $i++) { ?>
<option value="<?= $i ?>" <?php if($i == $select_opt){ echo 'selected'; } ?> > <?= $i?> </option>
<? }
?>
</select>
<input type="submit" name="submit" value="<?= $lang[185] ?>" class="minput"/>
</form>
<? } ?>
</div>
To confirm, the form works and displays the correct information. The problem is that I currently need to click "submit" twice.
Thanks
Good start, I would do it with a bit of AJAX that allows us to send a request and receive an answer "in the background" - so that first time user changes the select I would fetch data from backend in the background and display it without double-submitting needed.
Please check this thread - I think it is illustrating the same thing;
How to Submit Form on Select Change
It is based on JQuery and I think it is a good start for new developers.
But - if you do not want to use a framework and does not care for older browsers you can just use "vanilla" Javascript with Fetch (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) and onchange https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event
Fetch returns the result so then you have to pass it back to the website.
It is very easy to do so with :
1. set a div on your page and add a unique ID to it (like )
2. use document.getElementById("result").innerHTML = resultFromFetch;
So:
listen to onchange on select
fetch from backend when select changes
display fetch result
AJAX is really neat and very good for the user experience as it allows us to get the data asynchronously and in the "back stage" of our application. But then it is a good user experience measure to show also some "please wait" indications and also make sure to show some potential errors (the connection can go "down" when waiting for results and then it is wise to show errors to users instead of them waiting forever).
Hope this helps to point you in a new and exiting direction.

Dynamic populating the drop down list based on the button clicked

I am working on a small project where I am trying to change the drop down list option based on the button that is clicked.
Its sort of like populating the list based on the value of the first list that I is listed here https://www.plus2net.com/php_tutorial/php_drop_down_list.php
However currently I have my select list displayed using php and html. I make a call to my table in the tags above my page and then display the information.
<?php
$selList = array();
$query= $dbh->query("SELECT * from CarsShop order by dtDroppedOff");
foreach ( $query->fetchAll(PDO::FETCH_ASSOC) as $row ) {
$selList [] = array('carID'=> $row['carID'], 'vin'=> $row['CarVIN']);
}
?>
<select name="carLst" id="carLst" onClick="retrieveCarInfo(this.getSelected().getProperty('value'));" size="5" >
<option>List of cars...</option>
<?php foreach ($selList as $entry) { ?>
<option value="<?php echo $entry['carID']; ?>"><?php echo $entry['vin']; ?></option>
<?php }?>
</select>
However I want to add two buttons..one to display all cars that are ready for pickup and those who are not. I have a simple 1 or 0 in my table and I can pull information like that. However how could I toggle back and forth when clicking the buttons. My select list would have to populate each time i click the corresponding button.
Now I am aware I can make a JSON call as an onclick() and request this information and assign it on the onSuccess callback, but is there any way of doing this like how I already have it?

Select data from mysql with php, display in html dropdown list and insert selected value as URL parameter via javascript

First, please understand I have just begun to learn php, javascript and ajax in the past 10 days so I will need some hand-holding and step-by-step examples and guidance. I've carefully read the courses for those topics at w3schools and found them very helpful; as a result, I was able to write some basic code for my project by using their examples and other snippets I've found here and other sites.
This post is a little lengthy so I can explain my ultimate goal for this code and what I've already tried.
I have started writing a piece of very complex code that has multiple parts, but the final result will be a dropdown selection list with an image thumbnail button of the main_image of that page linked to an external URL which is dynamically created based on the user's dropdown list selection.
This is my project:
I am building a website with Joomla 3.x.x, Bootstrap 3 and j2store (with other components and modules) that features photos for sale as digital images and that can be applied to physical products (canvas prints, t-shirts, coffee mugs, etc). Those physical products exist on a 3rd party website (Zazzle) which are embedded into my private website with Zazzle's RSS feed and another 3rd party javascript code (to embed Zazzle RSS feed grid displays into my website).
The Zazzle API allows my users to choose any image from my private website and apply that image to any product available in Zazzle's marketplace.
My users would ultimately select a category of products from a dropdown list on my website and then click a button that would open a new window to connect to the Zazzle marketplace which would display a grid of relevant physical products featuring the image shown on the active page of my website where the user clicked the button.
For example, the user starts by looking at the page on my website with the main_image "Light Purple African Daisy", chooses a category of electronic products from a dropdown list and then clicks the "Design Your Own Gifts" button which opens a new window, connects to the Zazzle marketplace and displays a grid of electronic products showing the "Light Purple African Daisy" image on the user's chosen products.
The URL behind the "Design Your Own Gifts" button needs to be created dynamically with the selected value after the user chooses a category of products from a dropdown list on my website.
This is the Zazzle API I need to use:
https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg= <DYNAMIC CATEGORY ID FROM DROPDOWN SELECTION LIST> &t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid= <URLENCODED DYNAMIC PATH OF ACTIVE PAGE MAIN_IMAGE>"
I have created 2 tables in mysql database that hold the Names, Category IDs and Department IDs for the products in my Zazzle marketplace. I am also getting the main_image path from my j2store productimages table.
The code I have been able to write so far accomplishes the following tasks:
Connect to the database
Choose Columns/Tables
GET Data from Columns/Tables
Create HTML Form to Display Result of MYSQL Query
Create Dropdown Selection List of Query Results
Echo encoded URL with Zazzle API concatenated with Parameters/Dynamic Values
This is my code so far:
<div class="form-group" style="margin: 30px 10%;">
<h3>Create Zazzle Products</h3><p><h4>Select a Template Category</h4>
<form name="create-zproducts" id="create-zproducts" action="create-zproduct.php" method="POST">
<?php
//connection
$con = mysqli_connect('localhost', 'user', 'password', 'database');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM david_cim_template_categories, david_j2store_productimages";
$cg = $_GET['cim_template_cg'];
$coverimage_iid = $_GET['main_image'];
$result = mysqli_query($con,$sql);
?>
<select name="selectZcategories" id="selectZcategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname']'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
<button onclick="ajaxFunction();">Submit</button><br /><br />
<?php
<script>
function ajaxFunction() {
var selectedData=$("#selectZcategories option:selected").val();
$.ajax({
type : "POST",
url: "select_zproduct.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
</script>
?>
<?php
echo $ZAPI = "https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg=";
echo $cg = ['cim_template_cg'];
echo $ZPARAM = "&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid=https%3A%2F%2Fwww.capturedimagesofmaine.com%2Fimages%2Fproducts%2Foriginal%2F";
echo $coverimage_iid = ['main_image'];
echo $product_text = "&t_text1_txt=Welcome";
?>
</form>
</div>
// new file (select_zproduct.php) added to same path as create_zproduct.php
// contents of select_zproduct.php below:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$cg=$selecterArrayData[0];
$coverimage_iid=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$cg.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$coverimage_iid.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
The code above is just the beginning of what I've been able to write by myself so far.
My obstacle at the moment is not being able to make the " cg= " parameter display the numeric value of $cg= which was selected by the user from the dropdown list. The current code returns the word "Array" in the URL instead of the selected value. (eg. cg=Array instead of cg=196215449301144739)
I believe I need to use AJAX and Javascript to accomplish this action but I don't know enough to write it by myself yet.
The Code I Need to Write will accomplish the following tasks:
Assign proper $variables to URL fragments ($ZAPI, $cg, etc) to be used for concatenation
Assign proper $variables to database dropdown SELECTION Result to be used in the URL above
Concatenate all $variables
Parse all $variables
Embed final encoded URL into button
Use thumbnail of active page main_image as button image src
What I need to know right now is how do I insert the numeric value of 'cim_template_cg' into the " cg= " parameter in the final URL so the final URL will output " &cg=196215449301144739 " when the user selects the 'cim_template_cgname' associated with that cg=.
Once I see the solution I can apply it to the other dynamic values I need to create. I've only written one javascript code with help from a snippet so any AJAX or Javascript code that needs to be written will need to be shown to me in an example and describing related files, please.
Thanks for your help in advance!
So if I understood your question properly, you have the necessary data to achieve this, i.e. you have the URL path and ID from the database, as well as the URL string, which needs these database values dynamically added upon selection?
And to answer one of your questions, yes this can be done via AJAX if you wish for the PHP logic to be handled in a seperate file.
What you could do, is concatenate your URL path and ID from the database with a seperator value that you could perform an explode(); on to get the values.
so, your <select> would look something like this instead:
<select name="selectZcategories" id="zCategories">
<?php
while($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['cim_template_cg'].':'.$row['cim_template_cgname'].'">'.$row['cim_template_cgname'].'</option>';
}
?>
</select>
Now to the AJAX function. Personally, I use the jQuery library, simply because it makes things easy and simple. It simplifies a lot of the code, so I am going to go by the jQuery standards in my AJAX example. If you wish to use jQuery AJAX to achieve the same results, you will need to install jQuery into a library that you include like any other normal JS/CSS file etc.
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
}
})
}
What this achieves, is that the function will take the selected value of the <select> and parse the data to another file using the POST method. You are able to do a lot of things in the success function if you so desire, but for our purpose, I'll simply perform the redirect in the PHP file.
When the data has been parsed to the other file, you then perform an explode(); on the value to split it up into our two variables that we will parse along in our URL.
The PHP file could look something like this:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
?>
<script>
window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
How you call the AJAX function initially is up to you. It could be via a button for instance.
<button onclick="ajaxFunction();">Submit</button>
Hope this helped, or pointed you towards the right direction.
For tests as per request by your comment,
Ajax for test:
function ajaxFunction() {
var selectedData=$("#zCategories option:selected").val();
$.ajax({
type : "POST",
url: "/path/to/file.php",
data: { selection : selectedData },
success: function (html) {
//Success handling
alert(html);
}
})
}
PHP:
<?php
if( isset($_POST['selection']) )
{
$selecterData=$_POST['selection'];
$selecterArrayData=explode(':', $selecterData);
$categoryID=$selecterArrayData[0];
$imagePath=$selecterArrayData[1];
$url='https://www.zazzle.com/api/create/at-238500395169782226?rf=238500395169782226&ax=DesignBlast&sr=250508120301240636&cg='.$categoryID.'&t__useQpc=false&ed=true&t__smart=false&continueUrl=https%3A%2F%2Fwww.zazzle.com%2Fcapturedimagesmaine&tc=&ic=&t_coverimage_iid='.$imagePath.'';
echo 'cg: '.$categoryID.' img path: '.$imagePath;
?>
<script>
//window.location.href=<?php echo $url; ?>;
</script>
<?php
}
?>
I contacted the developer of J2Store for help with getting the main_image value from the active J2Store product page and embedding my final API URL into my J2Store product pages so he rewrote my code to integrate error-free with both Joomla and J2Store, as follows:
<?php
/**
* #package J2Store
* #copyright Copyright (c)2014-17 Ramesh Elamathi / J2Store.org
* #license GNU GPL v3 or later
*
* Bootstrap 2 layout of product detail
*/
// No direct access
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$query = $db->getQuery(true)->select('*')->from('#__cim_template_categories');
$db->setQuery($query);
$cg_values = $db->loadObjectList();
$image_path = JUri::root();
$main_image = $image_path.$this->product->main_image;
//$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
$zazzle_api = 'https://www.zazzle.com/api/create/at-238500395169782226';
?>
<?php if(count($cg_values)): ?>
<div class="cg_values">
<form method="get" class="zazzle_api_form" action="<?php echo $zazzle_api; ?>">
<select name="cg" class="cg">
<?php foreach($cg_values as $cg_value): ?>
<option value="<?php echo $cg_value->cim_template_cg; ?>">
<?php echo $cg_value->cim_template_cgname; ?>
</option>
<?php endforeach; ?>
</select>
<input type="hidden" name="rf" value="238500395169782226" />
<input type="hidden" name="ax" value="DesignBlast" />
<input type="hidden" name="sr" value="250508120301240636" />
<input type="hidden" name="t__useQpc" value="false" />
<input type="hidden" name="ed" value="true" />
<input type="hidden" name="t__smart" value="false" />
<input type="hidden" name="continueUrl" value="<?php echo urlencode('https://www.zazzle.com?www.capturedimagesmaine.com'); ?>" />
<input type="hidden" name="tc" value="" />
<input type="hidden" name="ic" value="" />
<input type="hidden" name="t_text1_txt" value="" />
<input type="hidden" name="t_coverimage_iid" value="<?php echo $main_image; ?>"
/>
<input class="btn btn-primary" type="submit" value="Create Your Own Custom Gifts"
/>
</form>
</div>
<?php endif; ?>

Cakephp 2.x - hide/show a combobox

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));

Issue with price format on Product Page (getPriceHtml)

I'm having troubles with the price formatting on a product page of a downloadable product.
The format (as defined globally) should be EUR 15.23. It work's fine in the sidebars, category pages, homepage and so on.
Anyway, on the product page the price is shown wrong (without space): EUR15.23
catalog/product/view.phtml:
//calling once - price EUR15.23
<?php echo $this->getPriceHtml($_product, true); ?>
//calling twice - first price EUR15.23 second price EUR 15.23 (correct)
<?php echo $this->getPriceHtml($_product, true); ?>
same problem when calling:
<?php echo $this->getChildHtml('product_type_data'); ?>
I think it has to do with the reloadPrice : function() JavaScript Code in
downloadable/catalog/product/links.phtml
Anyone also had this problem?
Actually I don't want to get through the JavaScript-Code and change something here as I do not want to change the core files.
Thanks!
Sure it isn't right solution, but if I got you right and it is always true that "first price EUR15.23 second price EUR 15.23 (correct)", then why not just
<?php $this->getPriceHtml($_product, true); // no output ?>
<?php echo $this->getPriceHtml($_product, true); // correct output ?>

Categories