Developer Snippet Diary

Ajax Jquery: send form data to server using AJAX JQuery

In modern web development, it's common to send form data to a server without refreshing the entire page. AJAX (Asynchronous JavaScript and XML) with jQuery provides a convenient way to achieve this. In this article, we'll explore a basic example of sending form data to a server using AJAX and jQuery.

index.php

<form id="formid" action="your_server_endpoint.php" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">

    <label for="email">Email:</label>
    <input type="text" id="email" name="email">

    <label for="superheroAlias">Superhero Alias:</label>
    <input type="text" id="superheroAlias" name="superheroAlias">

    <input type="submit" value="Submit">
</form>
<script>
$(document).ready(function() {
    $("#formid").submit(function(e) {
        e.preventDefault(); // Prevent the actual form submission.
        var form = $(this);
        var url = form.attr('action'); // The URL where the form data will be sent.
        // Serialize the form data to send it to the server.
        var formData = form.serialize();
        $.ajax({
            url: url,
            type: 'POST',
            data: formData,
            error: function() {
                alert("Error occurred while submitting the form.");
            },
            success: function(data) {
                alert("Server response: " + data);
            }
        });
    });
});

</script>

or send data in variable

var data = {
    'name'  : 'rizwan',
    'email': gondal@gm,
    'superheroAlias'    : ok
};

your_server_endpoint.php

<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    // Access the form data sent via AJAX.
    $name = $_POST["name"];
    $email = $_POST["email"];
    $superheroAlias = $_POST["superheroAlias"];

    // Process the data or perform any necessary actions.
    
    // Send a response back to the client (optional).
    echo "Data received successfully!";
} else {
    // Handle other types of requests or show an error.
    echo "Invalid request method.";
}
?>

 

You must add jquery first to make this code working..

By combining HTML forms, jQuery, and AJAX, you can create dynamic and responsive web applications that communicate seamlessly with servers. This basic example provides a foundation for more complex interactions, such as handling JSON data or incorporating additional form validation. Feel free to adapt the code to suit your specific project requirements.

Posted by: R GONDAL
Email: rizikmw@gmail.com