0

I have a plugin to submit a form via ajax.

I have this as the js:

<script type='text/javascript'>
        $(document).ready(function() {
            $('#form_id').submit(function() {
                                e.preventDefault();
                var $form = $(this);
                $.post($form.attr('action'), $form.serialize(), function(data) {
$('#feedback_id').html(data);
                });
                return false;
            });
        });
    </script>

The HTML of the form is like:

$action=admin_url('admin-ajax.php');

  <form method='post' action='$action'  id='form_id'>
<ul><li><input type='text' name='dname'  placeholder='Name'  />
</li><li><input type='email' name='email' class='field-style field-split align-left'  /></li>
<li>
<input type='hidden' name='action' value='php_function'/>
<input type='submit' value='SUBMIT' />
</li>
</ul>
</form>
<div id='feedback_id'></div>

There is a function php_function() to process the form input. Every other thing is in place:

add_action('wp_ajax_php_function', 'php_function');
add_action('wp_ajax_nopriv_php_function', 'php_function');

The output is supposed to be displayed in the div with id feedback_id but it opens and shows up in the page '/wp-admin/admin-ajax.php'

What am i doing wrong?

2

You're not passing the event object in your submit function, so e.preventDefault(); doesn't stop the form from being submitted.

$('#form_id').submit(function(e) { // <--- event object 'e'
    e.preventDefault();
  • Have added the e in the bracket. Still same behavior. – bodesam May 25 '17 at 22:51
  • Look at your browser's error console for javascript errors. If you're using the built in version of jQuery, $(document).ready(function() should be jQuery(document).ready(function($). – Milo May 25 '17 at 22:53
  • Thanks. Working now. Though I had to remove the $ from var $form . – bodesam May 25 '17 at 23:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.