Help creating an ajax method to add to basket - php

I have the following code that I want to turn into a silent ajax function so the page does not need to refresh, when a user adds a product the basket.
Currently I have the following code,
PHP
function showProduct($productId)
{
if (!$productId > 0)
{
redirect('home');
}
$this->load->model('Product_model');
$this->load->model('Checkout_model');
$this->data['items'] = $this->Checkout_model->GetProducts();
// Check to see if the Add To Bag button has been clicked.
if ($this->input->post('btnAddToBag'))
{
$derivativeId = $this->input->post('selDerivative-1');
$quantity = $this->input->post('selQuantity');
$derivative = $this->Product_model->GetProducts(array('pdId' => $derivativeId), 'small');
// Add item to shopping bag.
$attributes = $this->Product_model->GetProductDerivatives(array('pdId' => $derivativeId));
$this->Checkout_model->AddProduct($derivative, $attributes, $quantity);
$this->data['message'] = 'Item added to Shopping Bag.';
// Update Delivery Price
$this->Checkout_model->updateDelivery(49);
//get the bag details
}
$this->data["product_details"] = $this->Product_model->GetProducts(array('productId' => $productId, 'pdOrdering' => 1), 'detail');
$this->data['product_images'] = $this->Product_model->GetProductImages(array('productId' => $productId, 'ipPosition' => 'detail'));
//send the new filename to the view
//die(print_r($this->data['product_images']));
//die(print_r($this->data['sliderUrl']));
// Retrieve images for initial derivative.
$this->load->model('Attribute_model');
$this->data['derivative_images'] = $this->Attribute_model->GetAttributeValues(array('pdavProductDerivativeId' => $this->data["product_details"]->pdId), 'small', TRUE);;
$derivatives = $this->Product_model->GetProductDerivatives(array('pdProductId' => $productId));
$this->data["product_derivatives"] = $derivatives['derivatives'];
$this->data["product_attribute_names"] = $derivatives['attributeNames'];
// Retrieve details of this range.
$subRangeId = $this->data["product_details"]->productRangeId;
$this->data["sub_range_details"] = $this->Range_model->GetRanges(array('range.rangeId' => $subRangeId));
$rangeId = $this->data["sub_range_details"]->rangeParentId;
$this->data['active_menu_item'] = "subrange";
if ($rangeId == 0)
{
$rangeId = $subRangeId;
$this->data['active_menu_item'] = "full";
}
$this->data["range_details"] = $this->Range_model->GetRanges(array('range.rangeId' => $rangeId, 'range.rangeParentId' => 0), 'navigation');
if ($rangeId != $subRangeId)
$this->template->set_breadcrumb($this->data["range_details"]->rangeTitle, $this->data["range_details"]->rangePath);
//$this->data["rangePath"] = $this->uri->segment(1).'/';
$this->data["rangeId"] = $rangeId;
$this->data["subRangeId"] = $subRangeId;
// Retrieve list of sub ranges in this range.
$this->data["sub_ranges"] = $this->Range_model->GetRanges(array('range.rangeParentId' => $rangeId));
$this->data["individual_products"] = $this->Product_model->GetProducts(array('psiParentId' => $productId), 'small');
$this->data["related_products"] = $this->Product_model->GetRelatedProducts(array('product_related.prProductId' => $productId, 'ordering' => 'productActualPrice'), 'small');
$this->data['bestsellers'] = $this->Product_model->GetProducts(array('productBestSeller' => '1', 'range.rangeParentId' => $rangeId, 'ordering' => 'range.rangeOrder'), 'small');
$this->data["multibuy"] = $this->Product_model->GetProducts(array('psi.psiChildId' => $productId, 'productSavingType' => 'multi-buy'));
//$this->load->view('collection', $data);
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest") {
$this->template
->build('product/quickview', $this->data); // views/product/product.php
}else{
$this->template
->set_layout('default') // application/views/layouts/default.php
->title(($this->data["product_details"]->productMetadataTitle != '' ? $this->data["product_details"]->productMetadataTitle : $this->data["product_details"]->productTitle))
->set_metadata('keywords', $this->data["product_details"]->productMetadataKeywords, 'meta')
->set_metadata('description', ($this->data["product_details"]->productMetadataDescription != '' ? $this->data["product_details"]->productMetadataDescription : $this->data["product_details"]->productShortDesc), 'meta')
->set_metadata('', site_url('assets/js/product.js'), 'js')
->set_metadata('', site_url('assets/js/jquery.nivo.slider.js'), 'js')
->set_metadata('', site_url('assets/js/slider.js'), 'js')
->set_partial('left-nav', 'blocks/ranges_sub_menu') // application/views/blocks/ranges_sub_menu.php
->set_breadcrumb($this->data["sub_range_details"]->rangeTitle, $this->data["sub_range_details"]->fullRangePath)
->set_breadcrumb($this->data["product_details"]->productTitle, $this->data["product_details"]->fullProductPath)
->build('product/product', $this->data); // views/product/product.php
}
}
HTML FORM
<?php echo form_open(current_url(), array('id' => 'frmProducts'), array('submitted' => '1')); ?>
<div class="formRow">
<label for="rattanType"><?php echo $product_attribute_names; ?> </label><br />
<?php
$options = array();
foreach ($product_derivatives as $derivative) :
$options[$derivative['derivativeId']] = $derivative['attributeValues'];
endforeach;
?>
<?php echo form_dropdown('selDerivative-1', $options, $product_details->pdId, 'class="select clear" id="selDerivative-1"'); ?>
</div>
<?php if (count($individual_products) > 0) : ?>
<div class="formRow">
<label for="itemType">Item</label><br />
<select class="select clear" id="selURL-1" name="selURL-1">
<option value="<?php echo current_url(); ?>">Full Set</option>
<?php foreach ($individual_products as $product) : ?>
<option value="<?php echo site_url($product->fullProductPath); ?>"><?php echo $product->productTitle; ?> - £<?php echo ($product->productSavingType != 'none' ? $product->productSavingPrice : $product->productPrice); ?></option>
<?php endforeach; ?>
</select>
<input id="btnGo-1" name="btnGo-1" type="submit" value="GO" />
</div>
<?php endif; ?>
<div class="formRow">
<label for="addQty">Quantity</label><br />
<?php
$options = array();
for ($i = 1; $i < 10; $i++) :
$options[$i] = $i;
endfor;
?>
<?php echo form_dropdown('selQuantity', $options, '1', 'class="small select clear"'); ?>
</div>
<input type="submit" value="add to bag" name="btnAddToBag" id="btnAddToBag" />
<?php echo form_close(); ?>
// Reset action of form when add to bag button is clicked.
$("#btnAddToBag").click(function () {
$("#frmProducts").attr("action","<?php echo current_url(); ?>");
});
How can I change this code that it makes an ajax request and updates the cart without refreshing the page?

