Need help debugging Asynchronous AJAX call from a form in a div element to update same div with processed results based on form data - ajax

I am using a Mediawiki based website. The site is http://www.DragonFallRPG.com The widget in question is the 'Orion's Dice Box' in the left column of the site.
Not sure if that has any bearing on this but here goes. I have a custom div called 'dice' with a content destination div called 'result'. Below the 'result' div is a form for selecting a number of dice, and the number of sides for those dice. There is a processing script, which is tested working to provide a randomized result as if those dice were thrown. The problem is in the calling of one or more functions, I think. I found the AJAX method for getting the user input via 'get' somewhere on the web and no longer have any idea where it came from. I will include the files below.
dice_header.php (include file for <head> portion of webpage)
<style>
<!--[if IE] -- long buttons / button width in IE fix>
<style>.button{width:1;}</style>
<![endif]-->
</style>
<?php $javafile = dirname(__FILE__).'/ajax_engine.js'; ?>
<script type="text/javascript" src= "<?php echo $javafile ?>" ></script>
<script type="text/javascript">
function submit_dice() {
// Get form values
var no_of_dice = document.getElementById('dice').value;
var no_of_sides = document.getElementById('sides').value;
// Construct URL
<?php $handlerfile = dirname(__FILE__).'/handler.php' ?>
url = '<?php echo $handlerfile; ?>' + '?no_of_dice=' + escape(no_of_dice) + '&no_of_sides=' + escape(no_of_sides);
var xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
alert('Handlerfile URL = ' + url + '\r\n\r\n Escape URL = ' + escape(url) + '\r\n\r\n # of dice = ' + no_of_dice + '\r\n # of Sides = ' + no_of_sides);
alert('url for ajax_get = ' + url);
ajax_get (url, 'result');
}
</script>
The above code is an include in the header of the index.php
The function call for ajax_get seems to be where it breaks down in the process in the above code. I don't know if it requires the http portion of the url or not. I don't know if the escape url is required or not. I'm hesitant to monkey with the script any further without guidance.
The code that follows is the div block for the widget I'm trying to create
dice.php (include file for my widget / div block)
<div id="result" style="text-align:center;
word-wrap: break-word;
width:100px;
font-weight:bold;
font-size:large;
border:1px blue solid;
margin:0;">
<?php
//$filename = dirname(__FILE__).'/ajax_engine.js';
//$handlerfile = dirname(__FILE__).'/handler.php';
if (file_exists($handlerfile)) {
echo "Handler file path OK";
echo 'alert(\'Handler file path = "' . $handlerfile . '"\');';
die();
} else {
echo "BAD handler file path!";
}
?>
</div>
<table border="0" cellspacing="0" cellpadding="0" style="margin:0; padding:0px;" >
<tr>
<td><select name="dice" id="dice" size="1" style="margin:0px;">
<?php
for ($i = 1; ; $i++) {
if ($i > 20) {
break;
}
if ($i == 1) {
echo "<option value=$i selected>$i</option>\n";
} else {
echo "<option value=$i>$i</option>\n";
}
}
?>
</select></td>
<td><select name="sides" id="sides" size="1" style="margin:0px;">
<option value="4">d4</option>
<option value="6">d6</option>
<option value="8">d8</option>
<option value="10">d10</option>
<option value="12">d12</option>
<option value="20" selected>d20</option>
<option value="100">d100</option>
</select>
</td>
</tr><tr>
<td colspan="2">
<input type="button" onclick="submit_dice();" value="Roll Dice" style="width:100px;" />
</td></tr>
</table>
<!--
Psuedo vs. True Random Numbers
http://www.phpfive.net/pseudo-random_php_functions_and_truly_random_number_generators_article2.htm
-->
Next follows the javascript engine I'm using to begin the AJAX functionality... Mediawiki has it's own built in AJAX - but I have no familiarity with it and tried finding a less complicated working version else where that I could tweak - resulting in this headache.
Several alert popup calls made to help with debugging, but I'm lost, and none of these alerts are actually being called... I can't tell why.
// JavaScript Document "javascript_engine.js"
// Get base url
url = document.location.href;
var base_url = "http://";
alert('base_url = ' + base_url);
xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
var ajax_get_error = false;
alert('ajax_engine.js called');
function ajax_do (url) {
// Does URL begin with http?
alert('url.substring(0, 4) = ' + url);
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create new JS element
var jsel = document.createElement('SCRIPT');
jsel.type = 'text/javascript';
jsel.src = url;
// Append JS element (therefore executing the 'AJAX' call)
document.body.appendChild (jsel);
return true;
}
function ajax_get (url, el) {
// Has element been passed as object or id-string?
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
// Valid el?
if (el == null) { return false; }
alert(url.substring(0, 4));
// Does URL begin with http?
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create getfile URL
getfile_url = base_url + 'getfile.php?url=' + escape(url) + '&el=' + escape(el.id);
// Do Ajax
ajax_do (getfile_url);
return true;
}
Following is getfile.php
<?php //getfile.php -- used for addressing visual part of code
// Get URL and div
if (!isset($_GET['url'])) { die(); } else { $url = $_GET['url']; }
if (!isset($_GET['el'])) { die(); } else { $el = $_GET['el']; }
// echo 'alert(\'URL in getfile.php = \'); $url';
// Make sure url starts with http
if (substr($url, 0, 4) != 'http') {
// Set error
echo 'alert(\'Security error; incorrect URL!\');';
die();
}
// Try and get contents
$data = #file_get_contents($url);
if ($data === false) {
// Set error
echo 'alert(\'Unable to retrieve "' . $url . '"\');';
die();
}
// Escape data
$data = str_replace("'", "\'", $data);
$data = str_replace('"', "'+String.fromCharCode(34)+'", $data);
$data = str_replace ("\r\n", '\n', $data);
$data = str_replace ("\r", '\n', $data);
$data = str_replace ("\n", '\n', $data);
?>
el = document.getElementById('<?php echo $el; ?>');
el.innerHTML = '<?php echo $data; ?>';
Following is the form processor, generating the random numbers result for the AJAX output/update.
<?php // handler.php
/////////////////////////////////////////////////////////////////
// Random Dice Value Generator v1.0 //
// http://www.dragonfallrpg.com //
// Orion Johnson Copyright 2007 //
// //
// This script is used to create a random number based //
// values from the user's input //
/////////////////////////////////////////////////////////////////
/* double rolldice(int, int)
* - generates a random value based on the numbers passed as an argument
* - maximum iterations = 20 (can be changed in the user form)
* - maximum number of sides per function call = 4, 6, 8, 10, 12, 20, or 100 (can be changed)
*
* Usage: To generate a random total value as if one had thrown that many dice:
* Note: Future revisions may include the ability to add additional lines to the user form
* to mix types of simulated dice being thrown.
*
* array $no_of_dice(x-1); array value "x" taken from user form
* var $no_of_sides; value taken from user form
* var $total_value; sum of values from entire array
* echo $total_value;
*/
// Check variables
if (empty($_GET['no_of_dice'])) {
die ('<span style="color:red;">Number of dice value invalid!</span>');
}
if (empty($_GET['no_of_sides'])) {
die ('<span style="color:red;">Number of sides value invalid!</span>');
}
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 1000003);
}
function rolldice()
{
$total_value = 0; /* sum of values from entire array */
srand(make_seed()); /* seed random number generator // 1,000,003 is a prime number */
/* start loop structure from 0 to $no_of_dice */
for($i = 0; $i < $_GET['no_of_dice']; $i++)
{
$randnum = rand(1, $_GET['no_of_sides']);
$total_value = $total_value + $randnum;
}
/* end loop */
/* print/return results to the screen */
// echo 'Total value for dice: ' + rolldice();
return $total_value;
}
// Taken from http://www.sebflipper.com/?page=code&file=password.php
// for array iteration see also: http://www.php-scripts.com/php_diary/122799.php3
?>
If there is a simpler way to perform a div update with a random result based on form input, I'm all ears. This has been a headache for too long for me. I'm no code-head, just know enough to tinker and make some things work and understand most things when explained.

