0

I have an HTML file (index.html) with a form in it. I want to use AJAX to pass the form input to a PHP script called messagehandler.php, and messagehandler.php should then write the form input to a text file called messages.txt. For some reason, absolutely nothing happens when I input something to the form. I know that messagehandler.php writes to messages.txt correctly. index.html and messagehandler.php are below.

index.html:

<html>
    <head>
        <meta charset="utf-8">
        <link rel="stylesheet" type="text/css" href="index.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <title>Chat</title>
    </head>

    <body>
        <div id="inputbox">
                <form id="messageinput">
                <input type="text" name="message" id="submitbox" autofocus="autofocus" autocomplete="off">
                <input type="submit" value="" id="submitbutton">
            </form>
        </div>
    </body>

    <script>    
        $("#messageinput").submit(function() {
            var $messageSent = $("#messageinput").serialize();
            alert($messageSent);

            $.ajax({
                type: 'POST',
                url: 'messagehandler.php',
                data: $messageSent,
                success: function(response) {
                    alert("it worked");
                }
            });
        });

    </script>
</html>

messagehandler.php:

<?php
    $messageSent = $_POST['message'];
    $messages = fopen("messages.txt", "a");
    fwrite($messages, addslashes("<br />" . $messageSent));
    fclose($messages);
?>

When I enter "test" into the form and submit it, the alert says the value of $messageSent is message=test.

Any idea how to get this working? Thanks!

3
  • It worked for me when i copied your code. Commented May 5, 2018 at 1:28
  • Try event.preventDefault(). $("#messageinput").submit(function(e) { e.preventDefault() ....... }); Commented May 5, 2018 at 1:42
  • @Harish Thank you so so much, that worked. It was killing me because I thought it should be working (and apparently does work for @Sarpyjr). Would you mind posting this as an answer so I can accept it? Commented May 5, 2018 at 1:46

1 Answer 1

1

HTML form submission will reload the page content. Use event.preventDefault() to prevent default actions of html elements.

$("#messageinput").submit(function(e) {
    e.preventDefault(); // -> It prevents the default actions 

    var $messageSent = $("#messageinput").serialize();
    alert($messageSent);
    ......  
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.