I am just trying to select parent box then want to have child according to the parent, my aim is to create Parent(Country) and Child(City) Selectbox, when someone select country then it should show cities of that country which are stored in DB. The page should not reload when user select country but it should hit the DB and fetch cities of that Country, I created a Wordpress page and having the long from there here i am just putting the parent and child selectbox of my html.
HTML Page/Wordpress Page:
<select name="PER_COUNTRY" id="PER_COUNTRY">
<?php $rows= $wpdb->get_results($wpdb->prepare("SELECT * FROM country ORDER BY countryname" ,13,'gargle'),ARRAY_A);
foreach($rows as $row){?>
<option value="<?php echo $row["countrycode"]?>"><?php echo $row["countryname"]?></option>
</select>
Plugin folder is created with same name ajax-test, and placed 2 files there 1 is ajax-test.php and test.js
code of ajax-test.php is below:
<?php
/**
* Plugin Name: Ajax Test
* Plugin URI: http://test.org
* Description: Allows users to select cities
* Version: 1.0.0
* Author: Javed
* Author URI: http://test.org
* License: GPL2
*/
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
function my_enqueue() {
wp_enqueue_script( 'ajax-script', plugins_url( '/test.js', __FILE__ ), array('jquery'));
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' )));
}
function my_action() {
$country_id = $_REQUEST['country_id'];
echo $country_id;
die();
}
add_action('wp_ajax_my_action', 'my_action' );
add_action('wp_ajax_nopriv_my_action', 'my_action');
?>
in the above code i didn't call global db if i can process value of user selected box here and can send back to the child selectbox, then i can do DB and table query myself.
and test.js file code is:
jQuery(document).ready(function(){
jQuery('#PER_COUNTRY').change(function(){
var country_id = jQuery(this).val();
// alert(country_id);
jQuery.ajax
({
type: 'post',
url: ajax_object.ajax_url,
data: {
action : 'my_action',
country_id : country_id,
},
success: function(data)
{
alert(data);
}
});
});
});
As you can see that // alert(country_id); is commented in test.js this is for test, yes it is getting value but i think problem is with Ajax post, need your help in this regard, kindly guide me. What is wrong i'm doing here, i have already read so many tutorials but i didn't find any mistake in my code.
Well now i am giving answer of my question to myself just because i solved it myself and i only want to share answer so that if anyone also facing same problem can solve it, my all code is perfect fine, what i miss is just jQuery Enqueue from Function file, i did include jquery from header/footer and it was working fine for all jQuery operations but when it comes to Ajax, we must define it from Function, here is a way to define jQuery in Function:
if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
wp_enqueue_script('jquery');
}
I still want to thank WisdmLabs who at least try to solve my problem. :)
Related
I am trying to create my first worpress plugin!
Actually, the idea is when i click on the button, an ajax request is sent toward php file file (ajax-process.php ), it contains a very basic code to pull some data from database and then displaying it as an alert or other in my home page .
This is my plugin floder (inside wordpress plugins folder)
DB-Puller :
- DB-Puller.php
- ajax-process.php
And js (js_file.js) + css (css_file.css) folders.
Here what contains DB-Puller.php
<?php
/**
* Plugin Name: DB-Puller
* Plugin URI: https://my-web-site.com/
* Description: This is a my firt plugin, it(s allows to display data from database.
* Version: 0.1
* Author: Firest Last name
* Author URI: https://my-web-site.com/
* License: GPL3
*/
function scripts_files_enqueue_scripts() {
// Adding css file
wp_enqueue_style('css_file',plugins_url( 'css/css_file.css', __FILE__ ) );
// Adding JS file
wp_enqueue_script( 'js_file', plugins_url( 'js/js_file.js', __FILE__ ), array('jquery'), '1.0', true );
}
add_action('wp_enqueue_scripts', 'scripts_files_enqueue_scripts');
?>
And This what contains ajax-process.php
N.B : the database table is very basic, it contains just id + text columns
<?php
function my_ajax_action_callback()
{
if (isset($_POST['req']))
{
global $wpdb;
$quer = $wpdb->get_results( "SELECT * FROM wp_custom_table_1" );
$arr = $quer[0]->text;
echo $arr;
die();
}
wp_die(); // required. to end AJAX request.
}
What contains js file
jQuery(function($){
$('body').prepend('<button class="btn" type="button">PULL DATA</button>');
$('button.btn').on('click', function()
{
$.ajax({
url:'http://127.0.0.1/wp522/wp-content/plugins/DB-Puller/ajax-process.php',
method:'POST',
data:{
req:'',
action:'my_ajax_action',
},
success:function(data)
{
alert(data);
},
error:function()
{
alert(erooor);
}
})
})
})
The Alert is sent empty ! Please help me to detect where is the problem!
Thank you.
Looking on the code it does not seem like the Wordpress way of doing this kind of thing.
First you need to include your ajax-process.php in the plugins main file e.g:
require_once plugin_dir_path(__FILE__) . '/ajax-process.php';
Second, you need to register your ajax callback like this:
add_action('wp_ajax_my_ajax_action', 'my_ajax_function');
add_action('wp_ajax_no_priv_my_ajax_action', 'my_ajax_function');
Then register the ajaxUrl in scripts_files_enqueue_scripts() so it accessible from your javascript. The admin-ajax.php file handles all ajax requests:
wp_localize_script(
'js_file',
'ajax',
array(
'ajaxUrl' => admin_url('admin-ajax.php'),
)
);
Then in your javascript you need to use the ajaxUrl and specifying the action which will tell Wordpress which callback should be triggered:
jQuery(function($) {
$('body').prepend('<button class="btn" type="button">PULL DATA</button>');
$('button.btn').on('click', function() {
$.post({
url: ajax.ajaxUrl,
data: {
req: '',
action: 'my_ajax_action',
},
success: function(data) {
alert(data);
},
error: function() {
alert('error');
}
});
});
Here is a good article AJAX in Plugins, explaining how to use ajax in a plugin.
I've been googling this for a while and have tried a number of things (for example nesting my formName and formData in the 'data:' attribute, but that resulted in parseerrors, so I'm guessing I'm pretty close to having this working! I've also removed those attributes and hard coded the items in my function, but the problem remains the same.
Everything appears to be OK and I get by success alert, but when I check my database the usermeta hasn't been updated. I don't know the best way to debug the PHP function either so any tips on that would be handy for the future!!
This is my ajax function which get's fired on blur:
function storeData(data) {
$.ajax({
type: 'POST',
formData: data,
formName: 'Testform',
action: 'storeApplicationData',
success:function( data ) {
console.log('stored form');
},
error: function(xml, error) {
console.log(error);
}
});
return false;
}
This is my PHP code in my functions file, I've hard-coded the values I'm passing in to update_user_meta for now, just to ensure that isn't the issue:
function storeApplicationData(){
update_user_meta('15', 'Testform', '12345678');
}
add_action('wp_ajax_storeApplicationData', 'storeApplicationData');
add_action('wp_ajax_nopriv_storeApplicationData', 'storeApplicationData');
I'm checking the database directly, the meta field doesn't get updated...
Any help would be appreciated!
I figured this out, I was missing the proper enqueing for my ajax url:
function theme_enqueue() {
$theme_url = get_template_directory_uri(); // Used to keep our Template Directory URL
$ajax_url = admin_url( 'admin-ajax.php' ); // Localized AJAX URL
// Register Our Script for Localization
wp_register_script( 'applications', "{$theme_url}/applicationform.js", array( 'jquery' ),'1.0', true);
// Localize Our Script so we can use `ajax_url`
wp_localize_script('applications','ajax_url',$ajax_url);
// Finally enqueue our script
wp_enqueue_script( 'applications' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue' );
I also added:
url: ajax_url,
to my ajax!
I want to call /home/***/public_html/subdomains/busuioc/wp-content/themes/scalia/json_gallery_data.php
the content of json_gallery_data.php is:
global $wpdb;
$programs = $wpdb->get_results("SELECT * FROM program_tv");
$tv=array();
foreach ( $programs as $program){
$tv[]=$program->day;
}
echo json_encode($tv);
the ajax file is:
jQuery(document).ready(function(){
loadData();
});
var loadData=function(){
jQuery.ajax({
type:"POST",
url: 'site.com/wp-content/themes/scalia/json_gallery_data.php'
}).done(function(data){
var videos=JSON.parse(data);
for(var i in videos){
alert(videos[i]);
}
});
};
$wpdb won't be defined since you're bypassing wordpress, you'll have to use wordpress' ajax api to have access to it.
put your code block inside a function, and place it in the functions.php file of your theme (if you want to keep it in a separate file, include it in the functions.php file)
function my_ajax_handler(){
global $wpdb;
$programs = $wpdb->get_results("SELECT * FROM program_tv");
$tv=array();
foreach ( $programs as $program)
{
$tv[]=$program->day;
}
echo json_encode($tv);
wp_die();
}
after that you have to "register" it with wordpress' ajax api, and you do it like this
add_action( 'wp_ajax_call_my_ajax_handler', 'my_ajax_handler' );
add_action( 'wp_ajax_nopriv_call_my_ajax_handler', 'my_ajax_handler' );
wp ajax (action)
wp_ajax_nopriv_(action)
now, the file you're going to call in your ajax request is site.tld/wp-admin/admin-ajax.php. you can hardcode it, but that wouldn't be the best thing to do. ideally you should store it in a javascript variable, and wordpress has a handy function to do exactly that. put the below in the callback function that you're using to enqueue your scripts/styles
wp_enqueue_script( 'my-ajax-script', get_stylesheet_directory_uri() . '/path/to/script.js', array('jquery') );
wp_localize_script( 'my-ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_localize_script
now all you have to do is to modify your ajax call to include the ajax trigger we registered before,
jQuery.ajax({
type:"POST",
url: my_ajax_object.ajax_url,
data: { 'action': 'call_my_ajax_handler' }
})
notice how call_my_ajax_handler is the same thing we "registered" before.
assuming that there aren't any errors, you should see the expected result.
none of the code has been tested.
take a look at the AJAX in Plugins codex entry as well.
I need to set a WC()->set inside a php jquery .get function. What do I need to do inside of the php file to get access to the WC(). Right now it is telling me that WC is undefined.
This is inside my cart.php file that displays the cart and shows two radio buttons for a delivery options.
Here is the script that handles the RB change (I've simplified just to get the function to execute the reload upon return from the php query):
<script>
jQuery(document).ready(function($){
$("#myid").change(function(){
console.log("RB Changed!");
passed_variable = "1";
$.get('http://www.example.com/test.php',
{pass_var: passed_variable},
function(data, status) {
console.log("returned");
location.reload();
});
});
});
</script>
And here is the PHP query:
<?php
global $woocommerce;
echo "START<BR>";
$temp = $_GET["pass_var"];
WC()->session->set('_delivery_loading', $temp);
// or
$woocommerce->session->set('_delivery_loading', $temp);
echo "DONE[" . $temp . "]";
?>
Why do you need to call test.php? If you use a wp_ajax_$action callback you will be within the WP framework and WC() will be loaded. here's an example cobbled together from the codex and jQuery .ajax().
Enqueue the script you will be making the ajax calls from:
function so_34107959_enqueue_script(){
wp_enqueue_script( 'so_34107959_script', plugins_url( '/js/so_34107959.js' , __FILE__ ), '1.0b', array('wc-add-to-cart'), true );
}
add_action( 'wp_enqueue_scripts', 'so_34107959_enqueue_script' );
Note that the wc-add-to-cart script is a dependency. I'm only doing that so we can use WooCommerce's localized script variables. If you need to use this somewhere that the add to cart script isn't used then you will need to wp_localize_script() and pass in the admin ajax url yourself.
Your script file so_34107959.js:
jQuery(document).ready(function($){
$("#myid").change(function(){
var passed_var = "1";
$.ajax({
url: wc_add_to_cart_params.ajax_url, // here's the ajax url from WooCommerce
data: { action: "add_foobar", pass_var: passed_var } // the action must match up to wp_ajax_$action
})
.done(function( data ) {
if ( console && console.log ) {
// should return either success or fail
console.log( data );
}
});
});
});
And finally this code is the callback for your ajax "action":
function so_34107959_ajax_add_foobar() {
$temp = isset( $_REQUEST["pass_var"] ) ? $_REQUEST["pass_var"] : '';
if( $test ){
WC()->session->set('_delivery_loading', $temp);
echo 'success';
} else {
echo 'fail';
}
die();
}
add_action( 'wp_ajax_add_foobar', 'so_34107959_ajax_add_foobar' );
add_action( 'wp_ajax_nopriv_add_foobar', 'so_34107959_ajax_add_foobar' );
Untested, so watch out for typos.
Further explanations:
The PHP code assumes that you are writing a plugin. You could cheat and put it in your theme's functions.php but I think the theme should be kept for presentation and any functionality should be in plugins.
The codex has this explanation for the wp_ajax_$action hook:
This hook allows you to create custom handlers for your own custom AJAX requests. The wp_ajax_ hook follows the format "wp_ajax_$youraction", where $youraction is your AJAX request's 'action' property.
This means that if you pass an "action" to the "data" in your .ajax() that same action will wind up as the tail end of your wp_ajax_$youraction callback.
In my example therefore here's the data bit from the .ajax() script:
data: { action: "add_foobar", pass_var: passed_var }
The action is "add_foobar". It can be whatever.
Then you append that action "add_foobar" to the end of "wp_ajax_" so that add_action() looks like:
add_action( 'wp_ajax_add_foobar', 'so_34107959_ajax_add_foobar' );
This is for the admin/logged in users. The "nopriv" in:
add_action( 'wp_ajax_add_foobar', 'so_34107959_ajax_add_foobar' );
means that the ajax hook is available to non-logged in users.
Lastly, so_34107959_ajax_add_foobar() is the the server-side function that will handle your ajax request.
I'm writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then dynamically update the link-text with output from that function.
I'm stuck with the ajax query. I've got this complicated, clearly hack-ish, way to do it, but it is not quite working. What is the 'correct' or 'wordpress' way to include ajax functionality in a plugin?
(My current hack code is below. When I click the generate link I don't get the same output I get in the wp page as when I go directly to sample-ajax.php in my browser.)
I've got my code[1] set up as follows:
mu-plugins/sample.php:
<?php
/*
Plugin Name: Sample Plugin
*/
if (!class_exists("SamplePlugin")) {
class SamplePlugin {
function SamplePlugin() {}
function addHeaderCode() {
echo '<link type="text/css" rel="stylesheet" href="'.get_bloginfo('wpurl').
'/wp-content/mu-plugins/sample/sample.css" />\n';
wp_enqueue_script('sample-ajax', get_bloginfo('wpurl') .
'/wp-content/mu-plugins/sample/sample-ajax.js.php',
array('jquery'), '1.0');
}
// adds the link to post content.
function addLink($content = '') {
$content .= "<span class='foobar clicked'><a href='#'>click</a></span>";
return $content;
}
function doAjax() { //
echo "<a href='#'>AJAX!</a>";
}
}
}
if (class_exists("SamplePlugin")) {
$sample_plugin = new SamplePlugin();
}
if (isset($sample_plugin)) {
add_action('wp_head',array(&$sample_plugin,'addHeaderCode'),1);
add_filter('the_content', array(&$sample_plugin, 'addLink'));
}
mu-plugins/sample/sample-ajax.js.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
?>
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var aref = this;
jQuery(this).toggleClass('clicked');
jQuery.ajax({
url: "http://mysite/wp-content/mu-plugins/sample/sample-ajax.php",
success: function(value) {
jQuery(aref).html(value);
}
});
});
});
mu-plugins/sample/sample-ajax.php:
<?php
if (!function_exists('add_action')) {
require_once("../../../wp-config.php");
}
if (isset($sample_plugin)) {
$sample_plugin->doAjax();
} else {
echo "unset";
}
?>
[1] Note: The following tutorial got me this far, but I'm stumped at this point.
http://www.devlounge.net/articles/using-ajax-with-your-wordpress-plugin
TheDeadMedic is not quite right. WordPress has built in AJAX capabilities. Send your ajax request to /wp-admin/admin-ajax.php using POST with the argument 'action':
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
jQuery(this).html(value);
}
});
});
});
Then hook it in the plugin like this if you only want it to work for logged in users:
add_action('wp_ajax_my_unique_action',array($sample_plugin,'doAjax'));
or hook it like this to work only for non-logged in users:
add_action('wp_ajax_nopriv_my_unique_action',array($sample_plugin,'doAjax'));
Use both if you want it to work for everybody.
admin-ajax.php uses some action names already, so make sure you look through the file and don't use the same action names, or else you'll accidentally try to do things like delete comments, etc.
EDIT
Sorry, I didn't quite understand the question. I thought you were asking how to do an ajax request. Anyway, two things I'd try:
First, have your function echo just the word AJAX without the a tag. Next, try changing your ajax call so it has both a success and a complete callback:
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var val = '';
jQuery(this).toggleClass('clicked');
jQuery.ajax({
type:'POST',
data:{action:'my_unique_action'},
url: "http://mysite/wp-admin/admin-ajax.php",
success: function(value) {
val = value;
},
complete: function(){
jQuery(this).html(val);
}
});
});
});
WordPress environment
First of all, in order to achieve this task, it's recommended to register then enqueue a jQuery script that will push the request to the server. These operations will be hooked in wp_enqueue_scripts action hook. In the same hook you should put wp_localize_script that it's used to include arbitrary Javascript. By this way there will be a JS object available in front end. This object carries on the correct url to be used by the jQuery handle.
Please take a look to:
wp_register_script(); function
wp_enqueue_scripts hook
wp_enqueue_script(); function
wp_localize_script(); function
File: functions.php 1/2
add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' );
function so_enqueue_scripts(){
wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR JS FILE', array(), false, true );
wp_enqueue_script( 'ajaxHandle' );
wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
File: jquery.ajax.js
This file makes the ajax call.
jQuery(document).ready( function($){
//Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
$.ajax({
url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
type: 'POST',
data:{
action: 'myaction', // this is the function in your functions.php that will be triggered
name: 'John',
age: '38'
},
success: function( data ){
//Do something with the result from server
console.log( data );
}
});
});
File: functions.php 2/2
Finally on your functions.php file there should be the function triggered by your ajax call.
Remember the suffixes:
wp_ajax ( allow the function only for registered users or admin panel operations )
wp_ajax_nopriv ( allow the function for no privilege users )
These suffixes plus the action compose the name of your action:
wp_ajax_myaction or wp_ajax_nopriv_myaction
add_action( 'wp_ajax_myaction', 'so_wp_ajax_function' );
add_action( 'wp_ajax_nopriv_myaction', 'so_wp_ajax_function' );
function so_wp_ajax_function(){
//DO whatever you want with data posted
//To send back a response you have to echo the result!
echo $_POST['name'];
echo $_POST['age'];
wp_die(); // ajax call must die to avoid trailing 0 in your response
}
Hope it helps!
Let me know if something is not clear.
Just to add an information.
If you want to receive an object from a php class method function :
js file
jQuery(document).ready(function(){
jQuery(".foobar").bind("click", function() {
var data = {
'action': 'getAllOptionsByAjax',
'arg1': 'val1',
'arg2': $(this).val()
};
jQuery.post( ajaxurl, data, function(response) {
var jsonObj = JSON.parse( response );
});
});
php file
public static function getAllOptionsByAjax(){
global $wpdb;
// Start query string
$query_string = "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";
// Return results
$a_options = $wpdb->get_results( $query_string, ARRAY_A );
$f_options = array();
$f_options[null] = __( 'Please select an item', 'my_domain' );
foreach ($a_options as $option){
$f_options [$option['id']] = $option['name'];
}
$json = json_encode( $f_options );
echo $json;
wp_die();
}