You need to split off your basket display into another file so that you can use:
$.load()
Example basic usage:
$('#ShoppingCart').load('Cart.php', function() {
alert('Load was performed.');
});
<div id="ShoppingCart"> </div>
Or a little more like youve currently got it set up:
$("#btnAddToBag").click(function () {
$('#ShoppingCart').load('Cart.php', function() {
alert('Load was performed.');
});
});
Edit:
Re-reading your post, do you not want the cart to update atall?
In that case you would need to use $.post()
See: http://api.jquery.com/jQuery.post/

I have already answered a question for JSP/SERVLET here this one should work by changing the URL to a PHP page...
You need to make an XML Http request to the Servlet for that you need to make a XML Http object in the javascript in your HTML/PHP page
var myxmlhttpobj=new GetXmlHttpObject();
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
Now you need to make a request to the PHP from the javascript
var url="urlofPHPpage";
var para="parmeter1=value1&parameter2=valu2;
myxmlhttpobj.open("POST",url,true);
myxmlhttpobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
myxmlhttpobj.setRequestHeader("Content-length", para.length);
myxmlhttpobj.setRequestHeader("Connection", "close");
myxmlhttpobj.onreadystatechange=ajaxComplete;
myxmlhttpobj.send(para);
At the PHP page you need to process the result and sent it back as string:
When the request comes back the myxmlhttpobj.onreadystatechange=ajaxComplete; will be called
function ajaxComplete(){
if(myxmlhttpobj.readyState==4){
///Display the result on the HTML/PHP Page BASKET
}
}
That should help...
Also have a look at jQuery Ajax API.

