How to integrate ajax to Wordpress theme? - javascript

I am trying to use ajax in wordpress
I have two files, php and js
this is my php code
combo_check-out.php
function iRange($first, $last, $format = 'm/d/Y' ) {
$dates = array();
$current = strtotime($first);
$i=1;
while( $i <= $last ) {
$dates[] = date($format, $current);
$current = strtotime('+1 day', $current);
$i++;
}
$time = date("m/d/Y",$current);
return $time;
}
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
?>
<select name="check-out" id="check-out-date">
<option value="<?php echo iRange($id, 1, $format = 'm/d/Y' ) ?>">"1 Day (Same Day)"</option>
<option value="<?php echo iRange($id, 2, $format = 'm/d/Y' ) ?>">"2 Days"</option>
<option value="<?php echo iRange($id, 3, $format = 'm/d/Y' ) ?>">"3 Days"</option>
<option value="<?php echo iRange($id, 4, $format = 'm/d/Y' ) ?>">"4 Days"</option>
</select>
<?php}?>
and here it is my js code
combo_checkout_iRange.js
$(document).ready(function() {
$('#loader').hide();
$('#check-in-date').change(function(){
$('#check-out-date-wrap').fadeOut();
$('#loader').show();
$.post("combo_check-out.php", {
parent_id: $('#check-in-date').val(),
}, function(response){
setTimeout("finishAjax('check-out-date-wrap', '"+escape(response)+"')", 400);
});
return false;
});
});
//JQuery to hide Loader and return restults
function finishAjax(id, response){
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function alert_id()
{
if($('#check-out-date').val() == '')
alert('Please select a sub category.');
else
alert($("#check-out-date").val());
return false;
}
they work fine outside wordpress
how to integrate them in wordpress theme
Note: this should work in post type called "meetings"
so this is what i wrote on function.php
add_action("wp_enqueue_scripts", function() {
if (is_single()) {
if (get_post_type() == 'meetings')
{
wp_enqueue_script('combo_checkout_iRange', get_template_directory_uri() . '/js/combo_checkout_iRange.js', array( 'jquery' ), '1.0' ,true);
}
}
});

First step
the url you need to hit that is :
<?php echo admin_url( 'admin-ajax.php' ); ?>
now there are couple of method to get this into the js . that is your "ajaxurl"
Second Step
with the url , you need to pass a action like :
url?action=your_ajax_hit
in jquery , it would be like :
$.ajax({
url : ajaxurl+'?action=your_ajax_hit',
type : 'post'
.....
.....
.....
});
Third Step
into the functions.php you can add
add_action("wp_ajax_your_ajax_hit", "your_function_name");
add_action("wp_ajax_nopriv_your_ajax_hit", "your_function_name");
function your_function_name(){
// your code
wp_die();
}
you can see its
wp_ajax_ your_ajax_hit
thats it
please read this : http://codex.wordpress.org/AJAX_in_Plugins

Related

How to execute AJAX on button click in php?

I'm developing a WordPress plugin and I have added some elements on admin settings using php file. Now I want to execute a php function on button click and after searching on internet, AJAX seemed like a way to go. But I don't know AJAX at all. So here is some code I put together.
And I know this code may seem messed up but please take a look.
echo"<form method='POST' action='temp.php'>";
function slideyglidey_settings_section_callback() {
esc_html_e( 'Plugin settings section description', 'slideyglidey' );
}
function slideyglidey_settings_input_file_callback() {
$options = get_option( 'slideyglidey_settings' );
$file_input = '';
if( isset( $options[ 'file_input' ] ) ) {
$file_input = esc_html( $options['file_input'] );
}
echo '<input type="file" id="slideyglidey_fileinput"
name="slideyglidey_settings[file_input]" value="' . $file_input . '"
onchange="onFileSelected(event)" />';
}
function slideyglidey_settings_img_src_callback() {
$options = get_option( 'slideyglidey_settings' );
$img_src = '';
if( isset( $options[ 'img_src' ] ) ) {
$img_src = esc_html( $options['img_src'] );
}
echo '<img src="" id="slideyglidey_imgsrc"
name="slideyglidey_settings[img_src]" value="' . $img_src . '" width="350"
height="200"/>';
}
function slideyglidey_settings_upload_btn_callback() {
$options = get_option( 'slideyglidey_settings' );
$upload_btn = '';
if( isset( $options[ 'upload_btn' ] ) ) {
$upload_btn = esc_html( $options['upload_btn'] );
}
echo '<input type="button" id="slideyglidey_uploadbtn"
name="slideyglidey_settings[upload_btn]" value="Upload"/>';
}
echo"</form>";
?>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var $checkboxes = $( "form input:file" )
$checkboxes.on("change", function(){
var st="helloHOWAREYOU";
$.ajax({
type: "POST",
url: "temp.php",
cache: false,
data: 'name=' + st,
success: function(res){
$('#result').html(res);
}
});
})
</script>
temp.php
<?php
$name = $_POST['name'];
echo '<script>console.log($name)</script>';
?>
When I execute this code, I get no errors but I don't get the message in console log as well.
Any help is appreciated.
Thanks!
You can use this way to pass data
$.ajax({
...
data : {name : 'helloHOWAREYOU'},
...
});
Assuming this is your button:
echo <button id="handler">click me</button>
Then put the following code in a <script> tag:
document.getElementById('handler').addEventListener('click', AJAX);
function AJAX() {
const req = new XMLHttpRequest();
req.addEventListener("load", (data) => console.dir(data.target.response));
req.open("GET", "https://reqres.in/api/users?page=2");
req.send();
}
<button id="handler">click me</button>
Note I now perform the AJAX request to a website which offers some dummy data. Of course you have to change this to your own requirements.

Using ajax only saves 1 image from ACF gallery in wordpress

I'm using the ACF gallery field to let users create a gallery on front end and then I have an ajax call to save the gallery without page refresh.
If I remove the ajax save and use the default update post, all images in the gallery save correctly, but when I use my ajax save method only the last image in the gallery saves.
Here's my code:
Single post / form
<?php acf_form_head(); ?>
<?php get_header(); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php $args = array(
'form_attributes' => array(
'id'=>'modalAjaxTrying'
),
'submit_value' => __("update this badboy", 'acf'),
);
acf_form( $args );
?>
<?php endwhile; endif; ?>
<?php acf_enqueue_uploader();?>
<?php get_footer(); ?>
Ajax save in JS file
jQuery('form#modalAjaxTrying :submit').click(function(event){
event.preventDefault();
var form_data = {'action' : 'acf/validate_save_post'};
jQuery('form#modalAjaxTrying :input').each(function(){
form_data[jQuery(this).attr('name')] = jQuery(this).val()
})
form_data.action = 'save_my_data';
jQuery.post(ajaxurl, form_data)
.done(function(save_data){
alert('Added successFully :');
})
})
Functions.php
add_action( 'wp_ajax_save_my_data', 'acf_form_head' );
add_action( 'wp_ajax_nopriv_save_my_data', 'acf_form_head' );
Anyone looking to get ajax save to play nice with ACF gallery here ya go.
In your functions.php
add_action('acf/submit_form', 'my_acf_submit_form', 10, 2);
function my_acf_submit_form( $form, $post_id ) {
if(is_admin())
return;
//Test if it's a AJAX request.
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $form['updated_message'];
die();
}
}
add_action( 'wp_ajax_save_my_data', 'acf_form_head' );
add_action( 'wp_ajax_nopriv_save_my_data', 'acf_form_head' );
function my_acf_save_post( $post_id ) {
// get new values
$value = get_field('add_images', $post_id);
In your JS file
acf.do_action('ready', $('body'));
$('form#modalAjaxTrying').on('submit', function(e){
e.preventDefault();
});
acf.add_action('submit', function($form){
$.ajax({
url: window.location.href,
method: 'post',
data: $form.serialize(),
success: function(data) {
acf.validation.toggle($form, 'unlock');
alert(data);
}
});
});

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>

ajax on update data in database using codeigniter

<button id="survey_act" method="post" class="tiny ui blue button" type="button" value="<?php echo $surv['id']; ?>" >Activate Survey</button>
This is my button on click -
<script>
$(document).ready(function(){
$(document).on("click","#survey_act", function(){
alert(this.value);
idx = this.value;
$.ajax({
type: "POST",
url: "<?php echo base_url('index.php/admin/survey/act_surveyby_id/')?>/"+idx,
}).done(function(msg){
if(msg=="success"){
alert('You Successfully Activated the Survey!');
}
});
});
});
</script>
This is my javascript -
public function act_surveyby_id($id){
$this->load->model('survey_m');
if($this->survey_m->insert_activate($id)){
echo "success";
}else{
echo "invalid";
}
}
This is my controller -
public function insert_activate($id){
$date = date('m-d-Y',now());
$stat = 'Active';
$data = array(
'issued_date' => $date ,
'status' => $stat
);
$this->db->update('survey', $data)->where('survey_id', $id);
if($this->db->affected_rows()>0){
return true;
}else{
return false;
}
}
}
This is my model -
Problem: when i click the activate survey it wont change/update the details of the survey. I really badly need a help regarding with this. Thanks . . .
change $.ajax function like below
$.ajax({
url: '<?php echo base_url(); ?>index.php/admin/survey/act_surveyby_id',
type: "POST",
data: {
idx : idx;
},
and controller like below
public function act_surveyby_id(){
$id=$_POST['idx'];
$this->load->model('survey_m');
if($this->survey_m->insert_activate($id))
{
echo "success";
}else{
echo "invalid";
}
}

Apply Chosen Select Plugin in Wordpress AJAX

P.S. This question is long as there's lot of code. Thank you for your patience and time. I appreciate it.
I am using ultimate wp query search filter plugin on my wordpress site. I would like to use chosen plugin instead of default select boxes. The select boxes already on the page are working perfectly with this code.
(function($){
$(".first-ddwn, .second-ddwn, .third-ddwn, .main-ddwn, .posts_ajax select").chosen({
no_results_text: "Oops, nothing found!",
width: "50%"
});
})(jQuery);
I have changed the result html for AJAX search as mentioned by the plugin author so that I get a dropdown of result posts.
add_filter('uwpqsf_result_tempt', 'customize_output', '', 4);
function customize_output($results , $arg, $id, $getdata ){
// The Query
global $post;
$apiclass = new uwpqsfprocess();
$query = new WP_Query( $arg );
ob_start(); $result = '';?>
<form action="<? bloginfo('url'); ?>" method="get"><?php
echo '<select name="page_id" id="page_id">';
echo '<option value="">Select</option>';
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<option value="<? echo $post->ID; ?>"><?php echo the_title(); ?></option>
<?php }
echo '</select>';
echo '<input type="submit" name="submit" value="view" />';
echo '</form>';
} else {
echo 'no post found';
}
/* Restore original Post Data */
wp_reset_postdata();
$results = ob_get_clean();
return $results;
}
However, chosen doesn't get applied to this result dropdown. I have tried the option of using settimeout after the AJAX call as mentioned http://davidwalsh.name/jquery-chosen#comment-29299 but it didn't work. maybe I did it wrong. Also when I run it after ajax call like below, chosen does get applied to the select but is all broken.
jQuery.ajax({
type: 'POST',
url: ajax.url,
timeout:3000,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty();res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
$(".content select").chosen();
}
});
This is what I get
This is plugin's uwpqsfscript.js file
jQuery(document).ready(function($) {
$('body').on('click','.usearchbtn', function(e) {
process_data($(this));
return false;
});
$('body').on('click','.upagievent', function(e) {
var pagenumber = $(this).attr('id');
var formid = $('#curuform').val();
upagi_ajax(pagenumber, formid);
return false;
});
$('body').on('keypress','.uwpqsftext',function(e) {
if(e.keyCode == 13){
e.preventDefault();
process_data($(this));
}
});
window.process_data = function ($obj) {
var ajxdiv = $obj.closest("form").find("#uajaxdiv").val();
var res = {loader:$('<div />',{'class':'umloading'}),container : $(''+ajxdiv+'')};
var getdata = $obj.closest("form").serialize();
var pagenum = '1';
jQuery.ajax({
type: 'POST',
url: ajax.url,
timeout:3000,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty();res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
}
});
}
window.upagi_ajax = function (pagenum, formid) {
var ajxdiv = $(''+formid+'').find("#uajaxdiv").val();
var res = {loader:$('<div />',{'class':'umloading'}),container : $(''+ajxdiv+'')};
var getdata = $(''+formid+'').serialize();
jQuery.ajax({
type: 'POST',
url: ajax.url,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty(); res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
//res.container.find(res.loader).remove();
}
});
}
$('body').on('click', '.chktaxoall,.chkcmfall',function () {
$(this).closest('.togglecheck').find('input:checkbox').prop('checked', this.checked);
});
});//end of script
And some relevant code (maybe?) from uwpqsf-process-class.php
//front ajax
add_action( 'wp_ajax_nopriv_uwpqsf_ajax', array($this, 'uwpqsf_ajax') );
add_action( 'wp_ajax_uwpqsf_ajax', array($this, 'uwpqsf_ajax') );
add_action( 'pre_get_posts', array($this ,'uwpqsf_search_query'),1000);
}
function uwpqsf_ajax(){
$postdata =parse_str($_POST['getdata'], $getdata);
$taxo = (isset($getdata['taxo']) && !empty($getdata['taxo'])) ? $getdata['taxo'] : null;
$cmf = (isset($getdata['cmf']) && !empty($getdata['cmf'])) ? $getdata['cmf'] : null;
$formid = $getdata['uformid'];
$nonce = $getdata['unonce'];
$pagenumber = isset($_POST['pagenum']) ? $_POST['pagenum'] : null;
if(isset($formid) && wp_verify_nonce($nonce, 'uwpsfsearch')){
$id = absint($formid);
$options = get_post_meta($id, 'uwpqsf-option', true);
$cpts = get_post_meta($id, 'uwpqsf-cpt', true);
$pagenumber = isset($_POST['pagenum']) ? $_POST['pagenum'] : null;
$default_number = get_option('posts_per_page');
$cpt = !empty($cpts) ? $cpts : 'any';
$ordermeta = !empty($options[0]['smetekey']) ? $options[0]['smetekey'] : null;
$ordertype = (!empty($options[0]['otype']) ) ? $options[0]['otype'] : null;
$order = !empty($options[0]['sorder']) ? $options[0]['sorder'] : null;
$number = !empty($options[0]['resultc']) ? $options[0]['resultc'] : $default_number;
$keyword = !empty($getdata['skeyword']) ? sanitize_text_field($getdata['skeyword']) : null;
$get_tax = $this->get_uwqsf_taxo($id, $taxo);
$get_meta = $this->get_uwqsf_cmf($id, $cmf);
if($options[0]['snf'] != '1' && !empty($keyword)){
$get_tax = $get_meta = null;
}
$ordermeta = apply_filters('uwpqsf_ometa_query',$ordermeta,$getdata,$id);
$ordervalue = apply_filters('uwpqsf_ometa_type',$ordertype,$getdata,$id);
$order = apply_filters('uwpqsf_order_query',$order,$getdata,$id);
$number = apply_filters('uwpqsf_pnum_query',$number,$getdata,$id);
$args = array(
'post_type' => $cpt,
'post_status' => 'publish',
'meta_key'=> $ordermeta,
'orderby' => $ordertype,
'order' => $order,
'paged'=> $pagenumber,
'posts_per_page' => $number,
'meta_query' => $get_meta,
'tax_query' => $get_tax,
's' => esc_html($keyword),
);
$arg = apply_filters( 'uwpqsf_query_args', $args, $id,$getdata);
$results = $this->uajax_result($arg, $id,$pagenumber,$getdata);
$result = apply_filters( 'uwpqsf_result_tempt',$results , $arg, $id, $getdata );
echo $result;
}else{ echo 'There is error here';}
die;
}//end ajax
function uajax_result($arg, $id,$pagenumber,$getdata){
$query = new WP_Query( $arg );
$html = '';
//print_r($query); // The Loop
if ( $query->have_posts() ) {
$html .= '<h1>'.__('Search Results :', 'UWPQSF' ).'</h1>';
while ( $query->have_posts() ) {
$query->the_post();global $post;
$html .= '<article><header class="entry-header">'.get_the_post_thumbnail().'';
$html .= '<h1 class="entry-title">'.get_the_title().'</h1>';
$html .= '</header>';
$html .= '<div class="entry-summary">'.get_the_excerpt().'</div></article>';
}
$html .= $this->ajax_pagination($pagenumber,$query->max_num_pages, 4, $id,$getdata);
} else {
$html .= __( 'Nothing Found', 'UWPQSF' );
}
/* Restore original Post Data */
wp_reset_postdata();
return $html;
}//end result
I have been searching for days and have tried many things to make this work. I have no knowledge of jquery,so maybe someone will help me out.
Many Thanks

Categories