How to read the JSON data sent by javascript in PHP

0

I want to pass a form via json to my php and then insert the data into the database.

function enviaDados(form){
    var dados = document.getElementById('form');
    console.log(dados.categoria.value);
    $.ajax({
        type: "POST",
        data: "teste do json mo louco",
        url: "includes/post.php",
        success: function(msg){
            console.log(dados.categoria.value);
        }
    });
    alert("sadfdsaf");
}

How do I read this json in my php?

    
asked by anonymous 22.01.2018 / 19:00

2 answers

0

To retrieve data from your form, you can use the serialize() function. Here's an example of how to use:

function enviaDados(form){
    var dados = document.getElementById('form');
    console.log(dados.categoria.value);
    $.ajax({
        type: "POST",
        data: $('#myForm').serialize(),
        url: "includes/post.php",
        success: function(msg){
            console.log(dados.categoria.value);
        }
    });
    alert("sadfdsaf");
}

This function will take all the values of your form and mount a structure chave valor , where the key is the name attribute of <inputs>

In your PHP script you will retrieve the values using the super global $ _POST. Let's take an example. Suppose you have the following form:

<form  method="post" id="myForm">
    Seu nome: <input type="text" name="nome">
</form>

In php you could retrieve the information entered in the name field as follows:

$nome = $_POST['nome'];
    
22.01.2018 / 19:15
0

If you are expecting a string: $ string = file_get_contents ('php: // input');

If you're expecting an object, use json_decode .

    
22.01.2018 / 19:15