I’m trying to get a value from a PHP function through Ajax and save it in a variable in jquery.
The PHP;
add_action( 'wp_ajax_mark_as_read', array( &$this, 'readen_color' ) );
public function readen_color() {
if( isset( $_POST['post_id'] ) && is_numeric( $_POST['post_id'] ) ) {
echo 'hello';
}
}
The Jquery:
$(document).ready(function(){
alert ('Test');
var sArticleId, iPostId;
// Get the article ID and split it -
sArticleId = $("article").attr('id');
iPostId = parseInt(sArticleId.split('-')[1]);
$.post(ajaxurl, {
action:'readen_color',
post_id: iPostId
}, function (response) {
console.log(response);
var response = parseInt(response);
alert('value of response: ' + response);
});
});
Any ideas what i’m doing wrong?
Could not answer the my own question but
Now it works with:
var responsevar = response;
alert('The Server Responses: ' + responsevar);
Instead of:
var response = parseInt(response);
alert('value of response: ' + response);
You are passing ‘readen_color’ as the action parameter, but you’ve defined the ajax action as ‘mark_as_read’.
Try this:
And as for your PHP:
AJAX & “localized” data
Originally passing data from PHP to JS was only meant to be used with localization, hence the function name. Nowadays it’s widely accepted, that you can use it to transfer data as well for AJAX calls. Here’s an example on how to “localize” a script – alias: Get data from php to JS.
_Note: This is taken from a class from one of my plugins, so you’ll have to replace the
$this->foo
parts with your own.If you then want to pass data with AJAX, simply register a callback to your action (private/admin or public):
Then you can easily modify your result (or do a query or whatever comes into your mind).
Retrieve in JS
Now you’re able to call
awesomescript_obj
in your localized script file and have access to all the data (incl. those in thedata
container/array).