Extract data from a .serialize

0

I am sending data from a form using the $ .get or $ .post method The data is taken by

 var dados = $(this).serialize();

My code:

$(".formResposta").submit(function(){

        var dados = $(this).serialize();

        $.get('sys/GRAVA.resposta.php',
            {
                dados : dados 

            }, function(retorno){
                $('.retorno4').show('400');
                $('#alert1').prepend(retorno);
            });
});

I would like to know how to extract the data so that it can be saved to the database. Below the code you receive in GRAVA.resposta.php

 $dados  = $_GET['dados'];
    
asked by anonymous 08.02.2018 / 12:50

2 answers

0

You can receive your data this way:

$dados  = unserialize($_GET['dados']);

give the information passed by the form as an array

To see how your form is passing the infos, do the following:

var_dump($dados);

As php does not serialize in the same way as jquery we have 2 resolutions for the problem

1- function

function unserializeForm($str) {
$returndata = array();
$strArray = explode("&", $str);
$i = 0;
foreach ($strArray as $item) {
    $array = explode("=", $item);
    $returndata[$array[0]] = $array[1];
}
 return $returndata;
}

just use it

$dados  = unserializeForm($_GET['dados']);

or use php command for this

parse_str($_GET['dados'], $dados);

Given the $ data already will be an array with your form data can of the var_dump in it.

    
08.02.2018 / 13:02
0

To be clearer, I'll post the exact codes. My form has the following values: Name, Response, IP, and Comment_ID.

Function:

$(".formResposta").submit(function(){

        var dados = $(this).serialize();

        $.get('sys/GRAVA.resposta.php',
            {
                dados : dados 

            }, function(retorno){
                $('.retorno4').show('400');
                $('#alert1').prepend(retorno);
            });
});

GRAVA.resposta.php:

      $dados  = unserialize($_GET['dados']);


  if(isset($_GET['nome']) && isset($_GET['resposta']) && isset($_GET['btnIDComent']) && isset($_GET['btnIPres'])){

$nome = $_GET['nome'];
$resposta = $_GET['resposta'];
$id_comentario = $_GET['btnIDComent'];
$ipRes = $_GET['btnIPres'];

        $db_resposta->setNome($nome );
        $db_resposta->setResposta($resposta);
        $db_resposta->setID_Comentario($id_comentario);
        $db_resposta->setIpRes($ipRes);


         if($db_resposta->inserirResposta()){
            $db_resposta->getNome();
            $db_resposta->getResposta();
            $db_resposta->getID_Comentario();
            $db_resposta->getIpRes();
         }
         else{
            echo 'Não foi possivel salvar a resposta!';

            }
  }
else{
   echo 'Error';
 }

I think it's clearer. I want to get the data coming through the get and insert into the bank. unserialize ($ _GET ['data']) did not work

    
08.02.2018 / 13:15