I haven't read through all the code, but since MediaWiki 1.17.0 there's a feature called ResourceLoader (if you have older version you should upgrade), which you can use for this purpose.
You can make the whole code into an extension to have it organized in a directory (let's say extensions/DiceBox). The DiceBox.php file in that folder would then be along these lines:
<?php
if( !defined( 'MEDIAWIKI' ) ) {
die();
}
$wgExtensionFunctions[] = 'DiceBoxInit';
$wgHooks['SkinTemplateToolboxEnd'][] = 'DiceBoxOnSkinTemplateToolboxEnd';
$wgResourceModules['ext.DiceBox'] = array(
'localBasePath' => dirname( __FILE__ ),
'remoteExtPath' => 'DiceBox',
'scripts' => 'ext.DiceBox.js',
'dependencies' => 'jquery'
);
function DiceBoxInit() {
global $wgOut;
$wgOut->addModules( 'ext.DiceBox' );
}
?>
<?php
function DiceBoxOnSkinTemplateToolboxEnd() {
$sides = array( 4, 6, 8, 10, 12, 20, 100 );
?>
</ul>
</div>
</div>
<div class="portlet" id="p-dicebox">
<h5>Orion's Dice Box</h5>
<div class="pBody">
<div id="dice-result" style="display: none;"></div>
<form id="dice-form">
<select name="no_of_dice">
<?php
for( $i = 1; $i <= 20; $i++ ) {
echo '<option value="', $i, '">', $i, '</option>';
}
?>
</select>
<select name="no_of_sides">
<?php
foreach( $sides as $n ) {
echo '<option value="', $n, '">d', $n, '</option>';
}
?>
</select>
<input type="button" value="Roll Dice" id="dice-roll" />
</form>
<?php
return true;
}
This code outputs the code box HTML in the sidebar and registers the following JavaScript file (ext.DiceBox.js) to be available on the page:
jQuery( document ).ready( function( $ ) {
$( '#dice-roll' ).click( function() {
$.get( mw.config.get( 'wgExtensionAssetsPath' ) + '/DiceBox/handler.php',
$( '#dice-form' ).serialize(), function( data )
{
$( '#dice-result' ).html( data ).append( '<hr />' ).show();
} );
} );
} );
This code simply uses jQuery (which is bundled with MediaWiki as of 1.16.0) to send a request to the server when the button is clicked and displays the result in the box.
In the handler.php file, there's no place where the random number gets output, so you need to add echo rolldice(); before the ?>.
Finally, to make the extensions fully work, add require_once $IP . '/extensions/DiceBox/DiceBox.php'; to the bottom of LocalSettings.php.

Related

JavaScript for loop in AJAX request not working

I have a bit of a problem with JavaScript for loop not looping.
Here is the code:
if (this.readyState === 4 && this.status === 200)
{
if(this.response)
{
console.log(this.response);
var data = JSON.parse(this.responseText);
var output = '';
console.log(data);
for(var i=1 ; i <= data.length ; i++)
{
console.log('i got here');
output += '<a href="'+data[i].platform_name+'">'+
'<div class="new-prod">' +
'<div class="flip">' +
'<div class="front">' +
'<img src="images/'+data[i].picture+'" alt="Image for '+data[i].product_name+'">'+
'<p class="name">'+data[i].product_name+' ('+data[i].platform_name+')</p>'+
'<p class="price">'+data[i].price+' Kč</p>'+
'</div>'+
'<div class="back">'+data[i].description+'</div>'+
'</div>'+
'</div>'+
'</a>';
}
console.log(i);
document.getElementById('new-container').innerHTML = output;
document.getElementById('lmbtn').setAttribute('data-offset',parseInt(offset)+8);
}
else
{
document.getElementById('lmbtn').textContent="Thats all";
}
}
As you can see i´m making AJAX request to the server and get JSON as response.
My code gets to the console.log(data), it logs parsed JSON to the console, but for some reason it skips the for loop. console.log('i got here'); doesn´t log. At the end it logs console.log(i) is 1 and sets the innerHTML of the container to empty string.
Please, excuse my bad english and thanks for any help.
You better use for(var i=1 ; i <= Object.keys(data).length ; i++) or for (var key in data) inside your for loop as a condition.

Restrict zip codes for custom shipping method is not working after hide the shipping method

we are really facing very strange problem here.
we are using 1.9.0.1 and custom shipping method.
We Hide Shipping Method Step in checkout using answer gave by #Marius here :
https://magento.stackexchange.com/questions/53355/remove-shipping-steps-in-onepage-checkout
But we have one problem here.
we allowed only some zip codes to place an order.
but here its allowing for all zip codes when user enter first time.
once user enter zip code and click on "Continue" button, it will go to next step [payment methods]
Payment method step
Than if user again come to Previous step and enter same zip code and if user click on "Continue"
button, than it will show error message in pop up - "Invalid shipping method"
This is fine, but it should not allow when user enter zip code for first time also.
Before everything was fine, once we hide shipping method , this problem happened. but for default shipping method it is working fine.
ex site : link & zip code 000000
we are using this code for restricting zip codes and finding shipping charges.
<?php
class extension_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract
{
/* Use group alias */
protected $_code = 'mpperproductshipping';
public function collectRates(Mage_Shipping_Model_Rate_Request $request){
$postCode = $request->getDestPostcode();
$restrictedCodes = array(
110001,
110002
); //restricted values. they can come from anywhere
if (!in_array($postCode, $restrictedCodes)) {
return false;
}
$result = Mage::getModel('shipping/rate_result');
/* Edited by vikas_mageworx */
$postcode=$request->getDestPostcode();
$countrycode=$request->getDestCountry();
$items=$request->getAllItems();
/* End Editing by vikas_mageworx */
$postcode=str_replace('-', '', $postcode);
$shippingdetail=array();
/* one start */
$shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items);
/* one end */
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if($mpassignproductId) {
$mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId);
$partner = $mpassignModel->getSellerId();
} else {
$collection=Mage::getModel('marketplace/product')
->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid));
foreach($collection as $temp) {
$partner=$temp->getUserid();
}
}
$product=Mage::getModel('catalog/product')->load($proid)->getWeight();
$weight=$product*$item->getQty();
if(count($shippingdetail)==0){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}else{
$shipinfoflag=true;
$index=0;
foreach($shippingdetail as $itemship){
if($itemship['seller_id']==$partner){
$itemship['items_weight']=$itemship['items_weight']+$weight;
$itemship['product_name']=$itemship['product_name'].",".$item->getName();
$itemship['item_id']=$itemship['item_id'].",".$item->getId();
$itemship['qty']=$itemship['qty']+$item->getQty();
$shippingdetail[$index]=$itemship;
$shipinfoflag=false;
}
$index++;
}
if($shipinfoflag==true){
array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId()));
}
}
}
$shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail);
if($shippingpricedetail['errormsg']!==""){
Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']);
return $result;
}
/*store shipping in session*/
$shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo');
$shippingAll[$this->_code]=$shippingpricedetail['shippinginfo'];
Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll);
$method = Mage::getModel('shipping/rate_result_method');
$method->setCarrier($this->_code);
$method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title'));
/* Use method name */
$method->setMethod($this->_code);
$method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name'));
$method->setCost($shippingpricedetail['handlingfee']);
$method->setPrice($shippingpricedetail['handlingfee']);
$result->append($method);
return $result;
}
public function getShippingPricedetail($shippingdetail,$shippostaldetail) {
$shippinginfo=array();
$handling=0;
$session = Mage::getSingleton('checkout/session');
$customerAddress = $session->getQuote()->getShippingAddress();
/* Edited by vikas_boy */
$customerPostCode = $shippostaldetail['postalcode'];
$items = $shippostaldetail['items'];
/* End Editing by vikas_boy */
/* one */
foreach($shippingdetail as $shipdetail) {
$seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']);
$sellerAddress = $seller->getPrimaryShippingAddress();
$distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode);
// echo "distance ".$distance;die;
$price = 0;
$itemsarray=explode(',',$shipdetail['item_id']);
foreach($items as $item) {
$proid=$item->getProductId();
$options=$item->getProductOptions();
$mpassignproductId=$options['info_buyRequest']['mpassignproduct_id'];
if(!$mpassignproductId) {
foreach($item->getOptions() as $option) {
$temp=unserialize($option['value']);
if($temp['mpassignproduct_id']) {
$mpassignproductId=$temp['mpassignproduct_id'];
}
}
}
if (Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($proid))
{
continue;
}
$mpshippingcharge = 0;
$localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance');
$regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance');
$stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance');
if(in_array($item->getId(),$itemsarray)) {
if($mpassignproductId) {
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge();
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge();
}
} else {
// echo "imte ".$item->getProductId();
if($distance < $localDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge();
// echo "imte ".$item->getProductId();
// echo "ship ".$mpshippingcharge;
} elseif($distance > $localDistance && $distance < $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge();
} elseif($distance > $regionalDistance) {
$mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge();
}
}
/* tt */
// echo "test ".$mpshippingcharge;die;
if(!is_numeric($mpshippingcharge)){
$price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty()));
}else{
$price=$price+($mpshippingcharge * floatval($item->getQty()));
}
}
}
$handling = $handling+$price;
$submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0));
array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id']));
}
$msg="";
return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg);
}
/* one end */
/* tt start */
private function getDistanse($origin,$destination) {
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$response_all = json_decode($response);
$distance = $response_all->rows[0]->elements[0]->distance->value / 1000;
if($distance==0){
$zips = array(
$origin,$destination
// ... etc ...
);
$geocoded = array();
$serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false";
$curl = curl_init();
foreach ($zips as $zip) {
curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip)));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$data = json_decode(curl_exec($curl));
$info = curl_getinfo($curl);
if ($info['http_code'] != 200) {
// Request failed
} else if ($data->status !== 'OK') {
// Something happened, or there are no results
} else {
$geocoded[$zip] =$data->results[0]->geometry->location;
}
}
$distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng);
}
return $distance;
}
public function DistAB($lat_a,$lon_a,$lat_b,$lon_b)
{
$measure_unit = 'kilometers';
$measure_state = false;
$measure = 0;
$error = '';
$delta_lat = $lat_b - $lat_a ;
$delta_lon = $lon_b - $lon_a ;
$earth_radius = 6372.795477598;
$alpha = $delta_lat/2;
$beta = $delta_lon/2;
$a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ;
$c = asin(min(1, sqrt($a)));
$distance = 2*$earth_radius * $c;
$distance = round($distance, 4);
$measure = $distance;
return $measure;
}
}
/* tt end */
onepage.phtml : app/design/frontend/default/em0113/template/checkout/onepage.phml
<div class="page-title">
<h1><?php echo $this->__('Checkout') ?></h1>
</div>
<script type="text/javascript" src="<?php echo $this->getJsUrl('varien/accordion.js') ?>"></script>
<script type="text/javascript" src="<?php echo $this->getSkinUrl('js/opcheckout.js') ?>"></script>
<ol class="opc" id="checkoutSteps">
<?php $i=0; foreach($this->getSteps() as $_stepId => $_stepInfo): ?>
<?php if (!$this->getChild($_stepId) || !$this->getChild($_stepId)->isShow()): continue; endif; $i++ ?>
<li id="opc-<?php echo $_stepId ?>" class="section<?php echo !empty($_stepInfo['allow'])?' allow':'' ?><?php echo !empty($_stepInfo['complete'])?' saved':'' ?>">
<div class="step-title">
<span class="number"><?php echo $i ?>.</span>
<h2><?php echo $_stepInfo['label'] ?></h2>
<?php echo $this->__('Edit') ?>
</div>
<div id="checkout-step-<?php echo $_stepId ?>" class="step a-item" style="display:none;">
<?php echo $this->getChildHtml($_stepId) ?>
</div>
</li>
<?php endforeach ?>
</ol>
<script type="text/javascript">
//<![CDATA[
var accordion = new Accordion('checkoutSteps', '.step-title', true);
<?php if($this->getActiveStep()): ?>
accordion.openSection('opc-<?php echo $this->getActiveStep() ?>');
<?php endif ?>
var checkout = new Checkout(accordion,{
progress: '<?php echo $this->getUrl('checkout/onepage/progress') ?>',
review: '<?php echo $this->getUrl('checkout/onepage/review') ?>',
saveMethod: '<?php echo $this->getUrl('checkout/onepage/saveMethod') ?>',
failure: '<?php echo $this->getUrl('checkout/cart') ?>'}
);
//]]>
</script>
What you can do is bind a javascript event to the input field of pincode and send the request everytime when someone is typing in the pincode like this:
<input type = "text" onchange = "myfun(this.value)">
And then bind a javascript function myfun to it and make an AJAX call to your pincode checking controller, this will take the value once you finish typing into the text box
Otherwise you can also go with
<input type = "text" onkeypress = "myfun(this.value)">
And then again bind a javascript function myfun to it and make an AJAX call to your pincode checking controller, this will take the value even when you are typing into the text box
Ok, in your onepage template, write this code:
jQuery('#billing:postcode').change(function(){
// your ajax call to your controller where you are verifying your pincode, something like:
jQuery.ajax({
url: "path/to/your/controller",
data: this.value,
success: function(response){
if(response == true){
// your success action
} else{
//your failure action
}
}
})
})

