Sending PHP variables with ajax and then displaying a mysql query result - php

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.

Related

Declaring and using global variables in a custom admin menu item

I'm working on a custom review system. In this project in need to have and ID passed from a callback function which is declared below:
add_action( 'wp_ajax_edit_review', 'edit_review_callback' );
function edit_review_callback() {
check_ajax_referer( 'edit-review-function', 'security' );
$GLOBALS['review_edit_id'] = $_POST['table_id'];
echo $GLOBALS['review_edit_id'];
die();
}
That function is called like this:
$(".edit_review").click(function() {
//Select the right id for selecting right row
var tr = $(this).closest('tr');
var td = tr.find('td:eq(0)').text();
//Create data to send withs security nonce
var data = {
action: 'edit_review',
security: '<?php echo $ajax_nonce_edit; ?>',
table_id: td
};
//Send ajax-request
$.post(ajaxurl, data, function(response) {
alert( 'Response: ' + response );
});
var url = "<?= get_site_url() . '/wp-admin/admin.php?page=sub_menu_item_two_review'?>";
$(location).attr('href',url);
});
I want to set these global variables to use them in my custom menu item.
Which is declared like this:
add_submenu_page(
'review_page_slug',
'review_menu_page',
'Edit review',
'manage_options',
'sub_menu_item_two_review',
'edit_review_render'
);
Some where in here i want to use the variable:
function edit_review_render() {}
Ways I have tried to declare global variables;
global $review_edit_id; $review_edit_id = value;
$GLOBALS['review_edit_id'] = $_POST['table_id']; //As visible in the code below;
Ways I have tried to read variables:
global $review_edit_id; var_dump($review_edit_id); //Same as using the databas with global $wpdb;
var_dump($GLOBALS['review_edit_id']);
echo $GLOBALS['review_edit_id'];
I'm new to wordpress and have been working with it for about 4 weeks by now. I think its fun but I've been stuck on this part since the day before yesterday. Any help woud be much apriciated(and sorry for the big amount of code.).

How to get Wordpress post filter (misha_filter_function) to filter CPT categories associated by a tag

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?

Get PHP values in AJAX to replace input field values

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

Update Data parameter of a localized script in Wordpress

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

Rating not add with ajax in wordpress

I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)

Categories