0

I have this js in /js/functions.js:

     jQuery(document).ready( function($){
  //Some event will trigger the ajax call, you can push whatever data to the server, simply passing it to the "data" object in ajax call
  $.ajax({
    url: ajax_object.ajaxurl, // this is the object instantiated in wp_localize_script function
    type: 'POST',
    data:{
      action: 'myaction', // this is the function in your functions.php that will be triggered
      name: 'John',
      age: '38'
    },
    success: function( data ){
      //Do something with the result from server
      console.log( data );
    }
  });
});

And in functions.php I have:

<?php
add_action( 'wp_enqueue_scripts', 'so18550905_enqueue_scripts' );
function so18550905_enqueue_scripts(){
  wp_register_script( 'ajaxHandle', get_template_directory_uri() . '/js/functions.js', array(), false, true );
  wp_enqueue_script( 'ajaxHandle' );
  wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}

add_action( 'wp_ajax_nopriv_myaction', 'so18550905_wp_ajax_function' );
function so18550905_wp_ajax_function(){
  //DO whatever you want with data posted
  //To send back a response you have to echo the result!
  echo $_POST['name'];
  echo $_POST['age'];
  wp_die(); // ajax call must die to avoid trailing 0 in your response
}
?>

But I can't echo name and age on front pages.

Where is the problem?

Thanks.

8
  • Where would it echo? AJAX is happening on admin side, not client-facing side, in background.
    – GhostToast
    Jan 14, 2014 at 20:06
  • And how can I use $_POST['name'] and $_POST['age']? For example, if I want that if ($_POST['name']=='Jhon') then echo a DIV in a public file not in admin.
    – Mike
    Jan 14, 2014 at 20:11
  • The AJAX request should be expecting the PHP function to return a response. So you'd need to put everything together (after verifying it's all kosher) into an array (or string if you've not much to say) and return it
    – GhostToast
    Jan 14, 2014 at 20:23
  • if you're just printing the response somewhere, you don't have to return something, an echo should (and does) work fine. even if the response is a json object you can echo it. do you get any javascript errors in console? do you see your script and javascript object when you view page source?
    – Milo
    Jan 14, 2014 at 20:31
  • I would like to print $_POST['name'] in my WordPress home page. How can I do it?
    – Mike
    Jan 14, 2014 at 20:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.