Adding a dependent drop down box in Wordpress - javascript

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

Related

Wordpress unable to save featured image

this is Nadeem I am a beginner on PHP and WordPress, I stuck on one point during custom plugin development, my problem is, I am unable to save Featured image and custom taxonomy tag and category from the frontend. In the meantime, I already Search on Google, StackOverflow, etc. too much for this error solution about this but unfortunately, this does not work and I am stuck at this point from the last 2 weeks.
This is my Plugin PHP code
/**
* The Template for displaying car archives, including the main car-data page which is a post type archive.
*
* Override this template by copying it to yourtheme/car_data/archive-car-data.php
*
* #author Shaikh Nadeem
* #package Car_Data
* #subpackage Car_Data/Templates
* #version 1.0.0
*/
class Car_Frontend_Form
{
function __construct()
{
add_shortcode( 'submit_car', array($this, 'submit_car') );
add_action( 'wp_enqueue_scripts', array( $this, 'my_enqueue' ) );
add_action( 'save_post_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_nopriv_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'wp_ajax_submit_car_data_post', array( $this, 'submit_car_data_post' ) );
add_action( 'init', array( $this, 'submit_car_data_post' ) );
}
public function submit_car() {
echo '<div id="submit_car_form">';
echo '<form id="cd_car" name="cd_car" class="cd_car" method="post" action="'.$_SERVER['PHP_SELF'].'" enctype="multipart/form-data" >';
wp_nonce_field( "car-frontend-post" );
echo '<p><label for="title">Title</label><br />';
echo '<input type="text" id="title" value="" size="60" name="title" />';
echo '</p>';
echo '<p>';
echo '<label for="content">Post Content</label><br />';
echo '<textarea id="content" name="content" cols="40" rows="4"></textarea>';
echo '</p>';
echo '<p><label for="feature">Feature:</label><br />';
wp_dropdown_categories( "show_option_none=Feature&tab_index=3&taxonomy=feature&name=feature&id=feature&class=feature" ) .'</p>';
echo '<p><label for="make">Make:</label><br />';
wp_dropdown_categories( "show_option_none=Make&tab_index=4&taxonomy=make&name=make&id=make&class=make" ) .'</p>';
echo '<p><label for="post_tags">Tags</label><br />';
echo ' <input type="text" value="" size="60" name="post_tags" id="post_tags" /></p>';
echo '<p><label for="post_tags">Car Image</label><br />';
echo '<input type="file" name="file" id="file"></p>';
echo '<p align="left"><input type="submit" tabindex="6" id="submit_car" name="submit_car" /></p>';
echo '</form>';
echo '</div>';
return;
}
public function submit_car_data_post() {
if ( isset($_POST['title']) ) {
echo '<script>console.log("file error: '.$fileerror.'<br>");</script>';
$title = sanitize_text_field( $_POST['title'] );
$content = sanitize_text_field( $_POST['content'] );
$author_id = sanitize_text_field( $_POST['author_id'] );
$tags_input = sanitize_text_field( array($_POST['post_tags']) );
$feature = sanitize_text_field( array($_POST['feature']) );
$make = sanitize_text_field( array($_POST['make']) );
// $image = $_POST['file'];
$args = array(
'post_title' => $title,
'post_content' => $content,
'tags_input' => $_POST['post_tags'],
'author' => $author_id,
'post_status' => 'publish',
'post_type' => 'car-data',
'tax_input' => array(
$feature,
$make
),
// 'post_category' => array(
// 'feature' => array($_POST['feature']),
// 'make' => array($_POST['make'])
// )
);
// Check that the nonce was set and valid
if( !wp_verify_nonce($_POST['_wpnonce'], 'car-frontend-post') ) {
return;
}
if( is_wp_error( $posts ) ){
echo json_encode( $posts->get_error_messages() );
}
// save frontend Post
$posts = wp_insert_post( $args );
// save frontend Texonomy
wp_set_object_terms( $posts, $feature, 'feature' );
wp_set_object_terms( $posts, $make, 'make' );
// save Atachment on featured image for the current custom post
$uploaddir = wp_upload_dir();
$file = $_FILES[$image];
$uploadfile = $uploaddir['path'] . '/' . basename( $file );
move_uploaded_file( $_FILES['file']['tmp_name'], $uploaddir['path'] . '/' . $filename );
$filename = basename( $uploadfile );
$wp_filetype = wp_check_filetype(basename($filename), null );
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
'post_content' => preg_replace('/\.[^.]+$/', '', $filename),
'post_excerpt' => preg_replace('/\.[^.]+$/', '', $filename),
'post_status' => 'inherit',
'post_type' => 'attachment',
'menu_order' => $_i + 1000,
);
$attach_id = wp_insert_attachment( $attachment, $uploadfile );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata($attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
wp_die();
}
}
public function my_enqueue() {
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
}
and i use javascript for the ajax alert message when form is submit
jQuery(document).ready(function($) {
$('.cd_car').on('submit', function(event) {
event.preventDefault();
var message = document.getElementById("file").value;
var empt = document.forms["cd_car"]["title"].value;
if (empt == "")
{
alert("Please input a Value");
return false;
}
else
{
$.ajax({
type: 'post',
// url : ajax_object.ajaxurl,
data : $('.cd_car').serialize(),
success : function(data){
alert(message);
console.log(data);
},
error : function(data){
alert(message);
alert('fail');
}
});
}
});
});
Also i have there one error on this line code if ( isset($_POST['title']) ) unable to use submit key on isset post only title is working here.
I believe your issue is due to sanitize_text_field( array( .. )). sanitize_text_field only accepts strings as the parameter, so I assume by sending in an Array it's actually always seeing the string "Array" - not your POST values.
To sanitize the array, could do something like:
$tags_input = array();
if ( isset($_POST['post_tags']) && !empty($_POST['post_tags']) ) {
foreach ($_POST['post_tags'] as $val)
$tags_input[] = sanitize_text_field( $val );
}
// [ .. repeat for feature & make .. ]
Or, if they're single values only (not arrays), simply remove the array wrapper.

How To Multiply Result Based on Selection from Drop Down Menu

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

Why isn't my ajax code updating my second dropdown?

I have no idea why my code isn't working. I basically have two dropdowns, the first is populated from an mssql database and I want the second dropdown to update dependant on the selection in the first.
Below is my code which populates a dropdown box:
<?php
session_start();
$serverName = "REDACTED";
$connectionInfo = array( "Database"=>"REDACTED", "UID"=>"REDACTED", "PWD"=>"REDACTED");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if (!isset($_SESSION['nID']))
{
header("Location: Login.php");
die();
}
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['region']."</option>";
}
return $output;
}
?>
I then use this to populate the first dropdown:
<p>Select a Region
<select name ="region" id ="region">
<option value ="">Select Region</option>
<?php echo loadRegion(); ?>
</select></p>
For the second dropdown box I have the following:
<p>Select a Territory
<select name="territory" id="territory">
<option value="">Select Territory</option>
</select></p>
I call my ajax via:
<script>
$(document).ready(function(){
alert("ready");
$('#region').change(function(){
var region_id = $(this).val();
$.ajax({
url:"getter.php",
method:"POST",
data:{regionId:region_id},
dataType:"text",
success:function(data){
$('#territory').html(data);
}
});
});
});
</script>
My getter page reads as follows:
<?php
session_start();
include 'config.php';
$output = '';
$sql = "SELECT distinct id,territory,rid FROM territoriesHaiss where RID = '".$_POST["regionId"]."' order by id";
$result = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
$output = '<option value ="">Select Territory</option>';
while($row = sqlsrv_fetch_array($result))
{
$output .= "<option value=\"".htmlspecialchars($row['ID'])."\">".$row['territory']."</option>";
}
echo $output;
?>
As pointed out by the 2 comments above (thanks again for the help!) the error was in the code that populates the first dropdown. It should have been a lowercase 'ID', like follows:
function loadRegion()
{
include 'config.php';
$output = '';
$regionQuery = 'select distinct id, region from regionsHaiss order by id';
$regionPopulate = sqlsrv_query($conn, $regionQuery, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($regionPopulate))
{
$output .= "<option value=\"".htmlspecialchars($row['id'])."\">".$row['region']."</option>";
}
return $output;
}
?>

