WordPress API functions not working at AJAX functions.php call - ajax

I am trying to show subcategories of a category in WordPress using AJAX: when I select a main category, there is a call to WP Ajax and the result is used in showing the subcategories.
So far, I have the client-side code that works when not calling a WP function (this code is in a theme page):
jQuery('#cat-location-main').change(function () {
var optionSelected = jQuery(this).find('option:selected');
var valueSelected = optionSelected.val();
var textSelected = optionSelected.text();
console.log(valueSelected);
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'myajax-get-subcat',
category: valueSelected,
// send the nonce along with the request
categoryNonce: '<?php echo wp_create_nonce( 'myajax-get-subcat-nonce' );?>'
},
success: function(data, textStatus, jjqXHR) {
console.log(data);
},
dataType: 'json'
});
});
And I have this in the functions.php:
add_action('wp_ajax_myajax-get-subcat', 'myajax_get_subcat');
function myajax_get_subcat() {
$nonce = $_POST['categoryNonce'];
$main_category = $_POST['category'];
if (!wp_verify_nonce($nonce, 'myajax-get-subcat-nonce'))
die ( 'Busted!');
if(function_exists('wp_dropdown_categories')==true) {
echo 'true';
} else {
echo 'false';
}
wp_dropdown_categories('taxonomy=category&selected=1&echo=1&orderby=NAME&order=ASC&hide_empty=0&hide_empty=0&hierarchical=1&depth=1&id=cat-location-secondary&child_of='.$main_category);
exit;
}
Now I get a "true" on the client side when commenting wp_dropdown_categories line, and I get absolutely nothing when I uncomment that line (PHP crash). Nothing in php error log (WAMP setup).
Also, not working even if I add require_once(__DIR__.'/../../../wp-load.php'); but it works if I use GET in browser (for the functions.php).
Any help would be greatly appreciated!

My problem was because I do not return a json object but an html (actually mixed text and html), and you set jQuery to validate that the response is json, which it isn't.

Related

load mypage.php via ajax into a div in wordpress

