Wordpress - Admin-AJAX is not saving meta data - ajax

Trying to use the built in AJAX functions with the Wordpress Admin. I've been following this tutorial, but when I run the jQuery script, the data isn't being saved to the user meta.
<?php
add_action( 'admin_footer', 'ring_jquery' );
function ring_jquery() {
?>
<script type="text/javascript">
jQuery('.ring-submit').on('click', function(){
var u = jQuery(this).attr('user'),
c = jQuery('.agt_ringc[user="'+u+'"]').val(),
x = jQuery('.agt_ringx[user="'+u+'"]').val(),
formData = 'ringu='+u+'&ringc='+c+'&ringx='+x;
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'POST',
data: formData,
success: function(e){
jQuery('.success[user="'+u+'"]').fadeIn(400).delay(400).fadeOut(400);
},
error: function(){
jQuery('.fail[user="'+u+'"]').fadeIn(400).delay(400).fadeOut(400);
}
});
});
</script>
<?php
} //End ring_jquery()
add_action('wp_ajax_my_action', 'ring_callback');
function ring_callback() {
global $wpdb; // this is how you get access to the database
$ringu = $_POST['ringu'];
$ringc = $_POST['ringc'];
$ringx = $_POST['ringx'];
update_user_meta($ringu,'agt_ringc',$ringc);
update_user_meta($ringu,'agt_ringx',$ringx);
die(); // this is required to return a proper result
}
?>

You will need to have action : my_action in the data string , or as per codex :
var data = {
action: 'my_action',
whatever: 1234
};

Issue was, as #ObmerkKronen pointed out was that I was missing an action definition in the data string (which tells the AJAX page which function to run).
formData = 'action=ring_callback&ringu='+u+'&ringc='+c+'&ringx='+x;
I also changed the name of the action hook to match the name of the function. I don't know if this was necessary, but some other things I found did it and I wanted to fit in.
add_action('wp_ajax_ring_callback', 'ring_callback');

Related

Loading php file with AJAX in Wordpress frontend

Trying out AJAX request for the first time and facing problem. I want to load a php file on button click in Wordpress site. So far after researching, I got this code:
index.php file:
<button id="ajaxbtn">Ajax</button>
<div id="ajax">Some Text</div>
ajax.php file (the file i want to be loaded):
<?php echo "Hello!" ?>
functions.php file:
add_action( 'wp_enqueue_scripts', 'myajax_data', 99 );
function myajax_data(){
wp_localize_script('menu_toggle', 'myajax',
array(
'ajax_url' => admin_url('admin-ajax.php')
)
);
}
add_action('wp_ajax_tablo', 'tablo');
add_action('wp_ajax_nopriv_tablo', 'tablo');
function tablo() {
// Grab php file output from server
ob_start();
include(get_template_directory_uri() . '/ajax.php');
$result['content'] = ob_get_contents();
$result = json_encode($result); // use wp_send_json instead to make this shorter
echo $result;
die();
}
menu_toggle.js file (js file with ajax code):
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
alert('Load was performed.');
$('#ajax').append("hello");
$('#ajax').load(response.content);
}
});
});
I can actually get alert('Load was performed.'); and $('#ajax').append("hello"); displaying, so that means that ajax was connected right way and ajax request is working correctly. But $('#ajax').load(response.content); loading whole same index page in #ajax div instead of loading the content of ajax.php file i actually want. I probably got the wrong code either in function tablo() of functions.php file, or in ajax code of menu_toggle.js file. Can someone please help with this one?
You need to convert/parse the json data in JS coming from PHP. Like :
var res = JSON.parse(response);
The full code look like :
$("#ajaxbtn").click(function () {
$.ajax({
type : 'post',
dataType : 'json',
url : myajax.ajax_url,
data : {action: 'tablo'},
success: function(response) {
//load the fetched php file into the div
var res = JSON.parse(response);
alert('Load was performed.');
$('#ajax').append("hello");
$('#ajax').load(res.content);
}
});
});
Chetan Vaghela just helped with this problem on wordpress.stackexchange.com. If someone encounters with same problem as i had, please check Chetan Vaghela's answer below:
Solution provided by Chetan Vaghela on wordpress.stackexchange.com

Ajax - Getting Null Value if no new data

