How to use ajax in wordpress page

  • 5 years-11 months

    How to use ajax in wordpress page

    • Category : php
    • Viewed : 112 times
    • Posted On :
    • Posted by : Vikas

    This article, aimed at plugin developers, describes how to add Ajax to a plugin or page. Before reading this article, you should be familiar with the following

    // function.php in Wordpress -------- Start Code--------
    add_action('wp_head', 'dorcode_ajaxurl');
    function dorcode_ajaxurl() {
       echo '<script type="text/javascript">
               var ajaxurl = "'.admin_url('admin-ajax.php').'";
            </script>';
    }
    
    
    add_action( 'wp_ajax_your_dorcode', 'my_dorcode' );
    add_action( 'wp_ajax_nopriv_your_dorcode', 'my_dorcode' );
    
    function my_dorcode() {
    	$data_id = intval( $_POST['data_id'] );
        echo $data_id;
        wp_die();
    }
    // function.php in Wordpress -------- End Code--------
    
    
    
    // Anywhere in Wordpress -------- Start Code--------
    
    // if you need
    var ajaxurl = "<?php echo admin_url('admin-ajax.php') ?>";
    jQuery(document).ready(function($) {
    	var data = {
    		'action': 'your_dorcode',
    		'data_id': 1525
    	};
    	jQuery.post(ajaxurl, data, function(response) {
    		alert('Got this from the server:' + response);
    	});
    
    });
    // Anywhere in Wordpress -------- End Code--------

Report this or Ask your own question

Your Answer

When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
Let's work to help developers, not make them feel stupid.