I'm using a Wordpress plugin that I'm trying to customize for my needs but I'm very new to Javascript. The plugin calculates the distance between two zip codes which is what $distance is. I created a drop down menu with different values based on vehicle size. What I want to do is display the distance multiplied by the value assigned to each vehicle size (which is the cost per mile). Any help would be appreciated. Thank you.
<?php
/**
* Plugin Name: WP Distance Calculator
* Plugin URI: http://phpcodingschool.blogspot.com/
* Description: This plugin claculates distance between two near by locations.
* Version: 1.0.0
* Author: Monika Yadav
* Author URI: http://phpcodingschool.blogspot.com/
* License: GPL2
*/
class DistanceWPCalculator
{
public function __construct()
{ //action definations
add_shortcode( 'distance_calculator', array( &$this, 'distanceWPfrontend' ) );
add_action( 'wp_ajax_nopriv_distancewpcalculator', array( &$this, 'distancewpcalculator_calculate' ) );
add_action( 'wp_ajax_distancewpcalculator', array( &$this, 'distancewpcalculator_calculate' ) );
add_action( 'init', array( &$this, 'init' ) );
}
public function init()
{
wp_enqueue_script( 'distancewpcalculator', plugin_dir_url( __FILE__ ) . 'js/calculatedistance.js', array( 'jquery' ) );
wp_localize_script( 'distancewpcalculator', 'DistanceCalculator', array(
'ajaxurl' => admin_url( 'admin-ajax.php' )
) );
?>
<script>
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php
wp_enqueue_style( 'DistanceWPCalculator-Style', plugin_dir_url( __FILE__ ) . 'css/style.css', array(), '0.1', 'screen' );
}
public function distancewpcalculator_calculate()
{
// The $_POST contains all the data sent via ajax
if ( isset($_POST) ) {
$from = urlencode($_POST['from']);
$to = urlencode($_POST['to']);
$data = file_get_contents("http://maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&sensor=false");
$data = json_decode($data);
$time = 0;
$distance = 0;
foreach($data->rows[0]->elements as $road) {
$time += $road->duration->value;
$distance += $road->distance->value;
}
$time =$time/60;
$distance =round($distance/1609.344);
//Output
if($distance!=0){
echo "<div id='result_generated'>";
echo "From: ".$data->origin_addresses[0];
echo "<br/>";
echo "To: ".$data->destination_addresses[0];
echo "<br/>";
echo "Time: ".gmdate("H:i", ($time * 60))." hour(s)";
echo "<br/>";
echo "Distance: ".$distance." mile(s)";
echo "</div>";
}else{
echo "Sorry only nearby distance can be calculated.";
}
}
die();
}
//Function to display form on front-end
public function distanceWPfrontend( $atts ) {
?>
<form method ="post" id="calculator" >
<div class="DC_title">Distance Calculator</div>
<input type="text" id="from" name="from" placeholder="From.."></br>
<input type="text" id="to" name="to" placeholder="To.."></br>
<select id="carType" onchange="carsize()">
<option value=".45">Motorcycle</option>
<option value=".6">Small Sedan</option>
<option value=".65">Large Sedan</option>
<option value=".7">Wagon/Hatchback</option>
<option value=".7">Small SUV</option>
<option value=".8">Large SUV</option>
<option value=".8">Minivan</option>
<option value=".75">Small Truck</option>
<option value=".8">Large Truck</option>
</select>
<input type="button" id="calculate" name="calculate" value="Calculate">
</form></br>
<div id="result"></div>
<?php
}
}
$distancewpcalculator = new DistanceWPCalculator();
?>
This is actually PHP. In your distancewpcalculator_calculate() function you calculate the distance based on the results that the Google Maps API returns. You store the calculated distance in the $distance variable (specifically $distance =round($distance/1609.344);). In that assignment you convert the recorded $distance value from Km to Mi.
You should modify your HTML select tag and values to something like this:
<select id="carType" name="carType">
<option value=".45">Motorcycle</option>
<option value=".6">Small Sedan</option>
<option value=".65">Large Sedan</option>
<option value=".7">Wagon/Hatchback</option>
<option value=".7">Small SUV</option>
<option value=".8">Large SUV</option>
<option value=".8">Minivan</option>
<option value=".75">Small Truck</option>
<option value=".8">Large Truck</option>
</select>
Doing this will include the "carType" value in the $_POST data. Now that it is in the post data, you can get the value selected by doing $_POST['carType']. Now that data is recorded we can multiply the value of the distance by the carType selected.
public function distancewpcalculator_calculate()
{
// The $_POST contains all the data sent via ajax
if (isset($_POST)) {
...
$distance = round($distance / 1609.344);
$carType = $_POST['carType'];
$cost = $carType * $distance;
//Output
if ($distance != 0) {
...
echo "Distance: " . $distance . " mile(s)";
echo "<br />";
echo "Cost: {$cost}";
echo "</div>";
} else {
...
}
}
}
The calculated $cost is a product of the selected vehicle type ($carType) and the calculated distance between the two locations ($distance);
Related
I am creating a card calculator form where you can select a card type and select a quantity and a price is returned.
I am using a csv file for the pricing and I have it all working great. as a simple HTML Form displayed through a shortcode in WordPress.
<?php
// Get CSV
$ch = fopen($standard_csv, "r");
$header_row = fgetcsv($ch);
// Get array of rows
$rows = array_map('str_getcsv', file($standard_csv));
// Remove first row (header row) as we already have this separately
unset( $rows[0] );
?>
<!-- The Form -->
<form action="" method="post" name="calc" id="calc">
Type:
<select name="card" id="card">
<option value="">Please Select</option>
<?php
// Remove first blank cell from $header
unset( $header_row[0] );
foreach ( $header_row as $key => $card ){
echo '<option value="' . $key . '">' . $card . '</option>';
}
?>
</select>
Quantity:
<select name="quantity" id="quantity">
<option value="">Please Select</option>
<?php
foreach ( $rows as $key => $row ){
echo '<option value="' . $key . '">' . $row[0] . '</option>';
}
?>
</select>
<input type="submit" name="get-price" value="Get Price!">
</form>
<?php
if ( isset( $_POST['get-price'] ) ){
$card = $_POST['card'];
$quantity = $_POST['quantity'];
echo 'Price: £' . $rows[$quantity][$card];
}
?>
This is great but I want to display the returned price using AJAX so I do not have to refresh the page when a user requests a price for their chosen card and quantity.
I have my scripts enqueued like so:
wp_enqueue_script( 'custom_script', plugin_dir_url( __FILE__ ) . 'js/custom.js', array('jquery'), '1.0' );
wp_localize_script( 'custom_script-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),
add_action('wp_ajax_get_price', 'get_price');
add_action('wp_ajax_nopriv_get_price', 'get_price');
function get_price(){
$card = $_POST['card'];
$quantity = $_POST['quantity'];
return 'Price: £' . $rows[$quantity][$card];
}
I have this in my Javascript File
$('#calc').submit(function (event) {
event.preventDefault();
var card = jQuery('#card').val();
var quantity = jQuery('#quantity').val();
jQuery.ajax({
type: 'POST',
url: ajax_object.ajax_url,
data: {
action: 'get_price',
card: card,
quantity: quantity
},
success: function (data) {
console.log(data);
},
error: function (errorThrown) {
console.log(data);
alert(errorThrown);
}
});
});
I have totally confused myself and I have tried to follow many tutorials, but I just cant work out the correct logic to be able to output a price from the CSV file using AJAX without reloading the page.
I know this code is totally not right, but please any help to set me in the right direction would be extremely appreciated.
I just need help understanding the logic on how to handle passing the variables and prices between the ajax and the php function in order to return a price from the CSV File.
Thank you.
Don't return from ajax - exit.
Replace return 'Price: £' . $rows[$quantity][$card];
with
wp_die('Price: £' . $rows[$quantity][$card]);
Best wishes,
Mitchell
I have been following a few tutorials online for how to do this, and I do not know where I missed the mark... when I press my submit button, it does nothing but reload the page. I do not see any errors in loading my js though in the console of chrome so I think that might be my issue. But still unsure.
Basically, people can provide a new billing_address on their dashboard, and the billing address is associated with a user and sku.
Here is my form with three items (user, sku, address);
$loop = new WP_Query( $args );
echo '<form id="addressform" method = "post">';
echo '<br><select id="sku" name="sku" required >';
echo '<option value="empty">-- Select Coin--</option>';
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
echo '<option value=' . $product->get_sku() . '>' . $product->get_sku() . ' </option>';
endwhile;
echo '</select>';
echo '<input type="text" placeholder="Insert new address here" id="address" name="address" size="40" required />';
echo '<input type="hidden" id="userid" name="userid" value="' . $userid . '">';
echo '<input type="submit" id="submit" name="submit" value="Submit">';
echo '</form>';
echo '<div class="alert alert-danger display-error" style="display: none"></div>';
here is my javascript file known as address_submit.js
jQuery(document).ready(function($) {
jQuery('form#addressform').on('submit', function(e){{
jQuery.ajax({
type: 'POST',
dataType: 'json',
url: submitaddress_ajax_obj.ajaxurl,
data: {
'userid' : jQuery('form#addressform #userid').val(),
'sku' : jQuery('form#addressform #sku').val(),
'address' : jQuery('form#addressform #address').val(),
'action' : 'submitaddress'
},
success : function(data){
if (data.code == "200"){
alert("Success: " +data.msg);
} else {
jQuery(".display-error").html("<ul>"+data.msg+"</ul>");
jQuery(".display-error").css("display","block");
}
}
});
e.preventDefault();
});
});
and lastly, I knew I needed to add it to my functions.php for my child theme so I created a second file (address_verifier.php) and included it like this in my themes functions.php :
require_once( __DIR__ . '/include/address_verifier.php');
And lastly, here is what is in the address_verifier.php
function submitaddress_ajax_enqueue() {
// Enqueue javascript on the frontend.
wp_register_script('submitaddress-ajax-script', get_stylesheet_directory_uri() . '/js/address_submit.js', array('jquery') );
wp_enqueue_script('submitaddress-ajax-script');
// The wp_localize_script allows us to output the ajax_url path for our script to use.
wp_localize_script('submitaddress-ajax-script','submitaddress_ajax_obj',array( 'ajaxurl' => admin_url( 'admin-ajax.php' ),'loadingmessage' => __('Submitting Address...') ));
}
add_action( 'wp_enqueue_scripts', 'submitaddress_ajax_enqueue' );
add_action( 'wp_ajax_submitaddress', 'submitaddress' );
add_action( 'wp_ajax_nopriv_submitaddress', 'submitaddress' );
function submitaddress() {
global $woocommerce,$wpdb,$product;
$errorMSG = [];
//check if data is present
$user = $_POST['userid'];
//check sku selected
if (empty($_POST['sku'])) {
$errorMSG .= "<li>Please select a product.</li>";
} else {
$sku = $_POST['sku'];
}
//check address input
if (empty($_POST['address'])) {
$errorMSG .= "<li>Please enter an address.</li>";
} else {
$address = $_POST['address'];
}
if(empty($errorMSG)){
$updateaddress = $wpdb->query( $wpdb->prepare("REPLACE INTO ".$wpdb->prefix."newaddress (user, sku, address) VALUES (%d, %s, %s)", $user, $sku, $address ) );
$msg = "<strong> <i class='fa fa-check' aria-hidden='true'></i> Your <font color='red'>" . $sku . " </font>address has been updated. </strong>";
echo json_encode(['code'=>200, 'msg'=>$msg]);
die;
}
echo json_encode(['code'=>404, 'msg'=>$errorMSG]);
die();
}
move e.preventDefault(); to the top of the function.
I need two drop downs (City and Area). When I select a City from the first drop down the second drop down should be populated with the Area in that city. I have a table in which both the City and Area are stored.
I have the Wordpress page like this:
<form name="form" method="post" action="">
<label>City:</label>
<select name="city" class="city">
<option>Select City</option>
[insert_php]
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "builderstoday.in";
$conn = mysqli_connect( $servername, $username, $password, $dbname );
$db_table = "aacblocks";
$sql = "SELECT DISTINCT City FROM ".$db_table;
$result = mysqli_query( $conn, $sql );
if ( mysqli_num_rows($result) > 0 ) {
while ( $row = mysqli_fetch_array( $result ) ){
echo "<option value='" . $row['City'] . "'>" . $row['City'] . "</option>" ;
}
}
mysqli_close($conn);
[/insert_php]
</select>
<label>Area: </label>
<select name="area" class="area">
<option>Select Area</option>
</select>
</form>
I have created a plugin to use ajax in Wordpress:
Ajax.php
<?php
/**
* Plugin Name: Ajax Cities
* Description: Allows to select cities according to the country
* Version: 1.0.0
* Author: Jayesh Borase
* License: GPL2
*/
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_enqueue_script( 'ajax-script', plugins_url( '/ajax.js', __FILE__ ), array( 'jquery' ) );
wp_localize_script( 'ajax-script', 'ajax_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
) );
}
function my_action() {
$city = $_REQUEST['city'];
$DB_NAME = $_REQUEST['DB_NAME'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "builderstoday.in";
$conn = mysqli_connect($servername, $username, $password, $dbname);
$db_table = "aacblocks";
$sql = "SELECT DISTINCT Area FROM " . $DB_NAME . "Where City=" . $city;
$result = mysqli_query( $conn, $sql );
if ( mysqli_num_rows( $result ) > 0 ) {
while ( $row = mysqli_fetch_array( $result ) ) {
echo "<option value='" . $row['Area'] . "'>" . $row['Area'] . "</option>" ;
}
}
}
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action');
?>
and the ajax.js file:
( function( $ ) {
$( document ).ready( function () {
$( '.city' ).change( function () {
var City = $( this ).val();
var DB_Table = "<?php echo $db_table ?>";
$.ajax( {
cache: false,
type: "POST",
url: ajax_object.ajax_url,
data: {
action : 'my_action',
city : City,
DB_NAME : DB_Table,
},
success: function ( areadata ) {
jQuery( '.area' ).html( areadata );
}
} );
} );
} );
} )( jQuery );
Please help me to achieve this. The main thing is this is only for one product and I have more than 50 products i.e. I have to repeat the same thing for more than 50 products (table).
I Developing one project and I stuck in small thing which is very small for PHP Expert :D Which i'm not
I'm Trying to make Dropdown list of Custom taxonomies which work on select go to that Custom taxonomies page.
But After lot of search I found Solution But not doing action to go to the selected Custom taxonomies
First I found
<?php wp_dropdown_categories( 'taxonomy=my_custom_taxonomy' ); ?>
Second I found
function fjarrett_custom_taxonomy_dropdown( $taxonomy ) {
$terms = get_terms( $taxonomy );
if ( $terms ) {
printf( '<select name="%s" class="postform">', esc_attr( $taxonomy ) );
foreach ( $terms as $term ) {
printf( '<option value="%s">%s</option>', esc_attr( $term->slug ), esc_html( $term->name ) );
}
print( '</select>' );
}
}
Which I can use when I insert in any page code billow
<?php fjarrett_custom_taxonomy_dropdown( 'my_custom_taxonomy' ); ?>
Credit
https://frankiejarrett.com/2011/09/create-a-dropdown-of-custom-taxonomies-in-wordpress-the-easy-way/
BUT I DON'T KNOW NOW HOW I GONNA MAKE IT WORKING
Hope you can help me to find solution that from above any one solution can I able to make select and go thing.
Thanks in advance
POSSIBLE ANSWER - 1
I Found Possible Answer
<form id="category-select" class="category-select" action="<?php echo esc_url( home_url( '/' ) ); ?>" method="get">
<?php
$args = array(
'show_option_none' => __( 'Select category' ),
'show_count' => 1,
'orderby' => 'name',
'name' => 'cat',
'echo' => 0,
'taxonomy' => 'MyCustomTaxonomys',
'value_field' => 'slug'
);
?>
<?php $select = wp_dropdown_categories( $args ); ?>
<?php $replace = "<select$1 onchange='return this.form.submit()'>"; ?>
<?php $select = preg_replace( '#<select([^>]*)>#', $replace, $select ); ?>
<?php echo $select; ?>
<noscript>
<input type="submit" value="View" />
</noscript>
</form>
It Give me URL
www.website.com/?cat=xxx where xxx is my custom taxonomy
But I Want URL
www.website.com/cat/xxx where xxx is my custom taxonomy
Is it possible?
You
could use something like this :
<?php
function fjarrett_custom_taxonomy_dropdown( $taxonomy ) {
$terms = get_terms( $taxonomy );
if ( $terms ) {
printf( '<select name="%s" class="postform">', esc_attr( $taxonomy ) );
foreach ( $terms as $term ) {
printf( '<option value="%s" data-location="%s">%s</option>', esc_attr( $term->slug ), get_term_link(term_id), esc_html( $term->name ) );
}
print( '</select>' );
}
}
?>
Then use your javascript code to redirect depending on the value of the attribute data-location
I did it this way like you say with PHP with wordpres:
<?php function click_taxonomy_dropdown($taxonomy, $title) { ?>
<select name="<?php echo $taxonomy;?>" id="<?php echo $taxonomy;?>">
<option value="-1"><?php echo $title;?></option>
<?php
$terms = get_terms($taxonomy);
foreach ($terms as $term) {
$link = get_term_link( $term, $taxonomy );
if($term->parent == 0){
printf( '<option class="level-1" value="'.$link.'">%s</option>', $term->name );
}
}
echo '</select>';
?>
<?php } ?>
And then with JS:
var dropdown1=document.getElementById("yourtaxonomy");
function onCatChange1(){
if(dropdown1.options[dropdown1.selectedIndex].value>"")
location.href=dropdown1.options[dropdown1.selectedIndex].value
}
The JS just get the ID of your select and then go to value when options are selected
AT End I Found One Alternate Working Solution Writing here so it will help someone needful
<?php
$categories = get_categories('taxonomy=xxxx');
$select = "<select name='' id='cat' class='postform'>n";
$select.= "<option value='-1'>Select category</option>n";
foreach($categories as $category){
if($category->count > 0){
$select.= "<option value='".$category->slug."'>".$category->name."
</option>";
}
}
$select.= "</select>";
echo $select;
?>
<script type="text/javascript">
<!--
var dropdown = document.getElementById("cat");
function onCatChange() {
if (dropdown.options[dropdown.selectedIndex].value != -1) {
location.href = "<?php echo home_url();?>/yyyy/" + dropdown.options[dropdown.selectedIndex].value + "/";
}
}
dropdown.onchange = onCatChange;
-->
</script>
JUST SET Proper XXXX and YYYY Value and solve.
Credit: John B. Hartley
http://www.johnbhartley.com/2012/custom-taxonomy-category-dropdown/
Again Thank you all for your efforts
I have a PHP array that populates the first select dropdown list so the user can select a occupation. After the occupation is selected, the second drop down list gets loaded with the job positions for that occupation using a JavaScript function.
Then I use jQuery to change the action attr of the form based on the value of the second drop down. But it returns null because the <option></option> are being loaded through the JavaScript. If I hard code the <option></option> in the select box, then it works.
Just as a note. I am not using a database. I'm using a php array to hold the data for the 2 drop down lists. The array is already loaded on the page as an include at the top of the php page.
Three part question here.
First - how do I resolve my issue with the action attr?
Second - is there a way to accomplish the populating the second drop down using a different method which may work better?
Third - And if it is ajax, how can it get the php array data without pulling it from the server again, since the array is already loaded into the php page?
Here's my code arrangement
PHP Array
$pages = array(
// Engineer
'Engineer' => array('pageTitle' => 'Engineer', 'subpages' => array(
'Software Engineer' => 'Software',
'Embedded Software Engineer' => 'Embedded Software',)),
// Analyst
'Analyst' => array('pageTitle' => 'Analyst', 'subpages' => array(
'Systems-Analyst' => 'Systems',
'Data-Analyst' => 'Data',))
);
The Select and foreach loop
echo '<form method="POST" action="?position=" id="menuform">
<select name="occupation" id="occupation">
<optgroup label="Select Occupation">
<option value="" selected disabled>Select Occupation</option>';
foreach ($pages as $filename => $value) {
echo '
<option value="'.$filename.'"'.((strpos($position, $filename) !== false) ? ' selected' : '').'>'.$filename.'</option>';
} // foreach pages
echo '
</optgroup>
</select>
<select name="position" id="position" onchange="this.form.submit()">
</select>
</form>
';
JavaScript
<script type="text/javascript">
var occupation = document.getElementById("occupation");
var position = document.getElementById("position");
onchange(); //Change options after page load
occupation.onchange = onchange; // change options when occupation is changed
function onchange() {
<?php foreach ($pages as $filename => $value) {?>
if (occupation.value == '<?php echo $filename; ?>') {
option_html = "\n<? echo'<option selected disabled>Select Position</option>'; ?>\n";
<?php if (isset($value ['subpages'])) { ?>
<?php foreach ($value ['subpages'] as $subfilename => $subpageTitle) { ?>
option_html += "<? echo '<option value=\''.urlencode($subfilename).'\''.(($position == $subfilename) ? ' selected' : '').'>'.$subpageTitle.' '.$filename.'</option>'; ?>\n";
<?php } ?>
<?php } ?>
position.innerHTML = option_html;
}
<?php } ?>
}
</script>
jQuery
$('#menuform').attr('action',$('#menuform').attr('action')+$('#position').val());
Regarding you first question, how to dynamically set form action, here is a test code:
<?php
$pages = array(
'Engineer' => array(
'pageTitle' => 'Engineer',
'subpages' => array(
'Software Engineer' => 'Software',
'Embedded Software Engineer' => 'Embedded Software',
)
),
'Analyst' => array(
'pageTitle' => 'Analyst',
'subpages' => array(
'Systems-Analyst' => 'Systems',
'Data-Analyst' => 'Data',
)
)
);
?>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4 id="form-action-shower">Form action: <span></span></h4>
<form method="POST" action="?position=" id="menuform">
<select name="occupation" id="occupation">
<optgroup label="Select Occupation">
<option value="" selected disabled>Select Occupation</option><br />
<?php foreach($pages as $occupation => $occData): ?>
<option value="<?php echo $occupation ?>"><?php echo $occupation ?></option>
<?php endforeach ?>
</optgroup>
</select>
<select name="position" id="position">
<optgroup label="Select Position">
<option value="" selected disabled>Select Position</option><br />
<?php foreach($pages as $occupation => $occData): ?>
<?php foreach($occData['subpages'] as $key => $value): ?>
<option value="<?php echo $key ?>"><?php echo $value ?></option>
<?php endforeach ?>
<?php endforeach ?>
</optgroup>
</select>
<input type="submit" value="Click here to test form action">
</form>
<script>
$('#position').change(function() {
var form_action = '?position=' + $(this).val();
$('#menuform').attr('action', form_action);
$('#form-action-shower span').html(form_action);
});
</script>
Regarding your 2nd and 3rd question:
You can use JSON to solve such issues. Here is an example I found: http://jsfiddle.net/YqLh8/
You can use PHP to have the array structure available in JS:
<?php
$pages = array(
'Engineer' => array('pageTitle' => 'Engineer', 'subpages' => array(
'Software Engineer' => 'Software',
'Embedded Software Engineer' => 'Embedded Software',)
),
'Analyst' => array('pageTitle' => 'Analyst', 'subpages' => array(
'Systems-Analyst' => 'Systems',
'Data-Analyst' => 'Data',)
)
);
$json_pages = json_encode($pages);
echo "<script>var pages = $json_pages;</script>";
Which gives you a JS object like:
var pages = {
"Engineer": {
"pageTitle": "Engineer",
"subpages": {
"Software Engineer": "Software",
"Embedded Software Engineer": "Embedded Software"
}
},
"Analyst": {
"pageTitle": "Analyst",
"subpages": {
"Systems-Analyst": "Systems",
"Data-Analyst": "Data"
}
}
}
Then use JS to handle the on change events.