Related

Load More with PHP prevent calling of en event handler twice on fast clicks?

I have this code, which allows me to make a "show more" button on Advanced Fields Pro repeater Elements in WordPress.
The problem is when I click fast twice(or more) on the buttons it shows me the fields, which are hidden also twice the (or more) time.
Does anyone have an idea on how to solve it?
Code on WordPress Front end:
<div id="photo-gallery">
<div class="row mt-5 mb-3">
<?php
if( have_rows('logos_der_externen_plattformen') ):
$total = count(get_field('logos_der_externen_plattformen'));
$count = 0;
$number = 5;
while ( have_rows('logos_der_externen_plattformen') ) : the_row(); ?>
<div class="col-6 col-md-4 col-lg-2 p-md-5 pr-2 pl-2 pb-5 pt-2 text-center" data-aos="fade-up">
<img data-src="<?php the_sub_field('logo'); ?>" alt="<?php the_sub_field('alternative_beschreibung_des_logos'); ?>" class="lazy img-fluid">
</div>
<?php
if ($count == $number) {
// we've shown the number, break out of loop
break;
} ?>
<?php $count++; endwhile;
else : endif;
?>
</div>
<div align="center" class="text-decoration-none">
<a id="gallery-load-more" style="text-decoration:none;" href="javascript: my_repeater_show_more();" <?php if ($total < $count) { ?> class="d-none" <?php } ?>><h7 id="title-bg"><span>und viele mehr...</span></h7></a></div>
</div>
var my_repeater_field_post_id = <?php echo $post->ID; ?>;
var my_repeater_field_offset = <?php echo $number + 1; ?>;
var my_repeater_field_nonce = '<?php echo wp_create_nonce('my_repeater_field_nonce'); ?>';
var my_repeater_ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
var my_repeater_more = true;
function my_repeater_show_more() {
// make ajax request
jQuery.post(
my_repeater_ajax_url, {
// this is the AJAX action we set up in PHP
'action': 'my_repeater_show_more',
'post_id': my_repeater_field_post_id,
'offset': my_repeater_field_offset,
'nonce': my_repeater_field_nonce
},
function (json) {
// add content to container
// this ID must match the containter
// you want to append content to
jQuery('#photo-gallery .row').append(json['content']);
// update offset
my_repeater_field_offset = json['offset'];
// see if there is more, if not then hide the more link
if (!json['more']) {
// this ID must match the id of the show more link
jQuery('#gallery-load-more').css('display', 'none');
}
},
'json'
);
}
Backend:
/**
* ACF Load More Repeater
*/
// add action for logged in users
add_action('wp_ajax_my_repeater_show_more', 'my_repeater_show_more');
// add action for non logged in users
add_action('wp_ajax_nopriv_my_repeater_show_more', 'my_repeater_show_more');
function my_repeater_show_more() {
// validate the nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'my_repeater_field_nonce')) {
exit;
}
// make sure we have the other values
if (!isset($_POST['post_id']) || !isset($_POST['offset'])) {
return;
}
$show = 10; // how many more to show
$start = $_POST['offset'];
$end = $start+$show;
$post_id = $_POST['post_id'];
// use an object buffer to capture the html output
// alternately you could create a varaible like $html
// and add the content to this string, but I find
// object buffers make the code easier to work with
ob_start();
if (have_rows('logos_der_externen_plattformen', $post_id)) {
$total = count(get_field('logos_der_externen_plattformen', $post_id));
$count = 0;
while (have_rows('logos_der_externen_plattformen', $post_id)) {
the_row();
if ($count < $start) {
// we have not gotten to where
// we need to start showing
// increment count and continue
$count++;
continue;
}
?>
<div class="col-6 col-md-4 col-lg-2 p-md-5 pr-2 pl-2 pb-5 pt-2 text-center" data-aos="fade-up">
<img src="<?php the_sub_field('logo'); ?>" alt="<?php the_sub_field('alternative_beschreibung_des_logos'); ?>" class="img-fluid">
</div>
<?php
$count++;
if ($count == $end) {
// we have shown the number, break out of loop
break;
}
} // end while have rows
} // end if have rows
$content = ob_get_clean();
// check to see if we have shown the last item
$more = false;
if ($total > $count) {
$more = true;
}
// output our 3 values as a json encoded array
echo json_encode(array('content' => $content, 'more' => $more, 'offset' => $end));
exit;
} // end function my_repeater_show_more
This solution fork just fine for me:
document.getElementById("title-bg").onclick = function() {
document.getElementById("title-bg").style.display = "none";
}
There are 2 ways you could solve this:
Create a wrapper function around your JAVASCRIPT implementation of my_repeater_show_more. When this function starts, set a variable that the request is in progress. Unset the variable when the request has completed and the fields have been loaded. Disable the button when the field is set. This way, while the fields are loading, the button cannot be clicked.
Wrap your JAVASCRIPT call to my_repeater_show_more in a debounce. This will prevent the function from firing until some minimum amount of time has passed between clicks. Doing so will prevent the function from firing twice if you double click quickly.
More information about writing a debounce in vanilla JS can be found on this excellent blog post.

