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();
}
Related
I am trying to pass a javascript variable from a range slider into a php query.
So when the user slides range slider to '44', the front-page of my wordpress theme shows all posts tagged '44'.
I want to do this without refresh, so decided to try AJAX, which I'm very new to and struggling to see where I'm going wrong.
So my range slider:
<input id="ex2" type="range" min="0" max="360" step="1" />
In my script.js:
var slider = document.getElementById("ex2");
slider.onchange = function() {
var id = $(this).val();
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/wordpress/wp-admin/admin-ajax.php",
data: {
action:'get_data',
id: id
},
success:function(data) {
alert("result: " + data);
}
});
};
I am then bouncing this value via my functions.php page.. which maybe I can avoid and go straight to my front-page? Code from my functions.php page:
function get_data() {
echo $_POST['id'];
wp_die(); //die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );
And then trying to input into my php query on front-page.php:
<?php
$slider = $_POST['id'];
$query = new WP_Query( array( 'tag' => $slider ) );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();?>
<?php the_content();?>
<?php endwhile; endif;?>
I'm very new to PHP and AJAX, not fully understanding the post or echo functions, if someone could help me with my code would be amazing.
Thanks !
It is with the page refresh, but got it working with the POST parameter, don't need any extra code in scripts.js, or functions.php, just on my front-page and for the range slider (in my footer):
My range slider code:
<form action="http://localhost/wordpress/" method="POST">
<input id="ex2" name="ex2" onchange="this.form.submit()"
type="range" min="0" max="360" step="1" />
</form>
On my front-page:
<?php
$slider = $_POST['ex2'];
$query = new WP_Query( array( 'tag' => $slider ) );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();?>
<?php the_content();?>
<?php endwhile; endif;?>
And is working !
Try Something like this...
<script src="jquery.js"></script>
<form action="#" method="POST">
<input id="ex2" name="ex2" onchange="this.form.submit()"
type="range" min="0" max="360" step="1" />
</form>
<script>
var slider = document.getElementById("ex2");
slider.onchange = function() {
var id = $(this).val();
var Url = "http://localhost/test2.php?func=myFunc";
$.ajax({
type: "POST",
dataType: "json",
url: Url,
data: {
id: id
},
success:function(data) {
// alert("result: " + data);
console.log(data);
}
});
};
</script>
test2.php
<?php
function myFunc($id)
{
echo $id;
}
if(isset($_GET['func']) && function_exists($_GET['func'])){
if($_GET['func'] == 'myFunc') {
if(isset($_POST['id'])){
$_GET['func']($_POST['id']);
}
}
}
?>
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>
I am using ajax to send data to a php function. The end goal is to display rows of data based on $tweetdate. Here is my ajax script:
jQuery('#bootstrapModalFullCalendar').fullCalendar({
dayClick: function(date, event, jsEvent, view) {
var date = date.format();
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: {
'action': 'show_scheduled_tweets',
'tweetdate': date
},
beforeSend: function() {
console.log('before')
},
success: function(){
console.log('success')
},
error: function(){
console.log('error')
},
});
}
});
Here is my php function (add_action is for WordPress usage):
<?php
add_action('wp_ajax_show_scheduled_tweets', 'show_scheduled_tweets');
function show_scheduled_tweets () {
global $wpdb;
$tweetdate = $_POST["tweetdate"];
$query = "SELECT * FROM wp_tweettweet WHERE tweetdate='$tweetdate'";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
$currentDateTime = $result[time];
$time = date('h:i A', strtotime($currentDateTime));
?>
<form class="tweetclass form-inline" action="" method="post">
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
<input class="tweetinput" type="text" name="tweetupdate" value="<?php echo $tweet2; ?>">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="timepicker" class="timepicker" value="<?php echo $time; ?>"/>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
}
show_scheduled_tweets();
?>
fullCalendar is a jQuery event calendar. When the user clicks on a day (dayClick) that day is saved to date. That date is what I am trying to save to "tweetdate" in my ajax.
In chrome, when I use the network tab on the inspector I can see the ajax result and the date clicked on is set to "tweetdate". That isn't getting picked up by my php function. In my php "tweetdate" is not getting a value assigned to it.
Now, if I go into my php function and set "tweetdate" to an actual date instead of $_POST["tweetdate"]; e.g. 2016-06-15 than everything works perfectly.
I'm not quite sure what is going on.
To make it work, you need one more essential thing:
add_action('wp_enqueue_scripts', 'my_custom_scripts');
my_custom_scripts(){
// Here you register your script for example located in a subfolder `js` of your active theme
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/js/script.js', array('jquery'), '1.0', true );
// Here you are going to make the bridge between php and js
wp_localize_script( 'ajax-script', 'my_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
See that 'ajax-script' is in both functions wp_enqueue_script() and wp_localize_script()…
Then you will retrieve 'ajaxurl' and 'my_ajax' in your js combined in url:my_ajax.ajaxurl,:
jQuery(document).ready(function($) {
jQuery('#bootstrapModalFullCalendar').fullCalendar({
dayClick: function(date, event, jsEvent, view) {
var date = date.format();
jQuery.ajax({
type: "POST",
url: my_ajax.ajaxurl,// Here 'my_ajax' & 'ajaxurl' from wp_localize_script()
data: {
'action': 'show_scheduled_tweets',
'tweetdate': date
},
beforeSend: function() {
console.log('before')
},
success: function(){
console.log('success')
},
error: function(){
console.log('error')
},
});
}
});
});
Now you can get the $_POST["tweetdate"];in your php!!!
Update: May be you need to add to your php function (for front end):
add_action('wp_ajax_nopriv_show_scheduled_tweets', 'show_scheduled_tweets');
And to and die();at the end inside your function. so you will have:
add_action('wp_ajax_show_scheduled_tweets', 'show_scheduled_tweets'); // backend
add_action('wp_ajax_nopriv_show_scheduled_tweets', 'show_scheduled_tweets'); // fronted
function show_scheduled_tweets () {
global $wpdb;
$tweetdate = $_POST["tweetdate"];
$query = "SELECT * FROM wp_tweettweet WHERE tweetdate='$tweetdate'";
$results = $wpdb->get_results($query, ARRAY_A);
foreach($results as $result) {
$tweet2 = $result[text];
$recycleOption = $result[recycle];
$id = $result[id];
$currentDateTime = $result[time];
$time = date('h:i A', strtotime($currentDateTime));
?>
<form class="tweetclass form-inline" action="" method="post">
<input type="checkbox" name="recycle" <?php if($recycleOption == 1){ echo "checked";} ?>>Recycle Tweet?
<input class="tweetinput" type="text" name="tweetupdate" value="<?php echo $tweet2; ?>">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="timepicker" class="timepicker" value="<?php echo $time; ?>"/>
<input class="tweetsubmit" type="submit" value="Save">
<input class="tweetdelete" type="submit" value="delete">
</form>
<?php
}
die(); // very important to get it working
}
Update 2: important! — It should work this time!
I have made a little typing error:
It's add_action('wp_ajax_nopriv_ … instead of add_action('wp_ajax_no_priv_ …
These php codes needs to be on the function.php file of your active theme (or child theme).
Then you will call your function somewhere else or you can hook it with some add_action() hooks.
show_scheduled_tweets();
References:
Wordpress passing ajax value to a specific page using Wordpress
Using AJAX With PHP on Your WordPress Site Without a Plugin
How to use Ajax with your WordPress Plugin or Theme?
I'm trying to send AJAX data to my wordpress table but all I can get from my PHP is a 0. Its on the admin side. Can anyone help me?
Also all of this code is inside my plugin-admin.php file inside my plugin folder.
<?php
if ( ! defined( 'ABSPATH' ) || ! current_user_can( 'manage_options' ) ) exit;
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<script>
jQuery(document).ready(function($) {
var spostsarray = new Array();
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: "POST",
action: "featured_submit_action",
data: {"posts": spostsarray},
success: function(data){
console.log(data);
}
});
});
});
</script>
I've condensed it a bit but the general idea is that I can grab all the recent posts and the user can select which ones they want to feature, send that to the PHP method and edit the table with it.
The problem is with my AJAX callback I only ever return 0 and not the data sent from the javascript.
SOLVED:
After some help from Rohil_PHPBeginner I figured it out. The reason it didn't work is that I was executing the code from the menu page at at that point it was too late to add a hook. Here is the page I used to solve it:
AJAX in WP Plugin returns 0 always
Below code worked perfectly fine for me:
<?php
global $wpdb;
global $wp_version;
$results = $wpdb -> get_results(
"
SELECT ID, post_title, post_excerpt
FROM $wpdb->posts
WHERE post_type = 'post' and post_status NOT LIKE 'auto-draft'
AND post_title NOT LIKE 'Auto Draft'
AND post_status = 'publish'
ORDER BY post_title
"
);
?>
<div class="wrap">
<h2>Select Posts</h2>
<select id="selected-posts" multiple="multiple">
<?php
foreach ( $results as $result ){
?><option value="<?php echo $result->ID; ?>"> <?php echo $result->post_title; ?> </option> <?php
}
?>
</select>
<br>
<input type="submit" id="sposts-submit"></input>
</div>
<?php
add_action( 'wp_ajax_featured_submit_action', 'featured_submit_callback' );
add_action( 'wp_ajax_nopriv_featured_submit_action', 'featured_submit_callback' );
function featured_submit_callback(){
echo "hi";
wp_die();
}
?>
<script>
jQuery(document).ready(function($) {
//Click button
$("#sposts-submit").click(function(){
var spostsarray = new Array();
$("#selected-posts").each(function(item){
spostsarray.push( $(this).val() );
});
console.log(spostsarray);
var data = {
"action": "featured_submit_action",
"posts": spostsarray
}
$.ajax({
url: ajaxurl,
type: "POST",
data: data,
success: function(data){
console.log(data);
}
});
});
});
</script>
You don't need to pass the AJAX url in that way because when I used your code, it is showing me with PHP. WordPress provides a default url for AJAX so you can use that( ajaxurl which I used in below code).
Other than that You have not added code for no-privilege user (if it is going to use only for privileged user then it is okay otherwise you need to add code for that).
WordPress returns 0 when an ajax call doesn't find a valid callback function (though the 0 could be return from many other things).
WordPress looks for callbacks matching wp_ajax_{callback} when a user is logged in and wp_ajax_nopriv_{callback} when the user is logged out. {callback} is populated with the POST'd value of the "action" hidden input. Note that you're not passing the action into your AJAX call. You should change:
data: {"posts": spostsarray},
to
data: data
Since you're not going to match a callback function without passing in action, WordPress is returning 0
This is my code and I wanna do what is commented near line 73 (//HOW CAN I CALL FUNCTION post_type_search_callback HERE???). The results need to be in the same page, below the "form". I was trying some tutorials about ajax in the web but without succeeded. Pls help! Thanks!
<?php
class OwnersTriplify {
const plugin_name = 'Owners-triplify';
public static function head() {
}
public static function initialize() {
add_action('admin_menu', 'owners_triplify_admin_actions');
function owners_triplify_admin_actions() {
add_menu_page('Owners Triplify', 'Owners Triplify', 'manage_options', 'owners-triplify/includes/OwnersTriplify.php', 'owners_triplify', plugins_url('owners-triplify/images/icon.png'));
}
function register_my_setting() {
register_setting( 'hd-group', 'hd_options');
}
add_action( 'admin_init', 'register_my_setting' );
add_action( 'admin_enqueue_scripts', 'post_type_search_enqueue' );
function post_type_search_enqueue($hook) {
if( 'index.php' != $hook ) {
// Only applies to dashboard panel
return;
}
wp_enqueue_script( 'ajax-script', plugins_url( '/js/post_type_search_query.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
wp_localize_script( 'ajax-script', 'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}
function owners_triplify() {
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<div id="div1">
<h3>Digite o post-type que deseja triplificar: </h3>
<br/>
<form method="post" name="form1" action="">
<input name="postType" value="" id="postType">
<input type="hidden" name="action" value="update">
<input type="hidden" name="option_page" value="hd_options">
<button id="button1" name="termoPesquisado" type="submit" class="button-primary">Pesquisar</button>
</form>
<br/>
</div>
<script>
$("#button1").click(function () {
//HOW CAN I CALL FUNCTION post_type_search_callback HERE???
});
/*$("#button1").click(function () {
if ( $("#div2").is( ":hidden" ) ) {
$("#div2").slideDown();
$("#div1").hide();
}
else {
}
});*/
</script>
<?php
}
function pegaValores($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$termo = pegaValores($_POST["postType"]);
?>
<?php
add_action('wp_ajax_post_type_search', 'post_type_search_callback');
function post_type_search_callback() {
?>
<div id="div2">
<h3>Digite as equivalências: </h3>
<?php
global $wpdb;
$resultado = $wpdb->get_results("SELECT distinct meta_key FROM $wpdb->postmeta WHERE post_id in(SELECT ID FROM $wpdb->posts WHERE post_type = '".$termo."')");
$correspondencias;
$tamanhoResultado = count($resultado);
for($i = 1; $i <= $tamanhoResultado; $i++) {
$correspondencias[$i] = "correspondencia";
}
$contador = 1;
//$resultado_array = array();
foreach($resultado as $resultadoX) {
echo "<p>".
$resultado_array[] = $contador."- ".$resultadoX->meta_key." => ".
"<input value=".$correspondencias[$contador]." id='correspondencia".$contador."'/>".
"</p>"; //descobrir como colocar $contador + 1 para imprimir, a fim de que inicialize com 0 o contador e o for do correspondencias
$contador++;
//$datacount = implode('-',$resultado_array);
?>
<?php
}
?>
<button id="button2" name="triplify" onclick="atualizaValores()" class="button-primary" >Triplificar</button>
</div>
<?php
}
}
}
?>
php function
Note you are declaring all your functions inside initialize.....better to declare functions outside of other functions and call them as you need them.
add_action( 'wp_ajax_post_type_search_callback', array( 'OwnersTriplify', 'my_action_post_type_search_callback' ) );
add_action( 'wp_ajax_post_type_search_callback', array( 'OwnersTriplify', 'my_action_post_type_search_callback' ) );
function post_type_search_callback() {
$data= $_POST['variable'];
$output= 'i was returned with ajax';
//need to echo output and exit here
echo $output;
exit();
}
jQuery
You need to use the word jQuery or define $ for jQuery to work in wordpress.
jQuery(document).ready(function() { // wait for page to finish loading
jQuery("#button1").click(function () {
jQuery.ajax({
type: "POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: 'post_type_search_callback',
variable: 45 // enter in anyname here instead of variable, you will need to catch this value using $_POST['variable'] in your php function.
},
success: function (output) {
console.log(output);
}
});
});
});
further reading:
http://web-profile.com.ua/wordpress/dev/ajax-in-wordpress/