Skip to content Skip to sidebar Skip to footer

Send Form Data With Jquery Ajax Json

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 abo

Solution 1:

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 requestecho json_encode($_POST);

here is my index.html

<!DOCTYPE html><html><head></head><body><formid="form"action=""method="post">
Name: <inputtype="text"name="name"><br>
Age: <inputtype="text"name="email"><br>
FavColor: <inputtype="text"name="favc"><br><inputid="submit"type="button"name="submit"value="submit"></form><scriptsrc="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 toolsconsole.log(result);
                },
                error: function(xhr, resp, text) {
                    console.log(xhr, resp, text);
                }
            })
        });
    });

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

Both file are place in the same directory

Solution 2:

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',
    ...
})

Solution 3:

You can use serialize() like this:

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

  }
});

Solution 4:

Why use JQuery?

Javascript provides FormData api and fetch to perform this easily.

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

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

Solution 5:

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:

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

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

Post a Comment for "Send Form Data With Jquery Ajax Json"