How to add an image icon to an Elgg entity

Elgg Version 2.0
How can I go about creating an Elgg entity with an image icon, just like how one can do when creating an Elgg group?
I've tried implementing the following, but no image gets uploaded:
Action file:
<?php
// get the form inputs
$title = get_input('title');
$body = get_input('body');
$tags = string_to_tag_array(get_input('tags'));
// create a new my_blog object
$blog = new ElggObject();
$blog->subtype = "nganya";
$blog->title = $title;
$blog->description = $body;
// for now make all my_blog posts public
$blog->access_id = ACCESS_PUBLIC;
// owner is logged in user
$blog->owner_guid = elgg_get_logged_in_user_guid();
// save tags as metadata
$blog->tags = $tags;
// save to database and get id of the new my_blog
$blog_guid = $blog->save();
// if the my_blog was saved, we want to display the new post
// otherwise, we want to register an error and forward back to the form
if ($blog_guid) {
system_message("Your nganya post was saved >>>>>>>>>> " . $blog_guid);
forward($blog->getURL());
} else {
register_error("The nganya post could not be saved");
forward(REFERER); // REFERER is a global variable that defines the previous page
}
$has_uploaded_icon = (!empty($_FILES['icon']['type']) && substr_count($_FILES['icon']['type'], 'image/'));
if ($has_uploaded_icon) {
$icon_sizes = elgg_get_config('icon_sizes');
$prefix = "nganya/" . $blog->guid;
$filehandler = new ElggFile();
$filehandler->owner_guid = $blog_guid;
$filehandler->setFilename($prefix . ".jpg");
$filehandler->open("write");
$filehandler->write(get_uploaded_file('icon'));
$filehandler->close();
$filename = $filehandler->getFilenameOnFilestore();
$sizes = array('tiny', 'small', 'medium', 'large', 'master');
$thumbs = array();
foreach ($sizes as $size) {
$thumbs[$size] = get_resized_image_from_existing_file(
$filename,
$icon_sizes[$size]['w'],
$icon_sizes[$size]['h'],
$icon_sizes[$size]['square']
);
}
if ($thumbs['tiny']) { // just checking if resize successful
$thumb = new ElggFile();
$thumb->owner_guid = $blog->owner_guid;
$thumb->setMimeType('image/jpeg');
foreach ($sizes as $size) {
$thumb->setFilename("{$prefix}{$size}.jpg");
$thumb->open("write");
$thumb->write($thumbs[$size]);
$thumb->close();
}
$blog->icontime = time();
}
}
The Form:
<div>
<label><?php echo elgg_echo("groups:icon"); ?></label><br />
<?php echo elgg_view("input/file", array("name" => "icon")); ?>
</div>
<div>
<label for="title"><?= elgg_echo("title"); ?></label><br />
<?= elgg_view('input/text', ['name' => 'title', 'id' => 'title']); ?>
</div>
<div>
<label for="body"><?= elgg_echo("body"); ?></label><br />
<?= elgg_view('input/longtext', ['name' => 'body', 'id' => 'body']); ?>
</div>
<div>
<label for="tags"><?= elgg_echo("tags"); ?></label><br />
<?= elgg_view('input/tags', ['name' => 'tags', 'id' => 'tags']); ?>
</div>
<div>
<?= elgg_view('input/submit', ['value' => elgg_echo('save')]); ?>
</div>
The action code looks correct. In Elgg 2.2, this will be a lot easier, but in the meantime:
You need to add a plugin hook handler for
'entity:icon:url',<entity_type> hook and replace the URL if
$params['entity'] is of the subtype your are adding
Update your page handler to serve a file for the above URL.

