Connect with us

How to add ajax in WordPress

if you are looking a answer of How to call ajax in wordpress, first i have created index.php file and define ajax hooks

<?php
/*
Plugin Name:ajx
Plugin Uri:www.example.com
Author:victor
Author uri:www.example.com
version:2.0
Description:this is ajax plugin
*/

register_activation_hook(__FILE__,’callfirst’);
function callfirst(){

$args = array(
‘post_title’=>’aj main’,
‘post_content’=>'[ajaxpagecall]’,
‘post_status’=>’publish’,
‘post_type’=>’page’,

);
wp_insert_post($args);
}
add_action(‘wp_enqueue_scripts’,’you_jquery_js’);// load js in non-admin pages
function you_jquery_js(){
$myScriptUrl2 = WP_PLUGIN_URL . ‘/ajx/script.js’;
$myScriptFile2 = WP_PLUGIN_DIR . ‘/ajx/script.js’;
if ( file_exists($myScriptFile2) )
{
wp_enqueue_script(‘myscript’, $myScriptUrl2);
wp_enqueue_script( ‘myscript’);
//wp_localize_script(‘myscript’,’myAjax’,array(‘ajaxurl’=>admin_url(‘admin-ajax.php’)));
}

}
add_action( ‘wp_head’, ‘ajx_ajax_add_head_script’ );
function ajx_ajax_add_head_script(){

$getadminajax = admin_url(‘admin-ajax.php’);

echo ‘<script>var ajaxurl =’.”‘”.$getadminajax.”‘”.'</script>’;

}

add_action( ‘wp_ajax_ajx_ajax’, ‘ajx_ajax’ );
function ajx_ajax() {

include ‘ajx_ajx.php’;

die;
}

add_shortcode(‘ajaxpagecall’,’ajaxpagecallmain’);
function ajaxpagecallmain(){

include ‘ajaxpagecallmain.php’;

}
?>

Now I created file with the name of ajax_ajx.php which i want to get add queries or data which i want to get by ajax.

<?php
/*$args = array(
‘post_title’=>’aj main afeter ajax’,
‘post_content’=>'[ajaxpagecallafterajax]’,
‘post_status’=>’publish’,
‘post_type’=>’page’,

);
$v = wp_insert_post($args);
echo json_encode($v);
*/
echo ‘hello’;
?>

And added a one file with name ajaxpagecallmain.php for button on which click result will show:-

<div class=”g”>
<input type=”text” value=”oor” name=”oo_name” id=”oo_name”/>
<input type=”button” name=”bu_oo” value=”Create” id=”cr” onClick=”ssd()”/>

</div>

Your Answer

Please login or Register to submit your answer
Not the answer you are looking for? Browse other questions tagged or ask your own question.

Log In

Subscribe to our newsletter

Enter your email address to subscribe to blog and receive notifications of new articles by email.
100% Privacy. No spam guaranteed