WordPress AJAX request returns 0 - javascript

TL;DR: Not Dupe - Code first, scroll to bottom for problem.
Here is the link to the demo that I currently have.
In functions.php I localize my script first:
function ajaxurl(){
wp_enqueue_script( 'product-selector', get_template_directory_uri() . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'product-selector', 'MyAjax', array(
// URL to wp-admin/admin-ajax.php to process the request
'ajaxurl' => admin_url( 'admin-ajax.php' ),
// generate a nonce with a unique ID "myajax-post-comment-nonce"
// so that you can check it later when an AJAX request is sent
//'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' ),
)
);
}
add_action('wp_head', 'ajaxurl');
And then for the script my ajax calls on I have:
function ajax_callback() {
global $wpdb; // this is how you get access to the database
// Declare our variable.
$cat = $_POST['cat'];
// Q the DB
$query = $wpdb->get_col( $wpdb->prepare(
"
SELECT meta_value
FROM $wpdb->postmeta
WHERE post_category=%s
", $cat
) );
header('Content-Type: application/json');
wp_send_json( json_encode( $query ) );
}
add_action( 'wp_ajax_nopriv_ajax-callback', 'ajax_callback' );
And finally for ajax.js I have:
$(document).ready(function(){
var back_end_script_url = MyAjax.ajaxurl;
$(function() {
var category_callback = function(data) {
console.log(data);
var adhesion_select = $('#adhesion');
var substrate_select = $('#substrate');
substrate_select.find('option').remove();
adhesion_select.find('option').remove();
for (var k in data) {
var option = $('<option />').val(k).html(data[k]);
adhesion_select.append(option);
}
};
var adhesion_callback = function(data) {
console.log(data);
var substrate_select = $('#substrate');
substrate_select.find('option').remove();
for (var k in data) {
var option = $('<option />').val(k).html(data[k]);
substrate_select.append(option);
}
};
var category_change = function() {
console.log('Category Changed');
var category = $(this).find(":selected").val();
var params = {
action: 'ajax-callback',
cat: category
};
console.log(params);
$.post(back_end_script_url, params, category_callback);
};
var adhesion_change = function() {
console.log('Adhesion Changed');
var adhesion = $(this).find(":selected").val();
var category = $('#cat').find(":selected").val();
var params = {
action: 'ajax-callback',
cat: category,
adhesion: adhesion
};
console.log(params);
$.post(back_end_script_url, params, adhesion_callback);
};
$('#cat').on('change', category_change);
$('#adhesion').on('change', adhesion_change);
});
});
So my problem is, if you look at the demo, the ajax only returns the number 0, not the data from the db.
I have read every related question on this problem on stack and wordpress exchanges, and tried all of them out, and my result is always the same.
I hired out the JS code, but the guy swears its on my end. I'm not sure if that's true or not, because I can't find any problem in my code.
Thanks for your help, Stack!

It seems that you are missing the "action" attribute in the params you are sending on the ajax call.
Your params object should be:
var params = {
action: "ajax-call",
cat: category
};
Hope this helps,
Regards,
Marcelo

Related

Wordpress Widget: AJAX Request fails

I'm trying to make an AJAX-Request within a Wordpress Plugin in frontend, after clicking a button. -> Actually it is a Widget. So I implemented the frontend via extending de WP_Widget Class. I don't know if this is worth knowing.
I always get a 400 bad Request and '0'.
I dont wanted to use JQuery, but i also tried and there I get a 500 Internal Server Error.
Now im really confused.
I really searched up and down the internet and every question in this forum (I know there are many similar questions - but nothing worked to me)
I'm so thankful if anyone can help me.
Main Plugin File:
function scriptloader(){
$scripturl = plugin_dir_url(__FILE__) . 'includes/public/script.js';
wp_enqueue_script('script-js', $scripturl, array( 'jquery' ));
$styleurl = plugin_dir_url(__FILE__) . 'includes/public/css/main.css';
wp_enqueue_style('script-js', $styleurl, [], null, false);
$js_variable = [
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce( 'ajax_public' ),
'mystring' => "LOL!"
];
wp_localize_script('script-js', 'phpwindowobject', $js_variable);
};
add_action( 'wp_enqueue_scripts', 'scriptloader');
function k_ajax_requester(){
$mystring = "SERVER ALIVE";
echo $mystring;
wp_die();
};
add_action('wp_ajax_k_ajax', 'k_ajax_requester');
add_action('wp_ajax_nopriv_k_ajax', 'k_ajax_requester');
There is a button in frontend.php which executes ajaxrequest() by clicking in
my script.js :
function ajaxrequest(){
var url = phpwindowobject.ajax_url;
var data = {action: "k_ajax",mystring: "K_AJAX"}
console.log("Data to send:")
console.log(data)
var xhrobj = new XMLHttpRequest;
xhrobj.open('POST', url, true);
xhrobj.setRequestHeader('Content-Type', 'text/html; charset=utf-8');
xhrobj.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
console.log('Request completed');
}
else console.log("Ajax error: No data received")
}
else console.log("Ajax error: " + xhrobj.statusText );
}
};
xhrobj.onload = function(){
var answer = (xhrobj.response);
console.log(answer);
}
xhrobj.send(data);
};
What do you think?
Thank you.

