Send javascript object to php

4

I have the following class in php:

class Corretor
{
    private $id;
    private $nome;
    private $registro;
    private $email;
    private $senha;

    function __construct() {}

    /* Getters e Setters*/
}

And in my html code, I have this javascript code:

$(document).on("click", "#btn_cadastra_corretor", function(e){
e.preventDefault();
var email = $('#box_corretor_email').val();
var senha = $('#box_corretor_senha').val();
var nome = $('#box_corretor_nome').val();
var registro = $('#box_corretor_registro').val();
$.ajax({
    type: 'GET',
    dataType: 'json',
    data:{ categoria: '9', email: email, senha: senha, nome: nome, registro: registro },
    url: 'http://localhost:8080/servidor/index.php',
    success: function(resposta){
        if (resposta)
        {
            alert("Conta cadastrada com sucesso!");
        }
        else
        {
           alert("Nao foi possível cadastrar!");
        }
    },
    error: function (a, b, c){
        alert("ERRO: " + a + " : " + b + " : " + c);
    }
});

In php, I have several options that are accessed redirected by category - via a switch -. The option that makes the registration is:

case 9: /* CATEGORIA 9 - Cadastra o corretor */
    $corretor = new Corretor();
    $corretor->setEmail($_GET['email']);
    $corretor->setNome($_GET['nome']);
    $corretor->setRegistro($_GET['registro']);
    $corretor->setSenha($_GET['senha']);
    echo json_encode($operacao->CadastraCorretor($corretor), JSON_PRETTY_PRINT);
    break;

And in the operation class, I have the following code to register:

function CadastraCorretor(Corretor $corretor)
{
    try 
    {
        $stmt = Conexao::getInstance()->prepare('INSERT INTO corretor (nome, registro, email, senha, data_cadastro) VALUES (:nome, :registro, :email, :senha, :data_cadastro)');
        $stmt->execute(array(
            ':nome' => $corretor->getNome(),
            ':registro' => $corretor->getRegistro(),
            ':email' => $corretor->getEmail(),
            ':senha' => $corretor->getSenha(),
            ':data_cadastro' => implode("-",array_reverse(explode("/", date("d/m/Y"))))
        ));
        if ($stmt->rowCount() > 0)
        {
            return true;
        }
        return false;
    }
    catch (PDOException $e)
    {
        throw new Exception($e->getMessage());
    }
}

What I want to know is if I have to send an object of the javascript itself, without having to set the properties, as is happening in the third code.

    
asked by anonymous 11.03.2015 / 16:11

2 answers

5

You could serialize an object to 'Json' and in php deserialize it.

$(document).on("click", "#btn_cadastra_corretor", function(e) {
 e.preventDefault();
 var objeto = new Object();
 objeto.nome = 'Marconi';
 objeto.registro = '422009';
 objeto.email = '[email protected]';
 objeto.senha = 'bmaf@3';

 //Serialização
 var dados= JSON.stringify(objeto);

 $.ajax({
     type: 'GET',
     dataType: 'json',
     data: dados,
     url: 'http://localhost:8080/servidor/index.php',
     success: function(resposta) {
         if (resposta) {
             alert("Conta cadastrada com sucesso!");
         } else {
             alert("Nao foi possível cadastrar!");
         }
     },
     error: function(a, b, c) {
         alert("ERRO: " + a + " : " + b + " : " + c);
     }
 });

});

    
11.03.2015 / 18:32
0

Does not the broker class do anything? This is what I understood.

case 9:
    $operacao->CadastraCorretor();
    break;

Considering that your switch is on the same page, I believe you can use get within the CadastraCorretor function.

function CadastraCorretor()
{
    try 
    {
        $stmt = Conexao::getInstance()->prepare('INSERT INTO corretor (nome, registro, email, senha, data_cadastro) VALUES (:nome, :registro, :email, :senha, :data_cadastro)');
        $stmt->execute(array(
            ':nome' => $_GET['nome'],
            ':registro' => $_GET['registro'],
            ':email' => $_GET['email'],
            ':senha' => $_GET['senha'],
            ':data_cadastro' => implode("-",array_reverse(explode("/", date("d/m/Y"))))
        ));
        if ($stmt->rowCount() > 0)
        {
            echo true;
        }
        else echo false;
    }
    catch (PDOException $e)
    {
        throw new Exception($e->getMessage());
    }
}

If get does not work, try post.

Note: This is so easily solved in any frameworks that use routes and controllers that I think you should try, I've used a lot of switch, but I recommend you start adopting a framework, it would make your life a lot easier.

    
11.03.2015 / 22:53