Posting variables with AJAX to a php function on a different file and calling the function

I am attempting to post variables via AJAX and using these variables to run a script that creates a list of checkbox options. My code is as follows:
*index.php*
require_once ("session_start.php");
require_once ("ajax.php");
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );
$link = mysqli_connect ( 'localhost', 'root', '' );
if (! $link) {
die ( "Connection failed" . mysqli_errno ( $link ) );
}
function getDBlist() {
global $link;
$qry = ("SHOW DATABASES");
$res = mysqli_query ( $link, $qry );
while ( $row = mysqli_fetch_assoc ( $res ) ) {
echo '<input type="checkbox" name="db" value="' . $row ['Database'] . '" class="checkbox" />';
echo $row ['Database'];
}
}
getDBlist ();
The Script
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {"db=" + db},
success: function (html) {
$("#qryDisplay").show();
}
});
});
ajax.php
function showTables() {
if (isset ( $_POST ['db'] )) {
$db = $_POST ['db'];
$link = mysqli_connect ( '192.168.2.113', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
?>
<ul>
<?php
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
?>
<input type="checkbox" name="tbl[]" class="tbl_list"
value="<?php echo $row [0]; ?>" />
<?php echo $row [0]; ?>
<br>
<?php
}
}
}
showTables ();
?>
</ul>
<?php
function tblProperties() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
$db = $_POST ['db'];
$link = mysqli_connect ( '192.168.2.113', 'root', '', $db );
$qry = "DESCRIBE $tbl";
$result = mysqli_query ( $link, $qry );
?>
<div class="Table">
<div class="Heading">
<div class="Cell2">
<p> <?php echo $tbl; ?> </p>
</div>
</div>
<div class="Row">
<div id="topRow">
<input type="checkbox" name="tbl" id="tblall" value="All" />
<p>ALL</p>
</div>
<?php
while ( $row = mysqli_fetch_array ( $result ) ) {
?>
<div class="draggable-cell ui-widget-content">
<input type="checkbox" name="tbl" class="tblst"
value="<?php echo $row[0];?>" />
<p><?php echo $row[0]; ?> </p>
</div>
<?php }?>
</div>
</div>
<?php } } tblProperties();
(Clicking the checkbox should post a variable db to my ajax.php page)
At this point I believe i'm doing everything right, however when I call the ajax.php functions like showtables() in my index.php file I get no results. Could it be that the variables aren't being posted? If so why would the success condition be fulfilled? Have I missed something crucial?
Replace below:
data: {"db=" + db},
With below and try:
data: {db: db},
You need to echo your result set in ajax.php. you did not echo any thing or did not return anything.

