0

I have a form in a modal:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Add user
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body">
        <form action="" method="post" id="saveperson">
            <label for="newcat">Project Name</label>
            <input type="text" name="newcat" value="">
            <label for="description">Description</label>
            <input type="text" name="description" value="">
            <input type="submit" name="user" value="Submit">
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>

On submit I run the js:

$(document).ready(function() {
    $('#saveperson').submit(function(event) { //Trigger on form submit
      var postForm = { //Fetch form data
        'name'     : $('input[name=newcat]').val(),
        'desc'     : $('input[name=description]').val() //Store name fields value
      };
      $.ajax({ //Process the form using $.ajax()
        type      : 'POST', //Method type
        url       : 'process.php', 
        data      : postForm, //Forms name
        dataType  : 'json',
        success   : function(data) {
            $('.modal-body').html("Done!");
          }
          else {
            $('.modal-body').html("Error!"); 
          }
        }
      });
      event.preventDefault(); 
    });
});

And then this should run in process.php

<?php 
    header ( "Content-Type: application/json");
    $cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );  
    // Check if category exists
    if($cat_ID == 0) {
        $cat_name = sanitize_text_field($_POST['newcat']);  
        $cat_desc = sanitize_text_field($_POST['description']);
        $cat_slug = sanitize_title_with_dashes($cat_name);
        $my_cat = array(
            'cat_name' => $cat_name, 
            'category_description' => $cat_desc, 
            'category_nicename' => $cat_slug, 
            'category_parent' => 0
        );
        if( wp_insert_category( $my_cat ) ) {
            // Category added successfully
            die ( json_encode ( array ( "success" => 1)));
        } else {
            // Error while creating new category
            die ( json_encode ( array ( "success" => 0)));
        }
    } else {
        // That category already exists
        die ( json_encode ( array ( "success" => 0)));
    }
?>

But after the submit, nothing happens and the data isn't saved in the db, meaning isn't working. If I use this php tho in a standard php without ajax, it works and saves the data in the db

<?php 
    header ( "Content-Type: application/json");
    if( isset( $_POST['user'] ) ) {
        if( !empty( $_REQUEST['newcat'] ) ) {
            $cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );  
            // Check if category exists
            if($cat_ID == 0) {
                $cat_name = sanitize_text_field($_POST['newcat']);  
                $cat_desc = sanitize_text_field($_POST['description']);
                $cat_slug = sanitize_title_with_dashes($cat_name);
                $my_cat = array(
                    'cat_name' => $cat_name, 
                    'category_description' => $cat_desc, 
                    'category_nicename' => $cat_slug, 
                    'category_parent' => 0
                );
                wp_insert_category( $my_cat );
            }
        }
    }
?>
rob.m
  • 9,843
  • 19
  • 73
  • 162
  • is it go to `// That category already exists` condition ? – Natsathorn Oct 26 '18 at 04:38
  • You need to serialize the data before posting, see here https://stackoverflow.com/questions/6323338/jquery-ajax-posting-json-to-webservice – XTOTHEL Oct 26 '18 at 04:39
  • have u checked all responses are coming to your php function? – DPS Oct 26 '18 at 04:45
  • @DPS there must be some eror with the php receiving the data, it isn't running. If I run the php alone on a single page it works and saves the data. So the issue is with js sending the data and running the php, but i can't figure out where – rob.m Oct 26 '18 at 04:46
  • @Natsathorn there must be some error with the php receiving the data, it isn't running. If I run the php alone on a single page it works and saves the data. So the issue is with js sending the data and running the php, but i can't figure out where – rob.m Oct 26 '18 at 04:47
  • @rob.m I guess you are running standard Wordpress functions in core PHP file. This could be the reason php is not executing. – CodeThing Oct 26 '18 at 04:57
  • @CodeThing mmm that could be.. thought I could run wp_insert_category(); from a single php file outside wp core – rob.m Oct 26 '18 at 04:58

3 Answers3

0

There is an error in the browser console:

$(document).ready(function() {
    $('#saveperson').submit(function(event) { //Trigger on form submit
      var postForm = { //Fetch form data
        'name'     : $('input[name=newcat]').val(),
        'desc'     : $('input[name=description]').val() //Store name fields value
      };
      $.ajax({ //Process the form using $.ajax()
        type      : 'POST', //Method type
        url       : 'process.php', 
        data      : postForm, //Forms name
        dataType  : 'json',
        success   : function(data) {
            $('.modal-body').html("Done!");
          }
          else {
            $('.modal-body').html("Error!"); 
          }
        }
      });
      event.preventDefault(); 
    });
});

Notice the

          else {
            $('.modal-body').html("Error!"); 
          }

Error:

Uncaught SyntaxError: Unexpected token else

Remove the else block, it should work

It should be:

$(document).ready(function() {
    $('#saveperson').submit(function(event) { //Trigger on form submit
      var postForm = { //Fetch form data
        'name'     : $('input[name=newcat]').val(),
        'desc'     : $('input[name=description]').val() //Store name fields value
      };
      $.ajax({ //Process the form using $.ajax()
        type      : 'POST', //Method type
        url       : 'process.php', 
        data      : postForm, //Forms name
        dataType  : 'json',
        success   : function(data) {
            $('.modal-body').html("Done!");
          }
      });
      event.preventDefault(); 
    });
});

Here is the fiddle

Aditya Sharma
  • 645
  • 1
  • 10
  • 28
0

Did u try this?

 $( "#saveperson" ).submit(function( event ) {
       let form = $( this );

      let formData = new FormData(form[0]);

     $.ajax({ //Process the form using $.ajax()
        type      : 'POST', //Method type
        url       : 'process.php', 
        data      : formData, 
        success   : function(data) {
            $('.modal-body').html("Done!");
          }
      });
      event.preventDefault();

  });
DPS
  • 943
  • 11
  • 22
0

The issue was I was running wordpress standard functions from an external php file and it doesn't work. In order to achieve what i was doing, I had to use

function.php and wordpress ajax

  add_action( 'wp_footer', 'ajax_Person' );

  function ajax_Person() { ?>
    <script type="text/javascript">
    jQuery("#createCat").on("click", function(e){
      e.preventDefault();
      person();
    });
    function person(){
      jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
        success: function(data) {

        }
      });
    }
    </script>
  <?php }

  add_action('wp_ajax_data_person' , 'data_person');
  add_action('wp_ajax_nopriv_data_person','data_person');

  function data_person(){
    $catname = $_POST['catName'];
    $catdesc = $_POST["catDesc"];
    $cat_ID = get_cat_ID( sanitize_title_for_query($catname) );  
    // Check if category exists
    if($cat_ID == 0) {
        $cat_name = $catname;  
        $cat_desc = $catdesc;
        $cat_slug = sanitize_title_with_dashes($cat_name);
        $my_cat = array(
          'cat_name' => $cat_name, 
          'category_description' => $cat_desc, 
          'category_nicename' => $cat_slug, 
          'category_parent' => 0
        );
        if( wp_insert_category( $my_cat ) ) {
          echo 'Category added successfully';
        } else {
          echo 'Error while creating new category';
        }
    } else {
      echo 'That category already exists';
    }
  }
rob.m
  • 9,843
  • 19
  • 73
  • 162