I've created a Custom Post Type in Wordpress called Location/Tour and another one called Itinerary. In my CPT Itinerary, I have some ACF custom fields one of them is a repeater field that has subfields (Relationship field for the CPT Location/Tour, Title field, Description field).
I've created a button that should trigger an AJAX script which job is to get the values from the CPT Location/Tour(Title and Description) and
put them in my input subfields(Title and Description) in my CPT Itinerary.
I've created a PHP function that gets the values from the CPT Location/Tour and now I'm trying to run the PHP function using AJAX.
I was able to get the AJAX working and I get the values in my console log under ResponseText.
Now the part I'm struggling with. I need to set each value as a separate variable in JS so that I can replace the input field values with the new ones but unfortunately I don't know how.
I've tried almost everything and I think that I'm close to the answer but I'm missing something. :(
Here is my post-value-loader.php
<?php
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');
function post_loader($field) {
$post_id = $_POST["post_id"];
$args = array(
'p' => $post_id,
'numberposts'=> -1, // Fetch all posts...
'post_type'=> 'location_tour', // from the 'location_tour' CPT...
);
$location = new WP_Query( $args );
if ( $location->have_posts() ) : while ( $location->have_posts() ) : $location->the_post();
$title = the_field('title'); //The Title field value that we need
$description = the_field('description'); //The Description field value that we need
wp_reset_postdata();
?>
<?php endwhile; endif; ?>
<?php add_action('acf/prepare_field/name=default_tour', 'post_loader'); ?>
<?php }
// BUTTON TO RUN AJAX
function my_acf_prepare_field($field) {
echo '<div class="acf-field"><button type="submit" id="data_fetch" class="button acf-load-default-tour-values">Load default value</button></div>';
return $field;
}
add_action('acf/prepare_field/name=default_tour', 'my_acf_prepare_field');
// ADD SCRIPT TO WORDPRESS ADMIN AJAX
function js_data_fetch() {
wp_enqueue_script ("ajax-data-fetch", get_stylesheet_directory_uri() . "/inc/assets/js/data-fetch.js", array('jquery'));
//the_ajax_script will use to print admin-ajaxurl in data-fetch.js
wp_localize_script('ajax-data-fetch', 'the_ajax_script', array('ajaxurl' =>admin_url('admin-ajax.php')));
}
add_action("admin_enqueue_scripts", "js_data_fetch");
?>
And here is my data-fetch.js (Note: I'm not a JS guy :( )
jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
dohvati.preventDefault();
var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
jQuery.ajax({
url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
type: "POST",
dataType: 'json',
data: {
action: 'post_loader', // This is the name of the php function
post_id: post_id,
},
success: function(data){
console.log(data)
},
error: function(error){
console.log(error)
},
});
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(title); //This is replacing the title field - but the variables are missing
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(description); //This is replacing the description field - but the variables are missing
});
Also here are two images from the CPT Itinerary editor (https://imgur.com/kFImdpe) with the fields and my console log (https://imgur.com/wwxKXQP). Hope that this helps.
You have to return the data as JSON from post_loader function. I've cleaned up a little, but still, it's a mess.
// LOAD DEFAULT VALUES FROM DEFAULT TOUR
add_action('wp_ajax_post_loader', 'post_loader');
function post_loader() {
$post_id = $_POST["post_id"];
$args = array(
'p' => $post_id,
'numberposts'=> -1, // Fetch all posts...
'post_type'=> 'location_tour', // from the 'location_tour' CPT...
);
$location = new WP_Query( $args );
if ( $location->have_posts() ) :
while ( $location->have_posts() ) :
$location->the_post();
$title = the_field('title');
$description = the_field('description');
// You have to return data as json
wp_send_json([
'title' => $title,
'description' => $description
]);
//wp_reset_postdata();
endwhile;
endif;
// Why do you need this inside this function?
// add_action('acf/prepare_field/name=default_tour', 'post_loader');
}
JS
jQuery(document).on( 'click', '#data_fetch', function( dohvati ){
dohvati.preventDefault();
var post_id = jQuery('.acf-row .selection .values ul li span').data('id'); // This takes the post ID from the selected Post(Location/Tour) in the Relationship field
jQuery.ajax({
url: the_ajax_script.ajaxurl, //The URL that we set for the wordpress admin-ajax.php
type: "POST",
dataType: 'json',
data: {
action: 'post_loader', // This is the name of the php function
post_id: post_id,
},
success: function(data){
console.log(data)
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeabc041c8a").val(data.title); //This is replacing the title field - but the variables are missing
jQuery("#acf-field_5cb991a9337db-row-0-field_5cbeab8f41c89").val(data.description); //This is replacing the description field - but the variables are missing
},
error: function(error){
console.log(error)
},
});
});
Related
Can someone show me a good example of how to call a PHP function with Ajax? I'm trying to save an image gallery (with dynamic number of images) to database in the admin settings section. The below code is incomplete or maybe with some errors. Please show me a good example or a better way:
<button type="button" class="btn btn-primary" onclick="jsAddSettingsFields()">Save Changes</button>
function jsAddSettingsFields(){
var elements = document.getElementsByTagName("img");
var urlsdata = new Array();
for (var i = 0, element; element = elements[i++];) {
if (elements[i].id == "idGalPic") {
urlsdata[i] = elements[i].src;
// now we have all image urls in array, now need to
// call add_settings_fields
var data = {
action: 'php_addsettingsfields',
p_urls: urlsdata //I think i need to JSON this
};
jQuery.post( "", function( data ) );
}
}
}//end of js function
<?php
add_action( 'wp_ajax_update_options', 'php_addsettingsfields_callback' );
add_action( 'wp_ajax_nopriv_update_options', 'php_addsettingsfields_callback' );
function php_addsettingsfields_callback() {
$pic_urls = $_POST['p_urls']; // De-JSON-fy this variable
foreach ($pic_urls as &$url) {
add_settings_field($url);
}
add_settings_field(
'pic_url_id', // ID - slug name of field
'', // Title
array( $this, 'pic_gal_callback' ), // Callback
'TestPlugin', // Page
'setting_section_id' // Section ID - slug name of page
);
public function pic_gal_callback() {
<input type="hidden" id="idPic" name="idPic" value=$url />
}
// after all hidden fields(with gallery pic urls) are added to setting section submit
// the page and save the gallery urls to database
Here take a look at a working ajax example from one of my plugins.
Javascript Part:
//setting click event on button click to fire a function
$('#YourButtonIdHere').click(function () {
YourFunctionNameHere();
});
//function to execute
function YourFunctionNameHere() {
//formdata variable consists of
//action: this is ajax action name for WordPress which we define in PHP with a callback function with same name. See in PHP code part.
//$('#YourFormIDHere').serialize(); //this gets content from form and serialize it.
var frm_data = "action=your_action_name_here&" + $('#YourFormIDHere').serialize();
$.ajax({
type: "POST",
url: ajaxurl, // since WordPress version 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
data: frm_data,
cache: false,
success: function(data, textStatus, jqXHR) {
//do stuff here in case of success
},
error: function(jqXHR, textStatus, errorThrown) {
//do stuff here in case of error
}
});
}
PHP Part:
//here wp_ajax is the required prefix for your custom actions
//first parameter is action name with wp_ajax prefix
//second parameter is callback function to execute with same name as your action
//for example if your action name is wp_ajax_save_settings then your callback will be save_settings
add_action( 'wp_ajax_your_action_name_here', 'your_action_name_here' );
function your_action_name_here() {
global $wpdb; // this is how you get access to the database
//do stuff here and echo response
echo "ajax call success";
wp_die(); // this is required to terminate immediately and return a proper response
}
Edited for Clarity:
I'm using the misha_filter_function from: https://rudrastyh.com/wordpress/ajax-post-filters.html to filter posts.
The initial array is displaying the correct posts by the location_and_season (made with ACF) tag. But something weird is going on with the second array because when I click my dropdown select to sort the posts by category it's filtering all of the posts within the post type, and effectively ignoring 'tag' => $value,
I'm relatively new to Wordpress PHP and JS, so my Google-Fu hasn't been too helpful since I don't really know what to search. Any help would be appreciated. Thanks!
Here's the filter Code:
<?php
add_action('wp_ajax_myfilter', 'misha_filter_function'); //
wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
function misha_filter_function()
{
$value = get_field('location_and_season');
$args = array(
'post_type' => 'shows',
'tag' => $value,
'posts_per_page' => - 1, // show all posts.
'orderby' => 'name', // we will sort posts by name
'order' => 'ASC'
//$_POST['name'] // ASC or DESC
);
// for taxonomies / categories
// IMPORTANT! Adding && !empty( $_POST['categoryfilter'] ) fixes the no posts found for All Categories
if (isset($_POST['categoryfilter']) &&
!empty($_POST['categoryfilter'])) $args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
$query = new WP_Query($args);
// The Query
query_posts($args);
// The Loop
while (have_posts()):
the_post(); ?>
Here's the front end dropdown code:
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php"
method="POST" id="filter" style="float:right; margin-right: 15px;">
<?php
if ($terms = get_terms(array(
'taxonomy' => 'category',
'orderby' => 'name'
))):
echo '<select name="categoryfilter"><option id="refresh" value="all"
class="dropdown-select">All Topics...</option>';
foreach ($terms as $term):
echo '<option value="' . $term->term_id . '">' . $term->name .
'</option>';
endforeach;
echo '</select>';
endif;
?>
<div class="processing" style="height:30px;"></div>
<input type="hidden" name="action" value="myfilter">
</form>
And the JS
jQuery(function ($) {
$('#filter').change(function () {
var filter = $('#filter');
$.ajax({
url: filter.attr('action'),
data: filter.serialize(), // form data
type: filter.attr('method'), // POST
beforeSend: function (xhr) {
filter.find('.processing').html('<img src="spinner.gif" class="spinner">'); // changing the button label
},
success: function (data) {
filter.find('.processing').text(''); // changing the button label back
$('#response').html(data); // insert data
}
});
$(document).ready(function () {
$('#filter').on("click", function () {
$('.post-section').toggleClass("active");
});
});
return false;
});
I don't see anything that actually calls your php function. Wordpress ajax calls require an action in the data.
$.ajax({
url: filter.attr('action'),
type: filter.attr('method'), // POST
data: {
action: 'misha_filter_function',
categoryfilter: $(select['name ="categoryfilter"]').val()
},
beforeSend: function (xhr) {
filter.find('.processing').html('<img src="spinner.gif" class="spinner">'); // changing the button label
},
success: function (data) {
filter.find('.processing').text(''); // changing the button label back
$('#response').html(data); // insert data
},
failure: function(response){
console.log(response); //Debug only
}
});
Also, do you enqueue the js script with wp_localize_script?
I'm calling a wordpress plugin function via a front end page which is working good, the function that i m calling is inserting data into the database but its not working
here is the query i m running(which is not working):
The function is being called on submit as echo value is printed but no data is being inserted
function savedata(){
echo "<pre>";print_r($_POST);exit;
global $wpdb;
$wpdb->insert('questoptions',
array(
'question_id' => $_POST['question_id'],
'text' => $_POST['text']
),
array(
'%s',
'%s'
)
);
die();
return true;
}
here is the function calling this function from front end:
function abc(){
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: { action: 'savedata', 'question_id': document.getElementById('question_id').value, 'text': document.getElementById('text').value },
success: function(data){
alert('success');
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
anyone has any idea?
Thanks.
Wordpress ajax function infromation
Add this functions and check your post data is called or not ?
wp_ajax_nopriv_(action) executes for users that are not logged in.
add_action( 'wp_ajax_savedata', 'custom_savedata' );
add_action( 'wp_ajax_nopriv_savedata', 'custom_savedata' );
function custom_savedata() {
global $wpdb;
if(isset($_POST) && !empty($_POST['question_id'])):
$data = ($wpdb->insert('table_name_add_here', array(
'question_id' => $_POST['question_id'],
'text' => $_POST['text'],
)
));
if($data){
echo 'success';
}else{
echo 'not success';
}
else:
echo 'please check post data';
endif;
exit;
}
plz remove second line
echo "<pre>";print_r($_POST);exit;'
so it execute rest of code and return.
if u should try this and also not get solution than u must be check your database table name if table name pretend by 'wp' than u should try wp_ questoptions as table name in query instead of questoptions.
thinks. might be it will help you.
I'm working on a child theme, In my-page-template.php I have :
$id_curr= 5; //calculated value through code
wp_localize_script('my_js', 'ajaxload', array('post_id' => $id_curr));
In my_js.js I have an AJAX call :
$.ajax({
//...
type: 'post',
data: {
action: 'ajax_load',
post_id: ajaxload.post_id
}
})
Now in functions.php, I want to edit/update ajaxload.post_id according to a new result. Is there a way to do that? If I try re-calling wp_localize_script() with the same $name as shown below, will this work?
$id_new= 8; //new calculated value
wp_localize_script('my_js', 'ajaxload', array('post_id' => $id_new));
After deep research, I venture to answer my question.
Wordpress have the function wp_send_json() that allows to send a response back to an AJAX request. This function can update ajaxload.post_id.
In functions.php :
$return = array('post_id' => $id_new);
wp_send_json($return);
In my_js.js :
$.ajax({
type: 'post',
data: {
action: 'ajax_load',
post_id: ajaxload.post_id
},
success:function(data) {
var result = $.parseJSON(data);
ajaxload.post_id = result.post_id;
}
});
create an array with IDs.
$ids = array( 5, 8 );
foreach ( $ids as $id ) {
wp_localize_script('my_js', 'ajaxload', array('post_id' => $id));
}
This question might have already been asked. But I couldn't figure out how to do this.
So.. in the url I have example.com/get-coupon.php?id=288 this is a post id from a custom post type in wordpress.
What I want to do, is send this ID to an other file that makes a db query using this ID to return a coupon code. But I only want it to make this query and display the code, when the visitor presses a button.
My current get-coupon.php:
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<button id="getcode">Get Your Code</button>
<div id="resultip"></div>
<script>
$('#getcode').click(function(e) {
var pID = '<?php $_GET['id'] ?>';
$.ajax({
type: 'POST',
url: 'coupon.php',
data: { id: pID },
success: function(response) {
content.html(id);
}
});
});
</script>
And my coupon.php
$id = $_GET['id'];
/** Loads the WordPress Environment and Template */
global $wpdb, $wp_query;
include('wp-load.php');
$id = $_GET['id'];
$args = array( 'post_type' => 'coupon', 'p' => $id );
$loop = new WP_Query( $args );
$coupon = get_post_meta( $post->ID, 'clpr_coupon_code', true );
echo $coupon;
And again, I'd like to pass the ID variable from the URL to the query file.