P.H. Me
P.H. Me

Reputation: 23

Put HTML form data in JSON object and make AJAX POST call

I have the following HTML code:

<!DOCTYPE html>

<html>

    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>

    <body>
        <form>
            <table>
                <tr>
                    <td><label>Brand:<input type="text" name="brand" size="5" required></label></td>
                    <td><label>Model:<input type="text" name="model" size="5" required></label></td>
                    <td><label>OS:<input type="text" name="os" size="5" required></label></td>
                    <td><label>Image link:<input type="text" name="image" size="5" required></label></td>
                    <td><label>Screensize:<input type="text" name="screensize" size="5" required></label></td>
                </tr>
            </table>
            <input type="submit" value="Submit">
        </form>
    </body>

</html>

I was wondering how I can put the data of this HTML form in a JSON object and make an AJAX POST call?

Upvotes: 0

Views: 4367

Answers (1)

VafaK
VafaK

Reputation: 524

First, use serializeArray to Encode the form elements as an array of names and values. and then send it with Ajax request.

HTML:

    <form>
        <table>
            <tr>
                <td><label>Brand:<input type="text" name="brand" size="5" required></label></td>
                <td><label>Model:<input type="text" name="model" size="5" required></label></td>
                <td><label>OS:<input type="text" name="os" size="5" required></label></td>
                <td><label>Image link:<input type="text" name="image" size="5" required></label></td>
                <td><label>Screensize:<input type="text" name="screensize" size="5" required></label></td>
            </tr>
        </table>
    </form>

<button onclick="submitForm();">Submit JSON</button>

JS:

function submitForm() {
    $.ajax({
        method: "POST",
        url: "some.php",
        data: JSON.stringify($("form").serializeArray())
    });
  }

Upvotes: 1

Related Questions