i have an ajax load request working in wordpress, but i would like to load the content from another page into the container div. at the moment it just passes the url in $dataToSend as a string?
jQuery(document).ready(function(){
var $dataToSend = "my-page.php";
var $testBtn = jQuery('#text-ajax-btn');
var $holdingCtn = jQuery('#my-holding-ctn');
$testBtn.click(function(){
jQuery.ajax({
type:'POST',
url: myAjax.ajaxurl,
data:{
action:'myAjax',
dataToSend:$dataToSend,
},
success: function(data,textStatus,XMLHttpRequest){
$holdingCtn.html("");
$holdingCtn.append(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
how can i pass an entire .php page through as the $dataTosend?
I do this all the time for wordpress, give me a sec to access my repository and I will show you example code.
I think problem is your my-page.php! I imagine you custom coded it. So it doesn't have necessary functions loaded.
put following code at the top of your my-page.php (this will help with 500 error you are getting)
require('../../../wp-load.php');
ajax part should look something like this:
//start ajax
$.ajax({
url: "http://localhost/wp-content/themes/theme/my-page.php",
type: "POST",
data: data,
cache: false,
success: function (data) {
console.dir(data);
}
})
If you want to load content from my-page.php file then you can load from the server side using
$data = file_get_contents('path/to/file/my-page.php'); // pass right path/url
Then, just echo the content from your function (registered ajax handler in WordPress using add_action) and in this case it should be
echo $data;
die(); // terminate the further execution
So, it should look something like
add_action( 'wp_ajax_myAjax', 'yourAjaxHandler' );
add_action( 'wp_ajax_nopriv_myAjax', 'yourAjaxHandler' );
function yourAjaxHandler(){
$data = file_get_contents('path/to/file/my-page.php');
die($data); // echo out the string and terminates execution
}
In your success callback, you can use
success: function(data){
jQuery('#my-holding-ctn').html(data);
}
Not sure if this is fully applicable, but the super easy way is just
$("#myDiv").load("myFile.php?foo=1&bar=2...");

Joomla 2.5 Ajax component not working

I've been trying for ages to get Json working in Joomla and I just can't do it. I think I've tried every combination of URL etc so any help would be great:
this is for the admin side structure looks like
admin
-controllers
--orderitem.php
-views
--orderitem
---tmpl
----orderitem.php
-controller.php
function updateNow(newrefresh) {
var dataJSON = JSON.encode (newrefresh);
var request = new Request.JSON({
method: 'post',
url: 'index.php?option=com_customersitedetails&view=orderitem&task=refreshscreen&format=raw',
data: {
json: dataJSON
},
onComplete: function(jsonObj) {
alert("Your form has been successfully submitted ");
}
}).send();
};
Although runs the alert box it doesn't retun JSON just
View not found [name, type, prefix]: orderitem, raw, customersitedetailsView
Any ideas where I can start? thanks
You're missing views/orderitem/view.raw.php containing a CustomersitedetailsViewOrderitem class.
views/orderitem/view.raw.php
class CustomersitedetailsViewOrderitem extends JViewLegacy
{
public function display($tpl = null)
{
$response = 'Your magic response here';
echo $response;
JFactory::getApplication()->close();
}
}
You can look here for proper ajax call in joomla
How to Write PHP in AJAX
inside your controllers you should have a file "mycall.json.php" this file will process and return a json format of your ajax call
Joomla doesn't gives a build in AJAX as part of it's system. my answer is from Josef Leblanc course in lynda.com
http://www.lynda.com/Joomla-1-6-tutorials/Joomla-1-7-Programming-and-Packaging-Extensions/73654-2.html
As I said :
Write this i the frontend JS :
$.ajax({
type: 'GET',
url: 'index.php',
data: {option: 'com_componenetname', task: 'taskname.youroperation', format: 'json', tmpl: 'raw'},
dataType: 'json',
async: true, // can be false also
error: function(xhr, status, error) {
console.log("AJAX ERROR in taskToggleSuceess: ")
var err = eval("(" + xhr.responseText + ")");
console.log(err.Message);
},
success: function(response){
// on success do something
// use response.valuname for server's data
}
,
complete: function() {
// stop waiting if necessary
}
});
in the backend you should have a file under com_componentname/controllers/taskname.json.php
the file should look like this
class ComponentnameControllerTaskname extends JControllerLegacy (Legacy only J3.0)
{
public function __construct($config = array())
{
parent::__construct($config);
$this->registerTask('operationname', 'functionname');
}
public function functionname() {
// do something in backend
echo json_encode(array(''var1' => val1, 'var2' => val2 ) );
}
}
nibra - I use this in all my joomla sites and its working perfect. your comment was wrong, pease give me my credit back

Relevant data form_dropdown codeigniter

I am trying to post value using javascript in form_dropdown('') but it is not posting data on form.
Jquery library is loaded. On alert it display record of dep_selected
JQUERY On view page
function get_subdepartment() {
var dep_selected = $('select[name=txtDept]').val();
$.ajax({
data: {
dep_selected: dep_selected,
},
type: 'POST',
url: 'addVacancy/getSubDept',
success: function(data){ //alert(dep_selected);
console.log(data);
$('.subdepartment').html(data);
}
})
}
Controller Page:
function getSubDept(){
if($this->input->post('txtDept')){
echo "getSubDept > Dept: ".$this->input->post('txtDept');
}
else{
echo "getSubDept > No Return";
}
}
It display "getSubDept > No Return" Please help.
Well it's obvious, that in your controller you are requesting a post value by the key txtDept, but you don't have that when you send data with AJAX. What you have now is:
var dep_selected = $('select[name=txtLocation]').val();
and
data: {
dep_selected: dep_selected,
},
So you should simply change the first line in your controller method to
if($this->input->post('dep_selected')) {
I suggest you to do some reading about POSTing values with AJAX and how to work with JSON.

Ajax in Wordpress plugin

I am creating a simple wordpress plugin and trying to use AJAX, but I always get 0 in ajax response.
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
action: 'my_action',
whatever: '1234'
};
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response) {
alert(response);
});
});
</script>
<?php
add_action('wp_ajax_my_action', 'my_action_callback');
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
function my_action_callback() {
echo "test";
die();
}
what am I doing wrong?
You have to put the add_action at the complete bottom of your file or else it won't find the callback function
Try to change :
jQuery.post("http://localhost/taichi/wp-admin/admin-ajax.php", data, function(response)
To :
jQuery.post(ajaxurl, data, function(response)
And check if it is working on the admin side first. It should work fine.
Error Return Values
If the AJAX request fails when the request url is wp-admin/admin-ajax.php, it will return either -1 or 0 depending on the reason it failed.
Read this
Edit
admin-ajax always return default '0' as output.so while you alerting response you will 0 only.using die() in callback function will terminate that.
Had the same problem, it turned out that my callback was inside a php file which was only included to my "Theme Options" page.
To check if the function is able to trigger trougth admin-ajax.php try to add var_dump(function_exists("your_callback_name")); to the bottom of the wp-admin/admin-ajax.php (before die( '0' );) and then have a look to your ajax output.
Try the following code in your plugin file. or in function.php
jQuery(document).ready(function($){
var ajaxURL = 'http://localhost/taichi/wp-admin/admin-ajax.php';
var dataString = 'action=mnd_news';
$.ajax({
type: "POST",
url: ajaxURL,
data: dataString,
cache: false,
success: function(response){
if(response != 'error') {
alert(response);
}
}
});
});
add_action('wp_ajax_mnd_news', 'get_mnd_ajax');
add_action( 'wp_ajax_nopriv_mnd_news', 'get_mnd_ajax' );
function get_mnd_ajax() {
echo "test";
die();
}

Getting wordpress to play nice with AJAX

How do I use WP functions from AJAX calls. I've looked at the documentation for creating plugins that use ajax, but I couldn't figure out how to apply that to regular pages and posts.
Is there an easy way to just load everything without using their API? I have my way I like to do ajax and would rather not use their stuff.
This is a fluff version of my code:
Javascript (jQuery):
$('.action.next_posts').click(function() {
var last_date = $(this).attr('title');
//alert();
$.ajax({
url: WP_DIR+'functions.php?action=get_next_posts',
type: 'POST',
data: {date : last_date},
success: function(response) {
alert(response);
},
error: function(error) {
alert("error");
}
});
});
Functions.php (PHP):
// AJAX controller
if(isset($_GET['action'])) {
require_once('../../../wp-config.php');
require_once('../../../wp-includes/classes.php');
require_once('../../../wp-includes/functions.php');
wp();
echo 'ok';
echo bloginfo('name'); // NOT WORKING. TRIED adding actions..
return;
}
The following solution should work. You are going to go ahead and post directly to the WordPress installation and intercept the request before WordPress does all the querying that it would normally do. There are some caveats to this method, one of which being that some caching methods will interfere with it, but it should work fairly well for your purposes.
Besides, you said you didn't want to use the specified WordPress API, so this should be right up your alley.
JavaScript:
jQuery(document).ready(function($) {
$('.action.next_posts').click(function(event) {
event.preventDefault();
var last_date = $(this).attr('title');
$.ajax({
url: '/',
type: 'post',
data: {date : last_date, action: 'get_next_posts'},
success: function(response) {
alert(response);
},
error: function(error) {
alert("error");
}
});
});
});
functions.php
add_action('parse_request','my_request_parser');
function my_request_parser($wp) {
if( 'get_next_posts' == $_POST['action'] ) {
echo 'ok';
bloginfo('name');
exit();
}
}

Resources