Decode json from php sent by jquery.ajax (POST) Wordpress

0

I have a json that is stored in the variable projects which is sent by jquery.ajax in this way:

  var proyectos = [{"Paso1": selectEmpStar},{"Paso2": selectEtapa},{"Paso3": selectServ},{"Paso4": selectCarac},{"Paso5": selectCuent},{"Paso6": selecDatos}];

Sending by post the json

  var datos = JSON.stringify(proyectos);
  jQuery.ajax({
    type: 'POST',
    cache: false,
    url:'<?php echo admin_url('admin-ajax.php') ?>',
    data:{ 
    action: 'contact_send',
    dataProyectos : datos,
    dataAsunto : valNombres
    },
    success: function() {
        alert("Mensaje Enviado");
    }
  });

and in wordpress php for sending mail:

function callback_contact_send() {
$send_to = '[email protected]';
$subject = $_POST['dataAsunto'];
$message = $_POST['dataProyectos'];
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html\r\n";
$headers .= 'From: proyectos-tecnologicos' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

$mail = mail($send_to,$subject,$message,$headers);
if($mail){
  echo "Mensaje enviado";
}else{
  echo "Error";
}
die();

}

The message arrives correctly but in this way: In what way could the json be formatted and not arrive in that way for a better visualization?

    
asked by 16.01.2018 в 17:50
source

2 answers

0

Decode the json in an object:

$datos=json_decode($_POST['dataProyectos']);

access the values of object $datos

$mensaje="Empresa ".$datos->Paso1->empresa."<br>";
$mensaje.="Etapa ".$datos->Paso2->etapa."<br>";
 /***DEMAS CODIGO***/

EDITO

Mariano is right I did the test and it will not work I recommend you modify the structure of your JSON to make it more manageable example

"{\"Paso1\":{\"empresa\":\"startup\"},\"Paso2\":\"etapa\":\"Tengo una idea\"}}"

This way you can handle it with the initial example

    
answered by 16.01.2018 / 19:09
source
0

If the message is html, add the "pre" labels in front of and behind the body:

$message = "<pre>" . $_POST['dataProyectos'] . "</pre>";
    
answered by 16.01.2018 в 18:11