20

I'm new in PHP/jquery I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.

Is there anyway to do that?

Thanks for the help!

Edit:

<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
user1888798
  • 229
  • 1
  • 2
  • 5

5 Answers5

24

here is a simple one

here is my test.php for testing only

<?php

// this is just a test
//send back to the ajax request the request

echo json_encode($_POST);

here is my index.html

<!DOCTYPE html>
<html>

<head>

</head>
<body>

<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        // click on button submit
        $("#submit").on('click', function(){
            // send ajax
            $.ajax({
                url: 'test.php', // url where to submit the request
                type : "POST", // type of action POST || GET
                dataType : 'json', // data type
                data : $("#form").serialize(), // post data || get data
                success : function(result) {
                    // you can see the result from the console
                    // tab of the developer tools
                    console.log(result);
                },
                error: function(xhr, resp, text) {
                    console.log(xhr, resp, text);
                }
            })
        });
    });

</script>
</body>
</html>

Both file are place in the same directory

Oli Soproni B.
  • 2,774
  • 3
  • 22
  • 47
  • 6
    The data is posted here as url-encoded form data not json. Please refer to the answer by @Roman Susi – Ehsan88 Apr 17 '19 at 04:07
  • 1
    Not relevant to question. Asker wants to send the form data in JSON. The jQuery in the answer receives Ajax return in JSON instead of sending it in JSON. – unity100 Dec 17 '19 at 06:14
24

The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.

$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})
Roman Susi
  • 4,135
  • 2
  • 32
  • 47
4

You can use serialize() like this:

$.ajax({
  cache: false,
  url: 'test.php',
  data: $('form').serialize(),
  datatype: 'json',
  success: function(data) {

  }
});
Abhishekh Gupta
  • 6,206
  • 4
  • 18
  • 46
  • If you're using `$('form').serialize()` then you don't make data an object; it should just be `data: $('form').serialize(),`. – Anthony Grist Jun 06 '15 at 08:44
1

Why use JQuery?

Javascript provides FormData api and fetch to perform this easily.

var form = document.querySelector('form');
form.onsubmit = function(event){
    var formData = new FormData(form);
    
    fetch("/test.php",
    {
       body: formData,
       method: "post"
    }).then(…);
    
    //Dont submit the form.
    return false; 
}

Reference: https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch

Sorter
  • 9,704
  • 6
  • 64
  • 74
0

Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>';
    print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe@gmail.com" />
<button type="submit">Send!</button>

With AJAX you are able to do exactly the same thing, only without page refresh.

Frank B
  • 3,667
  • 1
  • 16
  • 22