how to do update using ajax jquery in wordpress? - javascript

i am developing plugin where i have to update the single record onchanging the select option element , i tried using wordpres codex way ,but i am struck can please anyone help me out here, below is my code
function ajaxFunction(str,id) {
var payment_selected = str;
var id=id;
var queryString = '&id_took='+id+'&sel='+payment_selected;
var data = {
'action' : 'my_action',
'payment_selected': payment_selected,
'id' : id
};
jQuery.post(admin_url("admin-ajax.php"), data, function(response) {
jQuery("#status").html(response);
});
}
/* this is a php file , i used in the plugin where below html form appears */
<?php
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['payment_selected'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
$result_pay = $wpdb->query($wpdb->prepare("UPDATE $table_name_payment SET payment_status = $id_selected WHERE id=$id"));
echo "success";
?>
/* this is the html file */
foreach ($rows as $row) { ?>
<table>
<td><?php echo $row->payment_status; ?></td>
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
<?php } ?>
<table>
<div id="status"></div>

function ajaxFunction(str,id) {
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: {
'action' : 'my_action',
'payment_selected': payment_selected,
'id' : id
},
success: function (response) {
if(response=='success'){
jQuery("#status").html(response);
}
}
});
}
PHP Code,
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['payment_selected'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
$result_pay = $wpdb->query($wpdb->prepare("UPDATE $table_name_payment SET payment_status = $id_selected WHERE id=$id"));
echo "success";
}
?>
HTML code,
<?php foreach ($rows as $row) { ?>
<table>
<tr><td><?php echo $row->payment_status; ?></td>
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
<?php } ?>
</td></tr>
<table>
<div id="status"></div>
Hope this will helps you.

well i tried in my own way its working fine for me, below is my answer
function ajaxFunction(str,id) {
var payment_selected = str;
var id=id;
var queryString = '&id_took='+id+'&sel='+payment_selected;
var data = {
'action' : 'my_action',
'payment_selected': payment_selected,
'id' : id
};
jQuery.post(ajaxurl, data, function(response) {
jQuery("#status").html(response);
});
}
/* write this php function outside of all the function*/
<?php
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['payment_selected'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
// $result_pay = $wpdb->query($wpdb->prepare("UPDATE $table_name_payment SET payment_status = $id_selected WHERE id = $id"));
$result_pay = $wpdb->update(
$table_name_payment, //table
array( 'payment_status' => $id_selected), //data
array('id' => $id) //data format
);
}
?>
foreach ($rows as $row) { ?>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<td>
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
</td>
<div id="status"></div>
<?php } ?>

Related

Wordpress Ajax not working?

I am developing plugin in wordpress, i used select tag element, i need the value to be stored in the database on change the option values , but it seems ajax is not working .below is my code ,
this is script code
function ajaxFunction(str,id) {
var payment_selected = str;
var id=id;
var queryString = "&id_took=" + id + "&sel=" + payment_selected;
jQuery.ajax({
var data = { 'action' : 'my_action',
'queryString':queryString
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
}
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
/*below one i have written in my plugin code */
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id_selected = $_POST['id_took'];
$id = $_POST['id'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
if($whatever2=="Payment completed")
{
$result_pay = $wpdb->query("UPDATE $table_name_payment SET
payment_status = $id_selected
WHERE id = $id ");
echo "success";
}
}
?>
Your use of jQuery.ajax seems wrong. Try without wrapping the code with jQuery.ajax like this:
Javascript
function ajaxFunction(str,id) {
var data = {
'action' : 'my_action',
'id_took': id,
'sel' : str
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
HTML
<select name='payment_select' id="payment_select" onchange="ajaxFunction(this.value,<?php echo $row->id ?>)">
<option value="Payment Due">Payment Due</option>
<option value="Payment completed">Payment Completed</option>
</select>
PHP
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
global $wpdb;
$id = $_POST['id_took'];
$str = $_POST['sel'];
$table_name_payment = $wpdb->prefix . "online_booking_system_model";
if($whatever2=="Payment completed")
{
$result_pay = $wpdb->query("UPDATE $table_name_payment SET
payment_status = $sel
WHERE id = $id ");
echo "success";
}
}
?>

the event of onchange at select control at php, trigger issue

I used this select which show counteries
<section class="shipping-calculator-form-shortcode" >
<p class="form-row form-row-wide" id="calc_shipping_country_field">
<label >Shipping options to</label>
<select onchange="myFunctionShipping(this)" name="calc_shipping_country" id="calc_shipping_country" class="ss-woo-shipping-calculator" rel="ss-woo-shipping-calculator">
<option value="1"><?php _e( 'Select a country…', 'woocommerce' ); ?></option>
<?php
foreach ( WC()->countries->get_shipping_countries() as $key => $value )
echo '<option value="' . esc_attr( $key ) . '"' . selected( WC()->customer->get_shipping_country(), esc_attr( $key ), false ) . '>' . esc_html( $value ) . '</option>';
?>
</select>
</p>
<span id="ss-woo-shipping-calculator-loading" style="display:none"><img src='<?php echo plugins_url( '/default.gif', __FILE__ ) ?>' /></span>
</p>
<?php wp_nonce_field( 'woocommerce-cart' ); ?>
<div id="ss-woo-shipping-result">
</div>
</section>
then by javascript code to retrieve the shipping options for it
<script type="text/javascript">
var $s = jQuery.noConflict();
function myFunctionShipping(item) {
$s(document).ready(function($) {
$("select").change(function(){
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var country = item.value;
$("#ss-woo-shipping-calculator-loading").show();
var data = {'action': 'ss_woo_shipping_calculator','country': country};
$.post("<?php echo get_home_url(); ?>", data, function(response) {
$("#ss-woo-shipping-calculator-loading").hide();
response = JSON.parse(response);
if(response.result == 1){
$("#ss-woo-shipping-result").html(response.message);
}else{
$("#ss-woo-shipping-result").html("");
}
return false;
});
return false;});
});
}
the problem that:- it trigger if also any other select control changed
also it is only trigger after changing the selection twice (after page loading)
It "says" that action apply to any select $("select").change(). You can change to limit action only to select with chosen id like
$("#calc_shipping_country").change(function()
or you can choose to use select class name.
EDIT.
My mistake, I didnt figure out that the action is called by function and not select action. Try to remove completely the $("select").change(function() wrap and make look something like this
<script type="text/javascript">
var $s = jQuery.noConflict();
function myFunctionShipping(item) {
$s(document).ready(function($) {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
var country = item.value;
$("#ss-woo-shipping-calculator-loading").show();
var data = {'action': 'ss_woo_shipping_calculator','country': country};
$.post("<?php echo get_home_url(); ?>", data, function(response) {
$("#ss-woo-shipping-calculator-loading").hide();
response = JSON.parse(response);
if(response.result == 1){
$("#ss-woo-shipping-result").html(response.message);
}else{
$("#ss-woo-shipping-result").html("");
}
return false;
});
return false;
});
}
</script>

Custom taxonomies Dropdown without a Submit Button using JavaScript

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

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.

Categories