yii2: call controller action in sortable jquery with ajax

I am using jquery sortable plugin to drag and drop items and setting their order. But I am unable to get the response from Ajax. I want to call the controller action from the js so that when I drag the item and drop it, then a response should come. The drag and drop functionality is working fine.
I tried this:
My View:
<div class="status-index info">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<ul class="sortable_status">
<?php
$items = StatusType::find()->orderBy('order')->all();
//var_dump($items);exit;
//$content = array();
foreach ($items as $item) {
echo '<li class="text-items"><label for="item'.$item->order.'"><span class="items-number">'.$item->order.'</span></label>
<label id="item'.$item->order.'" />'.$item->title.'</label>
<br/>
</li>';
}
?>
</ul>
</div>
JS:
$(function () {
var LI_POSITION = 'li_position';
$("ul.sortable_status").sortable({
update: function(event, ui) {
//create the array that hold the positions...
var order = [];
//loop trought each li...
$('.sortable_status li').each( function(e) {
//add each li position to the array...
// the +1 is for make it start from 1 instead of 0
order.push( $(this).attr('id') + '=' + ( $(this).index() + 1 ) );
});
// join the array as single variable...
var positions = order.join(';')
//use the variable as you need!
alert( positions );
// $.cookie( LI_POSITION , positions , { expires: 10 });
}
/*handle : '.handle',
update : function () {
var order = $('.sortable_status').sortable('serialize');
$(".info").load("process-sortable.php?"+order);
} */
});
});
Controller:
public function actionSortable()
{
/* foreach ($_GET['text-items'] as $position => $item)
{
$sql[] = "UPDATE `status_type` SET `order` = $position WHERE `id` = $item";
}*/
if ( isset( $_COOKIE['li_position'] ) ) {
//explode the cockie by ";"...
$lis = explode( ';' , $_COOKIE['li_position'] );
// loop for each "id_#=#" ...
foreach ( $lis as $key => $val ) {
//explode each value found by "="...
$pos = explode( '=' , $val );
//format the result into li...
$li .= '<li id="'.$pos[0].'" >'.$pos[1].'</li>';
}
//display it
echo $li;
// use this for delete the cookie!
// setcookie( 'li_position' , null );
} else {
// no cookie available display default set of lis
echo '
empty
';
}
}
why don't use an ajax call on stop ?
$("ul.sortable_status").sortable({
stop: function(event, ui) {
$.ajax({
type: "POST",
url: myUrl
data: {my-data: "any-value"}
})
.success(function(data) {
//your logic here
})
.fail(function() {
//your logic here
});
}
});
I used to define in my layout on the head tag of my html my variables as following
<head>
<script>
var myUrl = "<?php echo Url::to(['controller/action']); ?>";
</script>
</head>

