Home > Back-end >  i have this form in my wordpress plugin. and for some reason it doenst work with jQuery
i have this form in my wordpress plugin. and for some reason it doenst work with jQuery

Time:01-12

i have a form and i wanna use jQuery with it. but when i submit it it just doesnt use the code at all.

<form id="form">

      <label>Name</label><br />
      <input type="text" name="name"><br /><br />

      <label>Message</label><br />
      <textarea name="message"></textarea><br /><br />

      <button type="submit">Submit form</button>
      
</form>






<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA 6dMBOvcRh5Pe310sBpanc6 QBmyVM=" crossorigin="anonymous">

    //have to use jQuery to get the form data
    jQuery(document).ready(function($){
        $('#form').submit(function(e){
            e.preventDefault();
            alert('hello');
            var data = $(this).serialize();
            $.ajax({
                url: 'http://localhost:8888/wp-json/v1/contact_form/submit',
                type: 'POST',
                data: data,
                success: function(response){
                    console.log(response);
                }
            });
        });
    });


    
        



</script>

i used a alert to see if it works but it just does nothing.

when i submit i get to a blank page. so the e.preventDefaults also doesnt work.

i tried using copilot but it didnt do anything usefull

CodePudding user response:

You must declare your scripts in different tags.

<script src="https://code.jquery.com/jquery-3.6.3.js" integrity="sha256-nQLuAZGRRcILA 6dMBOvcRh5Pe310sBpanc6 QBmyVM=" crossorigin="anonymous"></script>
<script>
    //have to use jQuery to get the form data
    jQuery(document).ready(function($){
        $('#form').submit(function(e){
            e.preventDefault();
            alert('hello');
            var data = $(this).serialize();
            $.ajax({
                url: 'http://localhost:8888/wp-json/v1/contact_form/submit',
                type: 'POST',
                data: data,
                success: function(response){
                    console.log(response);
                }
            });
        });
    });
</script>
  • Related