|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Doing AJAX the WordPress way. |
|
4
|
|
|
* Use this class in admin or user side |
|
5
|
|
|
* |
|
6
|
|
|
* @author Nirjhar Lo |
|
7
|
|
|
* @version 1.2.1 |
|
8
|
|
|
* @package wp-plugin-framework |
|
9
|
|
|
*/ |
|
10
|
|
|
if ( ! defined( 'ABSPATH' ) ) exit; |
|
11
|
|
|
|
|
12
|
|
|
//AJAX helper class |
|
13
|
|
|
if ( ! class_exists( 'PLUGIN_AJAX' ) ) { |
|
14
|
|
|
|
|
15
|
|
|
final class PLUGIN_AJAX { |
|
16
|
|
|
|
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Add basic actions |
|
20
|
|
|
* |
|
21
|
|
|
* @return Void |
|
22
|
|
|
*/ |
|
23
|
|
|
public function __construct() { |
|
24
|
|
|
|
|
25
|
|
|
add_action( 'wp_footer', array( $this, 'custom_name_js' ) ); |
|
|
|
|
|
|
26
|
|
|
add_action( 'wp_ajax_custom_name', array( $this, 'custom_name' ) ); |
|
27
|
|
|
add_action( 'wp_ajax_nopriv_custom_name', array( $this, 'custom_name' ) ); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Output the form |
|
33
|
|
|
* |
|
34
|
|
|
* @return Html |
|
|
|
|
|
|
35
|
|
|
*/ |
|
36
|
|
|
public function form() { ?> |
|
37
|
|
|
|
|
38
|
|
|
<form id="add_by_ajax" method="POST" action=""> |
|
39
|
|
|
<input type="text" name="text_name" placeholder="<?php _e( 'Text', 'textdomain' ); ?>"> |
|
|
|
|
|
|
40
|
|
|
<input id="ajax_submit" type="submit" name="submit" value="Submit"> |
|
41
|
|
|
</form> |
|
42
|
|
|
<?php |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
|
|
46
|
|
|
/** |
|
47
|
|
|
* The javascript |
|
48
|
|
|
* |
|
49
|
|
|
* @return Html |
|
50
|
|
|
*/ |
|
51
|
|
|
public function custom_name_js() { ?> |
|
52
|
|
|
|
|
53
|
|
|
<script type="text/javascript"> |
|
54
|
|
|
jQuery(document).ready(function() { |
|
55
|
|
|
|
|
56
|
|
|
jQuery("#add_by_ajax form").submit(function() { |
|
57
|
|
|
|
|
58
|
|
|
event.preventDefault(); |
|
59
|
|
|
|
|
60
|
|
|
var val = jQuery("input[name='text_name']").val(); |
|
61
|
|
|
|
|
62
|
|
|
jQuery.post( |
|
63
|
|
|
'<?php echo admin_url("admin-ajax.php"); ?>', |
|
|
|
|
|
|
64
|
|
|
{ 'action': 'custom_name', 'val': val }, |
|
65
|
|
|
function(response) { |
|
66
|
|
|
if ( response != '' && response != false && response != undefined ) { |
|
67
|
|
|
|
|
68
|
|
|
var data = JSON.parse(response); |
|
69
|
|
|
// Do some stuff |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
); |
|
73
|
|
|
} |
|
74
|
|
|
}); |
|
75
|
|
|
}); |
|
76
|
|
|
</script> |
|
77
|
|
|
<?php |
|
78
|
|
|
} |
|
79
|
|
|
|
|
80
|
|
|
|
|
81
|
|
|
/** |
|
82
|
|
|
* The data processor |
|
83
|
|
|
* |
|
84
|
|
|
* @return Json |
|
85
|
|
|
*/ |
|
86
|
|
|
public function custom_name() { |
|
87
|
|
|
|
|
88
|
|
|
$val = $_POST['val']; |
|
|
|
|
|
|
89
|
|
|
|
|
90
|
|
|
// DO some stuff |
|
91
|
|
|
|
|
92
|
|
|
$response = array( 'val' => $value ); |
|
|
|
|
|
|
93
|
|
|
echo json_encode( $response ); |
|
94
|
|
|
wp_die(); |
|
|
|
|
|
|
95
|
|
|
} |
|
96
|
|
|
} |
|
97
|
|
|
} ?> |
|
98
|
|
|
|