1

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); 
  • Are you doing this in the admin or on a public page? – totels Nov 12 '12 at 14:10
  • @totels in functions.php and public page live example – mnewmedia Nov 12 '12 at 14:14
  • You'll need to use wp_ajax_nopriv_(action) for ajax on a public page. – totels Nov 12 '12 at 14:16
  • More details here. – totels Nov 12 '12 at 14:18
  • @totels before the test alert printed 0. Now it Prints NaN..? – mnewmedia Nov 12 '12 at 14:22
2

You are passing 'readen_color' as the action parameter, but you've defined the ajax action as 'mark_as_read'.

Try this:

$.post(ajaxurl, {
    action:'mark_as_read',
    post_id: iPostId
}, function (response) {
    console.log(response);
});

And as for your PHP:

add_action( 'wp_ajax_mark_as_read', array( &$this, 'readen_color' ) );
// Add no_priv if you want users not logged in to be able to call the function.
add_action( 'wp_ajax_no_priv_mark_as_read', array( &$this, 'readen_color' ) );

public function readen_color() {
    if( isset( $_POST['post_id'] ) && is_numeric( $_POST['post_id'] ) ) {
        // You must call die to avoid the trailing 0 in the response.
        die('hello');
    }
}
0

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.

$this->handle = 'awesomescript';
$this->action = 'awesomeaction';

wp_enqueue_script(
     $this->handle
    ,plugin_dir_url( __FILE__ ).'/js/ajax.js'
    ,array(
         'jquery'
        ,'jquery-ui-autocomplete'
     )
    ,filemtime( plugin_dir_path( __FILE__ ).'/js/ajax.js' )
    ,true
);

wp_localize_script(
     $this->handle
    ,"{$this->handle}_obj"
    ,array(
         'ajaxurl'    => admin_url( 'admin-ajax.php' )
        ,'_ajax_nonce' => wp_create_nonce( $this->nonce )
        ,'action'     => $this->action
        ,'data'       => array(
             'some_key'  => $some_value
            ,'other_key' => $some_other_value
         )
        ,'debug'      => $this->debug_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):

add_action( "wp_ajax_{$this->action}", array( $this, 'ajax_cb' ) );
add_action( "wp_ajax_nopriv_{$this->action}", array( $this, 'ajax_cb' ) );

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 the data container/array).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.