how to display image from uploads folder in wordpress

I am just learning to create meta box to upload file in wp-content/uploads folder through below code:
//display image meta box
function display_image_box() {
global $post;
wp_nonce_field( plugin_basename( __FILE__ ), 'wp_custom_noncename' );
echo '<input id="post_media" type="file" name="post_media" value="" size="25" />';
}
//upload image
function update_custom_meta_data( $id, $data_key, $is_file = false ) {
global $post;
if( $is_file && ! empty( $_FILES ) ) {
$upload = wp_handle_upload( $_FILES[$data_key], array( 'test_form' => false ) );
if( isset( $upload['error'] ) && '0' != $upload['error'] ) {
wp_die( 'There was an error uploading your file. ' );
} else {
update_post_meta( $id, $data_key, $upload );
}
}
}
//save image
function save_custom_meta_data( $id ) {
if( ! wp_verify_nonce( $_POST['wp_custom_noncename'], plugin_basename( __FILE__ ) ) ) {
return;
}
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
update_custom_meta_data( $id, 'post_media', true );
}
add_action( 'save_post', 'save_custom_meta_data' );
//register script
function register_admin_scripts() {
wp_register_script( 'custom_admin_script', get_template_directory_uri() . '/js/admin.js' );
wp_enqueue_script( 'custom_admin_script' );
}
add_action( 'admin_enqueue_scripts', 'register_admin_scripts' );
this working & uploaded file nicely but i cant display it cause getting the array something like this:
> [post_media] => Array
(
[0] => a:3:{s:4:"file";s:81:"E:wampwwwtestchild/wp-content/themes/twentyeleven/uploads/2012/12/coffee_star.jpg";s:3:"url";s:60:"wp-content/themes/twentyeleven/image/2012/12/coffee_star.jpg";s:4:"type";s:10:"image/jpeg";}
)
so how can i display the image file now ?
Since the custom fields are saved in _postmeta table, we will get it by $post->ID.
$media = stripslashes(get_post_meta($post->ID, 'post_media', true));
if (isset($media[0])){
echo '<img src="'.$media.'" alt="images" />';
}
Hope it helps...
And if you want to try this code.
Upload Script
<script type="text/javascript">
var formfield = '';
$j(document).ready(function(){uploadimagebutton();});
function uploadimagebutton() {
$j('#upload_image_button').click(function() {
formfield = $j(this).prev().attr('name');
tb_show('', 'media-upload.php?type=image&TB_iframe=true');
return false;
});
window.original_send_to_editor = window.send_to_editor;
window.send_to_editor = function(html){
if (formfield) {
imgurl = $j(html).attr('src');
$j('#'+formfield).val(imgurl);
tb_remove();
$j('#pagebackgroundthumb').html('<img src="'+imgurl+'" alt="" style="max-width:85%;" />');
} else {
window.original_send_to_editor(html);
}
};
$j('#delete_image_button').click(function(){
formfield = $j(this).prev().prev().attr('name');
$j('#'+formfield).attr('value', '');
$j('#pagebackgroundthumb').html('');
});
}
</script>
place this in your theme function.php
<?php
/* -------------------------------------------------------------
Meta boxes
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
add_action('edit_post', 'adj_update');
add_action('save_post', 'adj_update');
add_action('publish_post', 'adj_update');
/* Use the admin_menu action to define the custom boxes */
add_action('admin_menu', 'adj_add_custom_box');
/* Adds a custom section to the "advanced" Post and Page edit screens */
function adj_add_custom_box() {
if( function_exists( 'add_meta_box' )) {
add_meta_box( 'addsettings', 'Additional Settings',
'adj_inner_custom_box', 'page', 'advanced', 'high' );
}
}
/* Prints the inner fields for the custom post/page section */
function adj_inner_custom_box() {
// Use nonce for verification
echo '<input type="hidden" name="myplugin_noncename" id="myplugin_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
// The actual fields for data entry
global $post;
$subtitle = stripslashes(get_post_meta($post->ID, 'subtitle', true));
$pagebackground = stripslashes(get_post_meta($post->ID, 'pagebackground', true));
?>
<div class="inside">
<label for="subtitle"><strong>Page Subtitle:</strong> </label>
<input type="text" name="subtitle" value="<?php echo $subtitle ?>" id="subtitle" style="width:95%" />
<p>If menu title is different with page title, please type here the desired page title.</p>
<label for="pagebackgroundthumb"><strong>Page Background Image:</strong> </label>
<div id="pagebackgroundthumb"><?php if(!empty($pagebackground))echo '<img src="'.$pagebackground.'" alt="" width="80%" />';?></div>
<input id="upload_image" name="pagebackground" type="hidden" size="45" value="<?php echo $pagebackground;?>">
<input class="button-secondary" id="upload_image_button" value="Upload/Select an image" type="button"><input class="button-secondary" id="delete_image_button" value="Delete" type="button">
</div>
<?php
}
function adj_update($id) {
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename(__FILE__) )) {
return $post_id;
}
if ( 'page' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_page', $post_id ))
return $post_id;
} else {
return $post_id;
}
$label = $_POST['subtitle'];
$pagebackground = $_POST['pagebackground'];
if (!empty($label)) {
$meta_value = get_post_meta($id, 'subtitle', true);
if(!empty($meta_value)) {
update_post_meta($id, 'subtitle', $label);
} else {
add_post_meta($id, 'subtitle', $label, true);
}
} else {
delete_post_meta($id, 'subtitle');
}
if (!empty($pagebackground)) {
$meta_value = get_post_meta($id, 'pagebackground', true);
if(!empty($meta_value)) {
update_post_meta($id, 'pagebackground', $pagebackground);
} else {
add_post_meta($id, 'pagebackground', $pagebackground, true);
}
} else {
delete_post_meta($id, 'pagebackground');
}
}
?>

