How to read JSON data sent by javascript in PHP

Asked

Viewed 295 times

0

I want to pass a form via json pro my php to then insert the data in the bd.

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?

2 answers

0

0


To recover data from your form, you can use the function serialize(). Below is 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 assemble a structure chave valor, where the key is the name attribute of the <inputs>

in your PHP script you will recover 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 typed in the name field as follows:

$nome = $_POST['nome'];
  • What I needed, gave me a good idea. Thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.