Retrieving options from a dynamically created Select form

I have created a Dynamic HTML-Select whose options are populated by the names of the databases on my server. Upon clicking an option a new .php page is opened (using JQuery). In this new page I would like the database name selected from the previous page to passed as a string which I can use to do MySQL queries.
So what have I tried?
function selectDB() {
$link = mysqli_connect ( 'username', 'root', '' );
$qry = ("SHOW DATABASES");
$db_list = mysqli_query ( $link, $qry );
echo "<select name ='Databases' id='Databases' method='post'>";
while ( $row = mysqli_fetch_array ( $db_list ) ) {
echo "<option value='" . $row [0] . "'>" . $row [0] . "</option>";
}
echo "</select>";
}
JavaScript
$('#Databases').change(function () {
var yourDB = $(this).val();
window.location.assign("test.php");
});
test.php
if (isset ( $_POST ['Databases'] )) {
$dbName = $_POST ['Databases'];
$link = mysqli_connect ( 'username', 'root', '', "'%$dbName%'" );
if (! $link) {
die ( "Connection failed" . mysqli_errno ( $link ) );
}
$qry = "SHOW tables";
$tblist = mysqli_query ( $link, $qry );
return $tblist;
printf ( $tblist );
}
When I run this, I get the whitepageofdeath. Running error_log doesn't show anything. Where am I going wrong??
Just change the url to include the selection as a GET parameter
$('#Databases').change(function () {
var yourDB = $(this).val();
window.location.assign("test.php?db=" + yourDB);
});
The you can access it in your test.php page as a $_GET var

Categories