0

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?

P.H. Me
  • 23
  • 2
  • 7

1 Answers1

1

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())
    });
  }
VafaK
  • 514
  • 1
  • 6
  • 22