$ajax is being send but is missing a value

Ok, so my script tries to request from php results from mysql and load them into a div. The results are based on nid value which is has to send this value is extracted from id="record-#" the record- is removed and the # is left to be used by ajax as id for the nid.
here is the ajax data function
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "_class/view.php",
data: "ajax=1&nid=" + parent.attr('id'),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {$("#note_utm_nt").html(errorThrown);}
});
});
$("#note_utm_con_cls").click(function() {
$("#note_utm_con").hide();
});
});
and here is the rest of the page
<div id="note_utm_con" style="display: none;">
<button id="note_utm_con_cls" style="width: 20px;float: right; padding: 2px;clear: both;">X</button>
<div id="note_utm"></div>
<div id="note_utm_nt"></div>
</div>
<?php
class notes {
var $host;
var $username;
var $password;
var $table;
public function display_notes() {
$q = "SELECT * FROM `notice` ORDER BY nid ASC LIMIT 12";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
if($type == 1) {
$type = "posted a comment."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/megaphone.png";
} elseif($type == 2) {
$type = "raised a support ticket."; $icon = "http://cdn1.iconfinder.com/data/icons/basicset/help_16.png";
} elseif($type == 3) {
$type = "added new photo."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/photo.png";
} elseif($type == 4) {
$type = "updated profile details."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/user_info.png";
} else { }
$entry_display .= <<<ENTRY_DISPLAY
<ul class="list">
<li id="$nid">
<a href="javascript:;" id="$nid" onClick="retun false;" class="note">
<img src="$icon" />
$author,
$type
</a>
</li>
</ul>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<ul class="list">
<li>
<p>
<img src="http://cdn1.iconfinder.com/data/icons/basicset/monitor_16.png" />
Nothing to display
</p>
</li>
</ul>
ENTRY_DISPLAY;
}
return $entry_display;
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this;
}
private function note_type() {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return $type;
}
}
?>
so when a LI with a class="note" is clicked it triggers AJAX call. The call then uses the ID in the href to extract the $nid from the id="record-
In my case it seems as AJAX is sending the request since view.php returns the fields where the data should be but it does not seem to pass much needed nid so PHP is uable to select proper nid from MySQL to use.
Can some one tell me whats wrong with it and how it can be fixed to get the id?enter code here
Your quotation marks are wrong. Try this:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),
Edit: Unless you haven't posted the full code still, you don't actually set parent anywhere. This means that you will use the window.parent object, which surprisingly enough doesn't have an id. You should use this.parentNode.id instead:
data: "ajax=1&nid=" + this.parentNode.id,
From what you've written it looks as if you're passing the parent.attr("id") replace call as a string rather than extracting the variable:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),

Resources