-1

The post request is a simple message with two parameters retreived from the form. When I send the form, I get redirected but the callback function is not called (there should be a message in the console). Any ideas? Works fine in chrome...

 <form action="#" method="post">
    <input type="text" id="message" size="27">
    <input style="display:none;" type="text" id="pseudo" size="27" value="<?php echo '<span class=chatType>[' . $_SESSION['type'] . ']</span><span class=chatPseudo> ' . $_SESSION['pseudo'] . '</span>'; ?>">
    <button type="submit" id="envoyer" title="Envoyer" class="sendbutton">Send</button>
  </form>
</fieldset>


<script>
  $(function() {
    afficheConversation();

    $('#envoyer').click(function() {
        var message = $('#message').val();
        var pseudo = $('#pseudo').val();
        $.post('/../chat.php', { 
          'message': message,
          'pseudo':  pseudo,
           async:false
        }, function () {
          console.log('message sent : '+message);
          $('#message').val('');
          afficheConversation();
        });
  • 4
    Never use `async:false`, ever – Liam Feb 19 '18 at 16:05
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Liam Feb 19 '18 at 16:07
  • 3
    It's because you're clicking the submit button and the form is sent so your AJAX call is aborted – Rory McCrossan Feb 19 '18 at 16:07
  • 2
    To those saying don't use `async: false` - that's great advice, but not the issue here as OP is sending `async: false` as part of the request data, not setting it in the properties of the request – Rory McCrossan Feb 19 '18 at 16:08

1 Answers1

0

The issue is because you're attaching the event handler to the click of the submit button without stopping that event, so the form is still being submit which in turn is aborting your AJAX request while it's in progress.

To fix this, and make the logic semantic, hook to the submit event of the form, then call preventDefault() on the passed event to stop the submission. Something like this:

$(function() {
  afficheConversation();

  $('form').on('submit', function(e) {
    e.preventDefault();

    $.post('/../chat.php', { 
      'message': $('#message').val(),
      'pseudo':  $('#pseudo').val()
    }, function () {
      console.log('message sent: ' + message);
      $('#message').val('');
      afficheConversation();
    });
  });
});

Also note that it looks like you were attempting to make the request synchronous, although you had the syntax incorrect so the setting had no effect. Note that this is a very bad solution which should never be used. The browser will even warn you about it. Using async calls with the callback pattern is by far the best way to achieve what you're attempting here.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339