maknel
maknel

Reputation: 309

Cannot pass HTML form data to PHP file with AJAX

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!

Upvotes: 0

Views: 64

Answers (1)

Harish Kommuri
Harish Kommuri

Reputation: 2854

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);
    ......  
});

Upvotes: 1

Related Questions