I'm building a notification system and I'm just in need of one last part to make it work perfect.
When the ajax first loads it uses the php variable against the server side script to look for new content and if it does find something new it uses that new notification_id and updates the var for the next set of results, if it doesn't find anything the second time around the url notification_id becomes null and inserts null values into the div.
How would I stop this from happening?
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id'] ;?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
global: true,
dataType:"json",
cache: false,
success: function(data){
if(notification_id < data.notification_id){
$("#notif_actual_text-"+data.notification_id).prepend('<div class="notif_ui"><div class="notif_text"><div id="notif_actual_text-'+data['notification_id']+'" class="notif_actual_text"><img border=\"1\" src=\"userimages/cropped'+data['notification_triggeredby']+'.jpg\" onerror=this.src=\"userimages/no_profile_img.jpeg\" width=\"40\" height=\"40\" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br /></div></div></div></div>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
}
notification_id = data.notification_id;
}
});
}
setInterval(loadIt, 10000);
</script>
Try this (if the code above is from viewajax.php):
// Simply use isset() to check if $_GET['notification_id'] is set or not
var notification_id="<?php echo isset($_GET['notification_id']) ? $_GET['notification_id'] : $notification['notification_id']; ?>";
or if you are sending it to another file:
<?php
// Let's just say that this is viewajax.php
$notification_id = $_GET['notification_id'];
echo json_encode(array("notification_id" => $notification_id));
?>

Yii ajax file upload

I need to upload image with ajax call. But POST field with image always is empty. Part of my form:
<div class="col-lg-6">
<?php echo CHtml::activeFileField($model, 'logo'); ?>
<?php echo CHtml::textField('test', 'test'); ?>
<?php echo CHtml::submitButton('Upload'); ?>
<?php echo CHtml::ajaxSubmitButton('Upload ajax', '#');?>
</div>
If i click submitButton, then i have both test and logo fields - image uploaded.
And if i click ajaxSubmitButton, then i have only test field, logo is empty. What is the solution?
PS: i need non-extension solution.
You cannot upload files with ajaxSubmitButton by default. Use simple submit or some uploader.
If you want to upload image via ajax, here's example:
<?php echo CHtml::link('Upload ajax', '#', array("onclick"=>"js:upload_file(this)"));?>
In your js:
function upload_file(){
var fd = new FormData();
var e = document.getElementById("Model_logo");
fd.append( "Model[logo]", $(e)[0].files[0]);
$.ajax({
url: 'upload',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function (data) {
},
error: function () {
alert("ERROR in upload");
}
});
}
Change Model to your model name and this will work. Also now you can append any data to FormData and it will be passed in $_POST and your file in $_FILES.
Be carefull, this way doesn't work on ie7 and ie8 as i remember.
Based on ineersa's answer, I made some improvements:
<?php echo CHtml::link('Upload ajax', '#', array("onclick"=>"upload_file()")); ?>
In your js:
function upload_file(){
var fd = new FormData($('#model-form')[0]);
$.ajax({
url: 'upload',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function (data) {
},
error: function () {
alert("ERROR in upload");
}
});
}
This way you don't have to append each form field manually. All form data will be read automatically (including files). Just make sure that #model-form is changed according to your form id.
A way you don't need to call $.ajax(...) by yourself.
$(document).on('ajaxBeforeSend', 'form.my-form', function (event, jqXHR, settings) {
if ((settings.url.indexOf("js_skip") == -1) && $("form.my-form input[type=file]")[0].files.length) {
jqXHR.abort();
settings.cache = false;
settings.contentType = false;
settings.processData = false;
settings.data = new FormData(this);
settings.url = settings.url + "&js_skip=1";
jqXHR = $.ajax(settings);
}
});

Jquery and ajax

I am quite new to JS and JQ so I am ask this basic question. I have code like this:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('1500', function() {$(this).remove();
$('#messages').fadeOut('1000');
});
}
});
return false;
});
For now it is working like it should. But I want to add something more. Div with id #messages contains all messages, and I wish that upon deleting message it fadeout(it is working) and then load new data and present all messages again without the deleted one.
Also, there is a counter that counts unread messages, and I created separate page for ajax purpose, but I don't know how to go on from fadeOut.
This is the code from the seperate page:
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
I edited code a bit, but still nothing.
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>").show().fadeIn('1000');
});
});
}
});
return false;
});
When I look page source I can see that the content has been changed, but it is not displayed.
I didn't quite understand what you are trying to do but if this is what you mean by saying but I don't know how to go on from fadeOut you can put a callback function to fadeOut
$('#messages').fadeOut('1000', function () {
// Do something here
);

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

Resources