Make the options of the 2nd select box populate depending on the 1st. Both are PHP arrays

I have two innoDB tables in my database named customers and vessels. I also have a form with 2 select boxes one having the column: company_name of table: customers as options, and the other having the column: vessel_name of table: vessels.
What i want to do is make the options of the 2nd select box populate according to the customer's company_name chosen in the 1st select box.
Finally please take into consideration that i am a complete newbie in Javascript and jQuery and thats why i am asking here how can i achieve the above result.
The form:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name="ypo" method="post">
<select name="company_name">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<select name="vessel">
<?php
foreach($ploia as $end) {
?>
<option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
<?php
}
?>
</select>
</form>
</body>
</html>
The php to make the above form work :
<?php
// For customers
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if($pelat = $db->query($sqlpelates)) {
$pelates = array();
while($pelate = $pelat->fetch_object()) {
$pelates[] = $pelate;
}
$pelat->free();
}
// For vessels
$sqlploia = "SELECT * FROM vessels ORDER BY vessel_name";
if($plo = $db->query($sqlploia)) {
$ploia = array();
while($ploi = $plo->fetch_object()) {
$ploia[] = $ploi;
}
$plo->free();
}
?>
UPDATE: Below is the single .php page where i am trying to achieve the above result:
<?php
require 'db/connect.php';
//check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
// if not then this is a fresh page that needs everything
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if ($pelat=$db->query($sqlpelates)) {
$pelates = array();
while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
$pelat->free();
}
}
// modify the query to filter out only what your ajax request wants
$where = $ajax ? ' WHERE company_name="'.$_POST['companyName'].'"' : '';
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
$ploia = array();
while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
$plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
if ($ajax) {
// set the type, so the client knows what the server returns
header('Content-Type: application/json');
// output what the client asked for: an array of vessels in JSON format
echo json_encode($ploia);
// kill the script, this is all the client wants to know
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script src="jquery.js">
// Your code goes here.
// jQuery must be loaded already
$(function(){
var
// put the target php script
url = 'http://prinseapals-marine.com/filing/drop_down.php',
form=$('form[name="ypo"]'), company, vessels;
company = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="company_name"]')[0],
onSelect : function () {
var
idx = company.selectBox.selectedIndex,
data;
// if user selected an empty option, clear and return
if (idx === -1) {vessels.clearBox();return;}
// setup the data
data = {"ajax":1,"company_name":company.selectBox[idx].value};
// your script now has $_GET['ajax'], $_GET['company_name']
$.post(url,data,vessels.fillBox,'json');
// vessels.fillbox will be executed when your php script returns
}
};
vessels = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="vessel"]')[0],
// a handy method for clearing options
clearBox : function () {$(this.selectBox).empty()},
// called upon completion of the ajax request
fillBox : function (arrayOfVessels) {
// clear current contents
$(this.selectBox).empty();
// for each element in the array append a new option to the vessel selector
arrayOfVessels.forEach(function(v){
$(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
});
}
};
// add a listener to the company selector
$(company.selectBox).change(company.onSelect);
});
</script>
<form name="ypo" method="post">
<select name="company_name">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<select name="vessel">
<?php
foreach($ploia as $end) {
?>
<option value="<?php echo $end->vessel_name; ?>"><?php echo $end->vessel_name; ?></option>
<?php
}
?>
</select>
</form>
</body>
FINAL-UPDATE :
test.php:
<?php
require 'db/connect.php';
$cus = array();
if($cterm = $db->query("SELECT * FROM `customers`")) {
while($cterm2 = $cterm->fetch_object()) {
$cus[] = $cterm2;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form id="form1" name="myform">
<select name="selection" onchange="load('bdiv', 'test2.php');">
<?php
foreach($cus as $c) {
?>
<option value="<? echo $c->company_name ?>"><? echo $c->company_name ?></option>
<?php
}
?>
</select>
<div id="bdiv"></div>
</form>
</body>
</html>
test.js:
function load (thediv, thefile) {
// body...
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', thefile+'?selection='+document.myform.selection.value, true);
xmlhttp.send();
}
test2.php:
<?php
require 'db/connect.php';
if (isset($_GET['selection'])) {
# code...
$selection = $_GET['selection'];
}
$ves = array();
if ($vterm = $db->query(
"SELECT `vessel_name` FROM `vessels` WHERE `company_name` = '$selection'")) {
while ($vterm2 = $vterm->fetch_object()) {
$ves[] = $vterm2;
}
} else {
echo 'Please type a customer name.';
}
?>
<select>
<?php
foreach($ves as $v) {
?>
<option value="<?php echo $v->vessel_name ?>" ><?php echo $v->vessel_name ?></option>
<?php
}
?>
</select>
This is not the first time I see this asked but I will dive in
Warning: this answer has javascript, with jQuery. I will also append a php file afterwards with some changes to allow the same script to be called for the ajax request
// jQuery must be loaded already
$(function(){
var
// put the target php script
url = 'http://localhost/test/stackoverflow.php',
form=$('form[name="ypo"]'), company, vessels;
company = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="company_name"]')[0],
onSelect : function () {
var
idx = company.selectBox.selectedIndex,
data;
// if user selected an empty option, clear and return
if (idx === -1) {vessels.clearBox();return;}
// setup the data
data = {"ajax":1,"company_name":company.selectBox[idx].value};
// your script now has $_GET['ajax'], $_GET['company_name']
$.post(url,data,vessels.fillBox,'json');
// vessels.fillbox will be executed when your php script returns
}
};
vessels = {
// I prefer using native DomElements sometimes
selectBox : $(form).find('select[name="vessel"]')[0],
// a handy method for clearing options
clearBox : function () {$(this.selectBox).empty()},
// called upon completion of the ajax request
fillBox : function (arrayOfVessels) {
// clear current contents
$(this.selectBox).empty();
// for each element in the array append a new option to the vessel selector
arrayOfVessels.forEach(function(v){
$(vessels.selectBox).append('<option value="'+v+'">'+v+'</option>');
});
}
};
// add a listener to the company selector
$(company.selectBox).change(company.onSelect);
});
The logic behind the js code is to allow user interaction. When the user makes a selection a request is fired to the server and the response is processed in the client and populates your 2nd <select>
Now, a modified version of your php script (warning: this works with the template I append next)
<?php
// your model, check for whitespaces outside php tags, do not allow output yet
require 'db/connect.php';
// check if this is an ajax call
$ajax = isset($_POST['ajax']) ? $_POST['ajax'] : false;
if (!$ajax) {
// required for the template
$pelates = array();
// if not then this is a fresh page that needs everything
$sqlpelates = "SELECT * FROM customers ORDER BY company_name";
if ($pelat=$db->query($sqlpelates)) {
while($pelate=$pelat->fetch_object()) $pelates[] = $pelate;
$pelat->free();
}
} else {
// modify the query to filter out only what your ajax request wants
$where = ' WHERE company_name="'.$_POST['companyName'].'"';
// required for the ajax request
$ploia = array();
// you need to make sure to escape the incoming variable $_POST['company_name']
$sqlploia = 'SELECT * FROM vessels'.$where.' ORDER BY vessel_name';
if ($plo=$db->query($sqlploia)) {
while($ploi=$plo->fetch_object()) $ploia[] = $ploi;
$plo->free();
}
// the secret sauce... and some very bad programming, this should be done some other way
// set the type, so the client knows what the server returns
header('Content-Type: application/json');
// output what the client asked for: an array of vessels in JSON format
echo json_encode($ploia);
// kill the script, this is all the client want's to know
exit;
}
?>
Next comes a modified version of your html template
<!DOCTYPE html>
<html>
<head>
<title>Your title</title>
</head>
<body>
<form name="ypo" method="post">
<select name="company_name"><?php
foreach($pelates as $p) echo '<option value="'.$p->company_name.'">'.$p->company_name.'</option>';
?></select>
<!-- leave empty, we will populate it when the user selects a company -->
<select name="vessel"></select>
</form>
<!-- add jQuery lib here, either your own or from a CDN; this is google's version 2.0.3 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<!-- The code should be in a seperate file, load here if you want (but after jQuery lib) -->
<script src="your/javascript/file.js"></script>
</body>
</html>
Ok, now some pointers
you should be carefull with the php script I left there, there are other ways of doing what I intended which are cleaner and easier to maintain
the javascript is not the best, there are better solutions out there so be sure to check those out as well
If you do not understand parts of any of the scripts don't hesitate to ask
Beware any whitespace, do not allow any output before the php script, this is very important. All output should be left to the template
I hope this has been helpfull
Use ajax for this, Pass your company id to the javascript
<script>
function showCustomer(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myresult").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php?q="+str,true); // Pass value to another page Here->test
xmlhttp.send();
}
</script>
<select name="company_name" onchange="showCustomer(this.value)">
<?php
foreach($pelates as $pelend) {
?>
<option value="<?php echo $pelend->company_name; ?>"><?php echo $pelend->company_name; ?></option>
<?php
}
?>
</select>
<div id="myresult">
</div>
Now On test.php Simply Call Value & put select box,
<?php
$q = $_GET['q'];
// Here fetch values for particular q(company name)
// put select box

