How can I send input tag value from HTML file to PHP file without form tag?

Issue

I have the following input and button tag in my HTML code:

<input id = "inputarea" type = "text" name = "inputarea" size = "40">
<button id = "sendMessage">Submit</button>

I want to take the value of the input tag and send it to a variable in my PHP file every time the user clicks on the button. I don’t want to use a form tag because I don’t want the HTML page to get redirected to the PHP file when the user clicks on the submit button. Instead, I simply want the input tag value to be sent to PHP where the value will be processed and then sent somewhere else. How can I do this?

Solution

HTML

<textarea id = "displayChat" rows = "25" cols = "41" readonly></textarea>
<input id = "inputarea" type = "text" name = "inputarea" size = "40">
<button id = "sendMessage">Submit</button>

AJAX

$(document).ready(function() {
    $("#sendMessage").click(function () {
        
        var message = $("#inputArea").val();
        
        $.ajax({
            type: "POST",
            url: "chatbox.php",
            data: {messageText: message},
            success: function(response) {
                $("#displayChat").append(response);
            }
        });
    });
});

chatbox.php

$message = $_POST["messageText"];
echo "Message successfully retrieved by PHP";

Answered By – Prem Jadhav

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published