form post with ajax error

Hi everyone So I try to send form data integred by a ajax json function to a node server.

And I try the official code : https://learn.jquery.com/ajax/ajax-and-forms/ and https://api.jquery.com/jquery.post/

And my code :

<script>
// Attach a submit handler to the form
$( ".formdeleteuserwork" ).submit(function( event ) {

  // Stop form from submitting normally
  event.preventDefault();

  // Get some values from elements on the page:
  var $form = $( this ),
    term = $form.find( "input[name='idpublic']" ).val(),
    url = $form.attr( "action" );

  // Send the data using post
  var posting = $.post( url, { idpublic: term } );

  // Put the results in a div

});
</script>

and the html :

<form action="/formdeleteuserwork" id="formdeleteuserwork" class="formdeleteuserwork" method="post" style="position: absolute; top: -656px; left: -298px;"><input style="position: relative; top: 224px; left: -518px;" name="idpublic" value="something" src="http://127.0.0.1:8080/static/dfsfsdgfd/gfdsgsdfg.png" class="removeinvit" type="image"></form>

This code doesn't work : the page is refreshing.

Can you help me. Thanks !

1 answer

  • answered 2018-04-14 15:40 wigi

    As you wrote, that you create the form dynamically, you will need live event listeners instead of the default event listeners. Live event listeners do listen to any events on dynamically created nodes.

    So you will need to replace your listener with this:

    $( document ).on('submit', '.formdeleteuserwork', function( event ) {
    
        event.preventDefault();
    
        // your code
    
    });