Sending Object Data from AJAX to PHP

I'm trying to send data to a php file to save in database, but I don't have any response. If a checkbox is check, the [obj][idCheckbox] = 1, else [obj][idCheckbox] = 0.
File that sends
var i=0;
var objetoTodasPermissoes = function(){};
var objTodasPermissoes = new objetoTodasPermissoes();
$.each($(".classePermissoes"), function(){
objTodasPermissoes[$(this)[0].id] = 0
i++;
});
$.each($(".classePermissoes:checked"), function(){
alert('ok');
objTodasPermissoes[$(this)[0].id] = 1;
});
console.log(objTodasPermissoes);
$.each($("#userList tr"),function(){
alert(this.id);
var iduser = this.id;
$.ajax({
url:'../json/usuarioperm/savePermissions.php',
data:({
idusuario:iduser,
objTodasPermissoes:objTodasPermissoes,
}),
success:function(a){
Alert("Saved!");
}
});
});
}
the savePermissions.php file.
$iduser = $_POST["iduser"];
$perm_usuarios = $_POST["objTodasPermissoes"]["perm_usuarios"];
$perm_importar = $_POST["objTodasPermissoes"]["perm_importar"];
$perm_log = $_POST["objTodasPermissoes"]["perm_log"];
$perm_proto = $_POST["objTodasPermissoes"]["perm_proto"];
$perm_limpeza = $_POST["objTodasPermissoes"]["perm_limpeza"];
$perm_lixeira = $_POST["objTodasPermissoes"]["perm_lixeira"];
$perm_relatusuarios = $_POST["objTodasPermissoes"]["perm_relatusuarios"];
$perm_deptos = $_POST["objTodasPermissoes"]["perm_deptos"];
$perm_deptospastas = $_POST["objTodasPermissoes"]["perm_deptospastas"];
$perm_empresas = $_POST["objTodasPermissoes"]["perm_empresas"];
mysql_query("UPDATE hospital.users set
perm_usuarios=".$perm_usuarios.",
perm_importar=".$perm_importar.",
perm_log=".$perm_log.",
perm_proto=".$perm_proto.",
perm_limpeza=".$perm_limpeza.",
perm_lixeira=".$perm_lixeira.",
perm_relatusuarios=".$perm_relatusuarios.",
perm_deptos=".$perm_deptos.",
perm_deptospastas=".$perm_deptospastas.",
perm_empresas=".$perm_empresas." where id=".$iduser) or die (mysql_error());
Thank you.
PHP is kind of interesting in that it doesn't pull from $_POST like other forms when Ajax is involved. You actually will need to read the input from php://input
Here is a tiny example
$data = file_get_contents("php://input");
$response = json_decode($data, true ); // True converts to array; blank converts to object
$emailAddr = $response["email"];
Hopefully you can apply that successfully.
Edit: You can add the filter_var command to strip bad characters and sanitize the input.
$emailAddr = filter_var($response["email"], FILTER_SANITIZE_EMAIL);
$firstName = filter_var($response["firstName"], FILTER_SANITIZE_STRING);
While debugging this I would highly recommend using Chrome's Developer mode with the 'network' tab. Find your ajax call near the bottom and you can view exact header info.

Wordpress Modification To A Five-Star Rating Script

I have added custom javascript code to the header.php file of my wordpress site. I have tested this code on a basic html file and it works fine, but I cannot seem to make the vote recording function work on a wordpress post. The other components of the script are working fine (hover, vote display from a .txt file), but I cannot get the function to record the vote working. All files have read/write access.
I would greatly appreciate it if anyone could assist me or point me in the right direction to solve this.
Here is the part of the script that records the vote, I am fairly new to php and was wondering if there is something I can add/replace to modify so the code so it will work properly on Wordpress.
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
Here is a visual example for reference
Thank you for taking time to look at this, if there is any additional information that I can provide please let me know.
Here is the ratings.php that was mentioned in the script that was placed in the header.php.
ratings.php:
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = 'http://localhost/url/wordpress/wp-content/ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
}
?>
Here is the complete javascript code added to the header.php, the mouseover/mouseout seem to be working properly, so I think the javascript should be running.
Javascript added to header.php:
<?php wp_head(); ?>
<script type="text/javascript">
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
}
);
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
</script>
To solve this all I had to do was place my ratings.php file and ratings.data.txt within my wordpress theme folder and link the custom javascript to these files within my header.php file. The javascript now operates properly. This is not the proper way to do this though, ideally I should use the wp_enqueue_scripts hook in the header.php and have the custom css and js in the css/js folders. But for now this temporary fix works and I can continue experimenting.

