HOME / BLOG / BLOG-POST

What is a ajax basic tutorial for form submit?

ajax basic tutorial for form submit

//ajax tutorial  starts here
 <script>
 $(".submit-btn").click(function(e){
  $('.popup').css("display","flex");
  var username = $(".username").val();
  
  var data = {
   'action':'form_action',
   'username':username,
  }
  
  $.post(myajax.ajaxurl,data,function(response){
   $(".result").html(response);
   $('.popup').css("display","none");
  });
  
  e.preventDefault();
 });
</script>


//function.php
<?php
function grahak_scripts(){
 
 wp_enqueue_script("grahak-script",get_stylesheet_directory_uri().'/custom.js', array('jquery'));
 wp_localize_script('grahak-script','myajax',array('ajaxurl'=>admin_url('admin-ajax.php')));
 wp_enqueue_style("grahak-style",get_stylesheet_directory_uri().'/font-awesome.css');
}
add_action("wp_enqueue_scripts","grahak_scripts");




 function form_action(){
  $username = $_POST['username'];
  
  
  global $wpdb;
  $table_name = $wpdb->prefix . "ajaxtest";
  if(($wpdb->insert($table_name, array(
  'username' => $username,
     )))){
   echo "Data entered successfully!";
  };
  
  
  die();
  
 }
 
 add_action('wp_ajax_nopriv_form_action','form_action');
 add_action('wp_ajax_form_action','form_action');
 
?>


//main form

<div class="">
  <form>
  <input type="text" style="width:300px; margin:50px" class="username" name="usernname" >
  <input type="submit"  style="width:300px; margin:0px 50px" value="submit" class="submit-btn">
  </form>

</div>

<h4 class="result"></h4>

 


about authors

Sandip Das

Web Developer

Once a legend said “Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” – Martin Fowler.



POST COMMENTS

Leave a Reply

Your email address will not be published. Required fields are marked *