Loop through an array of checkboxes and insert values

First time posting, hope all goes well :)
Been working on this for a while but basically I'm doing something like this: http://drupal.org/project/fancycheckboxes
I need to set a value of yes/no for each checkbox that I'm looping through and right now it works but is changing the value of all when I change one.
My foreach loop:
<?php $object = new stdClass(); $i = 0; ?>
<?php foreach( $filters as $key => $value ) {
?>
<tr>
<td><label for="show_filter">Show <?php echo $object->$key = $value['filter']; ?> Filter</label></td>
<td><input type="checkbox" class="show_filter" <?php //if ( $row['active_filter'] === 'yes' ) { ?>checked="checked"<?php //} ?> name="dp_show_filter" value="<?php echo $object->$key = $value['active_filter']; ?>"/><?php echo $object->$key = $value['active_filter']; ?></td>
<td><a class="button-primary" href="?page=profolio_theme&del=<?php echo $row['id'];?>">Delete</a></td>
</tr>
<?php
$i++;
}
and my jQuery:
jQuery(document).ready(function(e) {
var $ = jQuery.noConflict();
$i = 0;
customCheckbox = $('.dp_wrap input[type="checkbox"]');
showFilter = $('.dp_wrap input[name="dp_show_filter"]');
values = [];
return customCheckbox.each(function() {
// the element
var el = this;
// Hide checkbox
$(this).hide();
// Replace element
var rep = $('<span></span>').addClass('dp-checkbox').insertAfter(this);
// default state
if( $(showFilter).val() === 'yes'){
$(showFilter).prop('checked', true);
$(rep).removeClass('off').addClass('on');
} else {
$(showFilter).prop('checked', false);
$(rep).removeClass('on').addClass('off');
}
if($(this).is(':checked') ) {
$(rep).addClass('on');
} else {
$(rep).addClass('off');
}
// Click event
$(rep).click(function(e) {
e.preventDefault();
if( $(el).is(':checked') ) {
values.push($(showFilter).val('no'), ++$i);
$(el).prop('checked', false);
$(rep).removeClass('on').addClass('off');
} else {
values.push($(showFilter).val('yes'), ++$i);
$(el).prop('checked', true);
$(rep).removeClass('off').addClass('on');
}
});
});
});
Currenty my values are posting to a database as yes/no.
Any help is greatly appreciated and I hope my first post is an acceptable one.
It is changing all of the values as it looks as though you are giving the same name to every checkbox created on your page.
You can change your PHP code to something more like this:
<?php $object = new stdClass(); $i = 0; ?>
<?php foreach( $filters as $key => $value ) {
?>
<tr>
<td><label for="show_filter">Show <?php echo $object->$key = $value['filter']; ?> Filter</label></td>
<td><input type="checkbox" class="show_filter" <?php //if ( $row['active_filter'] === 'yes' ) { ?>checked="checked"<?php //} ?> name="dp_show_filter_<?php echo $row['id'] ?>" value="<?php echo $object->$key = $value['active_filter']; ?>"/><?php echo $object->$key = $value['active_filter']; ?></td>
<td><a class="button-primary" href="?page=profolio_theme&del=<?php echo $row['id'];?>">Delete</a></td>
</tr>
<?php
$i++;
}
Then change your default state to this and remove the if statement from underneath it:
// default state
if( $(this).val() === 'yes'){
$(this).prop('checked', true);
$(rep).removeClass('off').addClass('on');
} else {
$(this).prop('checked', false);
$(rep).removeClass('on').addClass('off');
}
I am pretty sure that will fix your problem as you described it. It is hard to tell without a more complete example of your code.
You iterate through your customCheckbox array with an each, but inside your loop, you access $(showFilter), which is a global array.
Did you mean $(showFilter[i]) ?
The each callback receives i (the index in the loop) as a parameter :
return customCheckbox.each(function(i) {
...
if( $(showFilter[i]).val() === 'yes'){ ...

Magento how to add a required field to the shipping method?

I have added a dropdown box in the template file of my shipping method. Now I want to make it a required field. I have tried so many ways. But didn't worked. Any help will be appreciated.
Below is the template file.
<?php
$_code=$this->getMethodCode();
$carrier = $this->getMethodInstance();
$pickupData = $this->getQuote()->getPickupData();
$_rate = $this->getRate();
if(!isset($pickupData['store']))
{
$pickupData['store'] = -1;
}
if(!isset($pickupData['name']))
{
$pickupData['name'] = '';
}
?>
<ul class="form-list" id="shipping_form_<?php echo $_rate->getCode() ?>" style="display:none;">
<li>
<label for="shipping_pickup[store]" class="required"><em>*</em><?php echo $this->__('Choose Store Location:') ?></label>
<span class="input-box" style="float:left ;">
<select class="required-entry" name="shipping_pickup[store]" id="shipping_pickup[store]">
<option value='0'><?php echo $this->__('Select Store..');?></option>
<?php
$collection = $this->getAllLocations();
foreach($collection as $coll)
{
$data = $coll->getData();
?>
<option value='<?php echo $data['location_id']; ?>'><?php echo $this->__($data['location_name']);?></option>
<?php
}
?>
</select>
</span>
</li>
</ul>
This code is always going to work because it is always going be set in the $_POST array which seems to turn into an array called $pickupData
You will need to alter your code to make sure that $pickupData['store'] is not a zero
//make sure this variable is available in the array to avoid errors
//check to make sure variable is not a zero still
if(isset($pickupData['store']) && $pickupData['store'] == 0){
$pickupData['store'] = -1;
}
In opcheckout.js edit the line 663 to 763.
validate: function() {
var methods = document.getElementsByName('shipping_method');
if (methods.length==0) {
alert(Translator.translate('Your order cannot be completed at this time as there is no shipping methods available for it. Please make necessary changes in your shipping address.').stripTags());
return false;
}
if(!this.validator.validate()) {
return false;
}
for (var i=0; i<methods.length; i++) {
if (methods[i].checked) {
var methodName = methods[i].value;
if(methodName == 'pickup_pickup')
{
var locationOpt = document.getElementById('shipping_pickup[store]');
var selectedOpt = locationOpt.options[locationOpt.selectedIndex].text;
if(selectedOpt == 'Select Store..')
{
alert(Translator.translate('Please specify a location.').stripTags());
return false;
}
else
{
return true;
}
}
else
{
return true;
}
}
}
alert(Translator.translate('Please specify shipping method.').stripTags());
return false;
},

Categories