Yii Ajax Form submit

I have a problem with my Yii Form-Submission via Ajax:
Everything worked fine on my local machine but on the Webserver I always get the error Alert...
The Ajax Error is thrown every time the function is called...
although the data is properly POST'ED and the function in the URL did what it should..
So basically everything works but the Ajax Error is thrown every time
SO here is my code:
function merge()
{
var productA = $('#Product_selected_product').val();
var productB = $('#product_dd').val();
<?php echo CHtml::ajax(
array(
'url'=>CController::createUrl('product/companyItems'),
'data'=>array('productA' => 'js:$(\'#Product_selected_product\').val()', 'productB' => 'js:$(\'#product_dd\').val()','checker' => 'erwin'),
'type'=>'post',
'dataType'=>'json',
'error'=>"function() { alert('ERROR'); }",
'success'=> "function(){window.location.href = '../product/'+productB+''}"
)
);
?>
return false;
}
The companyItems Action searches for entrys in a table with the ID of ProductA and replaces it with the ID of ProductB.
Controller Action : CompanyItems:
public function actionCompanyItems(){
if(isset($_POST['checker'])) {
$productA = $_POST['productA'];
$productB = $_POST['productB'];
$commandMerge = Yii::app()->db
->createCommand("UPDATE ebay SET product_id = :productB WHERE product_id=:productA")
->bindValues(array(':productB' => $productB ,':productA' => $productA))
->execute();
$commandDelete = Yii::app()->db
->createCommand("UPDATE product SET is_deleted = '1' WHERE id = :productA")
->bindValues(array(':productA' => $productA))
->execute();
}
I hope someone can help me....
Dave

Hook AJAX in Wordpress

I have been delving into the world of Javascript and AJAX. I am super close, but for some reason I do not think I am hooking into wordpress ajax functions right. I have poured through the docs and this and think it is 99% there.
Is what this app does is there is a list of items. Each one with a + button. Clicking the button pops up a confirm box, and if confirmed grabs the needed data to pass to the php. The php adds the item into mysql with wpdb->insert. It also does some changes if you buy.
The js works all the way up to the call, grabbing the right values etc. Testing the php separately works as well if I hard code the values it is supposed to grab from POST. So I KNOW both pieces run, I just can't get the js to call the ajax api right. Can someone please take a look at this and let me know how to hook these together so the ajax call actually runs the php?
Here is the code.
<?php
add_action( 'admin_footer', 'addItemAJAX_javascript' );
function addItemAJAX_javascript() {
$adminAJAX = admin_url('admin-ajax.php');
?>
<script type="text/javascript" language="JavaScript">
$(function() {
$( "input[name=btnAddItem]" )
.button()
.click(function( event ) {
event.preventDefault();
var confirmAction = confirm('Are you sure you want to add this item to your character?');
if (confirmAction==true) {
// build data for AJAX call
var cID = $('#hdnCharID').val();
cID = cID*1;
var charMoney = $('#hdnCharMoney').val();
var thisValue = $(this).val();
var iID = $(this).prev('input[id="hdnItemID"]').val()
iID = iID*1;
//Add or Buy Item
if (thisValue != "+") {
var buy = 1;
}
else {
var buy = 0;
}
var ajaxurl = <?php echo json_encode($adminAJAX); ?>;
console.log('cID = ' + cID);
console.log('charMoney = ' + charMoney);
console.log('thisValue = ' + thisValue);
console.log('iID = ' + iID);
console.log('buy = ' + buy);
console.log('ajaxurl = ' + ajaxurl);
var data = {
action: 'addItemAJAX',
charID: cID,
itemID: iID,
buyItem: buy
};
console.log('data = ' + data);
console.log(data);
//WP ajax call
$.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
}
else {
console.log('add item aborted');
}
});
});
</script>
<?php
};
addItemAJAX_javascript();
// PHP SIDE OF AJAX - Handeling Request //// AJAX PROCESSING /////////////////////////////////
add_action('wp_ajax_addItemAJAX', 'addItemAJAX_callback');
function addItemAJAX_callback() {
global $wpdb;
$charID = intval($_POST['charID']);
$itemID = intval($_POST['itemID']);
$buyItem = intval($_POST['buyItem']);
// //get item details
$getItemDetailsSQL = "
Select
fyxt_wp_db_fatcow.fyxt_items.idfyxt_items,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_name,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_description,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_cost,
fyxt_wp_db_fatcow.fyxt_items.fyxt_item_weight
From
fyxt_wp_db_fatcow.fyxt_items
Where
fyxt_wp_db_fatcow.fyxt_items.idfyxt_items = $itemID";
$getItemDetailsResults = $wpdb->get_row($getItemDetailsSQL);
$iID = $getItemDetailsResults->idfyxt_items;
$iName = $getItemDetailsResults->fyxt_item_name;
$iDesc = $getItemDetailsResults->fyxt_item_description;
$iCost = $getItemDetailsResults->fyxt_item_cost;
$iWeight = $getItemDetailsResults->fyxt_item_weight;
$charItemTable = fyxt_char_items;
$wpdb->insert(
$charItemTable,
array (
idfyxt_item => $iID,
idfyxt_character => $charID,
item_name => $iName,
item_desc => $iDesc,
item_cost => $iCost,
item_weight => $iWeight,
item_quant => 1,
equip => 0,
carried => 1
)
);
$wpdb->print_error();
$newItemAdded = $wpdb->insert_id;
//remove cash if item is bought
if ($buyItem == 1 ) {
$curCharMoneySQL =
"Select
fyxt_wp_db_fatcow.fyxt_characters.char_money
From
fyxt_wp_db_fatcow.fyxt_characters
Where
fyxt_wp_db_fatcow.fyxt_characters.idfyxt_character = $charID";
$curCharCash = $wpdb->get_var($curCharMoneySQL);
$wpdb->print_error();
$newCash = $curCharCash - $iCost;
$changeCashSQL = "
UPDATE fyxt_characters
SET
char_money = $newCash
WHERE
idfyxt_character = $charID";
$changeCash = $wpdb->query($changeCashSQL);
$wpdb->print_error();
}
$debugArray = Array();
array_push($debugArray,$charID, $itemID, $buyItem, $getItemDetailsSQL, $getItemDetailsResults,$newItemAdded, $newCash);
echo $debugArray ;
die();
}
?>
I am pretty sure it is 1 (or 2) of 2 things. I am not sure if I am hooking these functions to wordpress right. Or there might be issues with nested functions I have for the jQuery button. I doubt it is number 2 though because it seems to work... I just get a 0 back from the server without any database activity. Here is what the log says.
cID = 112 ?charID=112:538
charMoney = 9990 ?charID=112:539
thisValue = + ?charID=112:540
iID = 664 ?charID=112:541
buy = 0 ?charID=112:542
ajaxurl = http://localhost/nnnnnnnn.com/wp-admin/admin-ajax.php ?charID=112:543
data = [object Object] ?charID=112:550
Object {action: "addItemAJAX", charID: 112, itemID: 664, buyItem: 0} ?charID=112:551
XHR finished loading: "http://localhost/nnnnnnnn.com/wp-admin/admin-ajax.php". jquery-1.9.1.js:8526
send jquery-1.9.1.js:8526
jQuery.extend.ajax jquery-1.9.1.js:7978
jQuery.(anonymous function) jquery-1.9.1.js:7614
(anonymous function) ?charID=112:554
jQuery.event.dispatch jquery-1.9.1.js:3074
elemData.handle
Thank you very much for all of the help and suggestions!
First of all you need to add hooks in proper way
// For the users that are not logged in
add_action( 'wp_ajax_nopriv_addItemAJAX', 'addItemAJAX_callback' );
// For the users that are logged in:
add_action( 'wp_ajax_addItemAJAX', 'addItemAJAX_callback' );
// ajax handler
function addItemAJAX_callback()
{
// code goes here
// since $debugArray is an array, so
die(json_encode($debugArray)); // last line
}
One hook will work when user is logged in and another will work when user is not logged in (for any user). If you are making ajax request for logged in users then, wp_ajax_nopriv_ hook is required.
Keep your js/ajax code in a separate file in yourthemefolder/js/myAjaxScript.js and also keep following code in your functions.php file
add_action('wp_enqueue_scripts', 'my_load_scripts');
function my_load_scripts()
{
// for pluggin, you may use "plugin_dir_url( __FILE__ )"
wp_enqueue_script( 'my_ajax-script', get_stylesheet_directory_uri() . '/js/myAjaxScript.js', array('jquery') );
// Following code will let you use "ajaxObj.ajax_url" to get the
// ajax url (admin-ajax.php) in your my_ajax_scriptjs file
wp_localize_script(
'my_ajax-script', 'ajaxObj', array( 'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
In your my_ajax_script.js file, you may code like this
var data = {
action: 'addItemAJAX_callback',
// ...
};
$.getJson(ajaxObj.ajax_url, data, function(response) {
// response is an object
// ...
});
Alos remember, when using ajax from admin panel, you don't need to use wp_localize_script, since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php.
I won't go through your code as it seems a bit hard to replicate (see SSCCE for this matter). But I'll outline how to work with Ajax and WordPress (from How to Use AJAX in a WordPress Shortcode?):
1) Enqueue and localize the JavaScript file.
Instead of enqueueing, we could print directly in the head or footer, but it's not good practice. And the localization will pass PHP values to JS in a clean fashion.
I'm assuming you're working with a theme, otherwise change get_stylesheet_directory_uri() to plugins_url().
add_action( 'wp_enqueue_scripts', 'enqueue_so_19721859' );
function enqueue_so_19721859()
{
# jQuery will be loaded as a dependency
## DO NOT use other version than the one bundled with WP
### Things will BREAK if you do so
wp_enqueue_script(
'my-handler',
get_stylesheet_directory_uri() . '/js/ajax.js',
array( 'jquery' )
);
# Here we send PHP values to JS
wp_localize_script(
'my-handler',
'my_handler',
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'ajaxnonce' => wp_create_nonce( 'my_ajax_validation' ) // <--- Security!
)
);
}
2) Ajax for logged and non-logged users
You gotta add a public Ajax callback too with no_priv_:
add_action('wp_ajax_addItemAJAX', 'addItemAJAX_callback');
add_action('wp_ajax_no_priv_addItemAJAX', 'addItemAJAX_callback');
3) Ajax Callback and Response
The Ajax callback has security checks and uses wp_send_json_* to handle the response:
function addItemAJAX_callback()
{
check_ajax_referer( 'my_ajax_validation', 'security' );
$my_thing = something();
if( !$my_thing )
wp_send_json_error( array( 'error' => __( 'Could not retrieve a post.' ) ) );
else
wp_send_json_success( $my_thing );
}
4) Finally, the script
It's essential to wrap all jQuery with noConflict mode.
You can pass whatever info you need through the localized object my_handler. We check 3 things from the response:
total failure: couldn't reach the callback or didn't pass security
partial failure: the callback was reached but returned json_error
success: proceed with your thing
jQuery( document ).ready( function( $ ) {
var data = {
action: 'addItemAJAX_callback',
security: my_handler.ajaxnonce
};
$( '#my-submit' ).click( function(e) {
e.preventDefault();
$.post(
my_handler.ajaxurl,
data,
function( response ) {
// ERROR HANDLING
if( !response.success ) {
// No data came back, maybe a security error
if( !response.data )
$( '#my-answer' ).html( 'AJAX ERROR: no response' );
else
$( '#my-answer' ).html( response.data.error );
}
else
$( '#my-answer' ).html( response.data );
}
);
});
});

Categories

Resources