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

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>

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";
}
}
?>

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.

How to hide the check box after the form submit

Hello friends this i am facing some problem...I have multiple check boxes and by selecting each check box i am inserting the users details to database by Ajax. the records records are inserting to database but my problem is that , suppose i have 5 users in the page, suppose i am selecting the 3 user check boxes and submit , and if the insertion succeed then i want that the 3 selected users will not shown on page. i use Google many tips but can't solve the problem.
//this is the menu.php
<li class="invitetab"><span>Invite</span></li>
$('.invitetab').one('click', function(){
var rp = '<?php echo $baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $_SESSION['db_user_info']['id'] ?>';
$( document ).ready(function() {
$.ajax({
url: ""+rp+"invite.php?pageid="+v+"&userid="+userid,
type: 'POST',
beforeSend: function()
{
$("#loading_img").show();
},
success: function(data)
{
$("#loading_img").hide();
$("#Invite").append(data);
}
});
});
});
//And this is the invite.php
$('.gr-post-btn-submit').click(function(){ // when a feature button is selected
var rp = '<?php echo $config->baseUrl ;?>/themes/gr-mist/pagemenu/parts/';
var v = '<?php echo $_GET['pageid'];?>';
var userid = '<?php echo $user_id ?>';
var serialize = $('.abc').serialize(); // takes all the values of the filter
$.ajax({
type : 'POST',
url: ""+rp+"sendinv.php?pageid="+v+"&userid="+userid, // sends the values to ajax file
data : serialize,
beforeSend: function()
{
$("#loading_own").show();
$("#Invite").css({ opacity: 0.5 });
},
success: function(data)
{
$("#loading_own").hide();
$("#Invite").css({ opacity: 5.6 });
// $("#Invite").show();
//this is the portion where we have to do some thing to hide the inserting check boxes
}
});
});
<form method="post" class="abc" id="" name="inviteform"
enctype="multipart/form-data" action="#">
<?php
$sql = "select * from gr_user_friendships where toid=$user_id and status = 1";
$pagd = $_GET['pageid'];
$liked_users = $db->select($sql);
$count = 0;
for($i=0; $i<count($liked_users); $i++)
{
$extrct_fr = "select * from gr_page_likes where page_id=".$pagd." and receiver_id=".$liked_users[$i]['fromid'];
//echo $extrct_fr;
$frnd = $db->select($extrct_fr);
if(count($frnd)>0)
{
$invt = $db->select("select * from gr_user_friendships where toid=$user_id and fromid!=$frnd[0]['receiver_id']");
$invt_id = $invt[0]['fromid'];
}
else
{
$invt_id = $liked_users[$i]['fromid'];
}
if(!empty($invt_id))
$count = 1;
$user = "Select * from gr_users where id = $invt_id";
//echo $user;
$table = mysql_query($user);
$dbc = mysql_fetch_array($table);
$usid= $dbc['id'];
$bab = $dbc['name'];
$imgs = $dbc['avatar'];
$image_of_fr = $_SERVER['DOCUMENT_ROOT']."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
$image_location_f = $config->baseUrl."/uploads/users/".$usid."/profile/profile-pic/thumb/".$imgs;
if(file_exists($image_of_fr))
{
$imgp = $image_location_f;
}
else
{
$imgp = $config->baseUrl."/themes/gr-mist/includes/images.jpg";
}
if(!empty($invt_id)){
?>
<style type="text/css">
#users_<?php echo $invt_id ?>
{
width:147px;
height:54px;
display:inline-block;
}
</style>
<input type="checkbox" class="checkbox1" id="gcc_<?php echo $invt_id ?>" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
<?php
}
}//end of for
?>
<br>
<?php if($count){ ?>
<span style="color:blue; font-weight:bold;" >
<input type="checkbox" id="selecctall"/> Select All</span>
<input type="button" name="gr_submits" class="gr-post-btn-submit" value="invite" id="submits"/>
<?php } ?>
</form>
and this is the sendinv.php
global $db;
$myliker = $_POST['pgliker'];
$pageid = $_GET['pageid'];
$userid = $_GET['userid'];
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
}
/**In you invite.php put the element which you want to hide after success
form submission into one div*//
//replace your one with this one.
<div id="gcc_<?php echo $invt_id ?>">
<input type="checkbox" class="checkbox1" name="pgliker[]" value="<?php echo $invt_id ?>"/>
<img width="30" height="30" src="<?php echo $imgp;?>"/>
<?php echo $bab; ?>
</div>
/**Now make an array in your sendinv.php and encode it with json incode***/
//replace your sendinv.php with this one.
$arr = array();
foreach($myliker as $tps)
{
$sql = "Insert into gr_page_likes values('',$pageid,$userid,$tps,0)";
$db->insert($sql);
$arr[] = $tps;
}
echo json_encode($arr);
exit;
/**After in your invite.php in the success block run
jquery foreach with the data and hide the checked boxes with the ids associted after submission. */
$.each( data, function( key, value ) {
// alert( key + ": " + value );
$("#gcc_"+value).hide();//the div for each checked user
});

AJAX- getting a specific array value in post

Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.

how to create an autocomplete textbox in wordpress?

Hi i am developing a plugin in wordpress.
i tried code for create autocomplete text box in my customized form.
Ajax Calling function
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
foreach($result as $dis)
{
$data.=$dis->city."<br>";
}
echo $data;
die();
}
add_action( 'wp_ajax_city_action', 'city_action_callback' );
add_action( 'wp_ajax_nopriv_city_action', 'city_action_callback' );
Shortcode function
function my_search_form() {
?>
<script>
jQuery(document).ready(function($) {
jQuery('#city').keyup(function() {
cid=jQuery(this).attr('val');
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
//alert(response);
});
});
});
</script>
<input type="text" id="city" name="city" autocomplete="off"/>
<?php
}
this code return related results perfectly in variable response.
But i don't know how create a text box look like a autocomplete box.
Please explain me how to do that in wordpress?
Just add a div under the input tag
HTML Code:
<input type="text" id="city" name="city" autocomplete="off"/>
<div id="key"></div>
replace the div after the success on you ajax.
Ajax Code:
var ajaxurl="<?php echo admin_url( 'admin-ajax.php' ); ?>";
var data ={ action: "city_action", city:cid };
$.post(ajaxurl, data, function (response){
$('#key').html(response);
});
PHP Code:
function city_action_callback() {
global $wpdb;
$city=$_GET['city'];
$result = $mytables=$wpdb->get_results("select * from ".$wpdb->prefix . "mycity where city like '%".$city."'" );
$data = "";
echo '<ul>'
foreach($result as $dis)
{
echo '<li>'.$dis->city.'</li>';
}
echo '</ul>'
die();
}

Categories