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