如何在jquery中将表单数据转换为JSON(初学者)?

I am trying to send data using AJAX to PHP page. I am getting all the data from the form and I am trying to convert it to JSON. However, .stringify() doesn't do the job for me.

Here is my code:

<script>
        $(document).ready(function(){

            console.log("Ready..");

            $("#profile-form").submit(function(event){
                var data = $(this).serialize();
                console.log(JSON.stringify(data));

                $.ajax({
                    type    : "POST",
                    url     : "profile.php",
                    data    : JSON.stringify(data),
                    success : function(response){
                        alert(response);
                    }
                });
            });

            //$("#profile-form").submit();
        });
</script>

I am able to see the form-data on the console. However, I am not getting any JSON data on the server. I have just done print_r($_POST['data']) in my profile.php page. However, it says variable data not defined.

There should be no $_POST['data'] available because the data you are sending is saved directly in $_POST variable, which should be accessible with print_r($_POST) or print_r(json_decode(print_r($_POST))) (since you have stringified it.)

since you already serialize your data. no need to use JSON.stringify it. also add an option dataType : json

$.ajax({
    type    : "POST",
    url     : "profile.php",
    data    : data,
    dataType : 'json',
    success : function(response){
        console.log(response);
    }
});

also on your PHP. you should do

print_r($_POST);  

According to documentation,

The .serialize() method creates a text string in standard URL-encoded notation.

Just something like single=Single&multiple=Multiple&multiple=Multiple3&check=check2&radio=radio1

It is not what you want, actually.

You can simply generate a JavaScript object and serialize it:

$.ajax({
    type     : "POST",
    url      : "profile.php",
    data     : 'data=' + JSON.stringify({
        "name": $("#name").val(),
        "password": $("#password").val()
    })
}).done(function(dt) {
});

At the server-side, $_POST['data'] will contain the JSON representation of your form.

It may be automated. Read these articles on how to do the universal solution:

Convert form data to JavaScript object with jQuery
Serialize form data to JSON