how to use ajax in WordPress without plugin

  1. Create form in template file
<form  id="newsletter_form1" method="POST" action="">		
				<input type="email" id="news_email" placeholder="Enter your email" required>			
<button class="sbtn">Submit</button>

2. create js file that call the ajax on submit of form

var frm1 = jQuery('#newsletter_form1');
frm1.submit(function (e) {
	var email = jQuery("input[type=email]").val();
	jQuery.ajax ({
                  url: '/wp-admin/admin-ajax.php',
		  type: 'POST',
		  dataType: 'JSON',
		  data: {
			action: 'call_your_function',
			id : email
		 success: function (data)
			console.log('Submission was successful.');
		error: function (data) {
			console.log('An error occurred.');

3. Add the following code to function.php file

add_action ('wp_ajax_call_your_function', 'your_function') ;
add_action ('wp_ajax_nopriv_call_your_function', 'your_function') ;

your_function ()
		if (!isset ($_REQUEST['id']))
			$return_value = 'your error message' ;
			wp_send_json_error ($return_value) ;

		$email = $_REQUEST['id'] ;

         $return_value = ' success Your email: '. $email;
	wp_send_json_success ($return_value) ;


Leave a Reply

Your email address will not be published.

You may use these <abbr title="HyperText Markup Language">html</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>


%d bloggers like this: