Skip to content

Instantly share code, notes, and snippets.

@Dinamiko
Last active October 24, 2015 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dinamiko/becf280ceeb072c86784 to your computer and use it in GitHub Desktop.
Save Dinamiko/becf280ceeb072c86784 to your computer and use it in GitHub Desktop.
<?php
/**
* crea registro con datos desde el formulario
*/
function encuesta_ajax() {
// verifica nonce
if ( ! isset( $_POST['encuesta_nonce_field'] ) || ! wp_verify_nonce( $_POST['encuesta_nonce_field'], 'encuesta_action' ) ) {
print 'Lo siento, no verifica.';
exit;
} else {
// comprobamos que existen
if( isset( $_POST['encuesta_radiochoices'] ) && isset( $_POST['encuesta_email'] ) ) {
$respuesta_length = strlen( $_POST['encuesta_radiochoices'] );
$email_length = strlen( $_POST['encuesta_email'] );
$valid_email = is_email( $_POST['encuesta_email'] );
// valida el máximo de carácteres permitido en cada string y si el email es válido
if( $respuesta_length <= 30 && $email_length <= 100 && $valid_email ) {
// saneamos
$encuesta_radiochoices = sanitize_text_field( $_POST['encuesta_radiochoices'] );
$encuesta_email = sanitize_email( $_POST['encuesta_email'] );
global $wpdb;
$table_name = $wpdb->prefix . "encuesta";
// insertamos
$inserted = $wpdb->insert (
$table_name,
array(
'time' => date( "Y-m-d h:i:s", time() ),
'respuesta' => $encuesta_radiochoices,
'email' => $encuesta_email
),
array(
'%s',
'%s',
'%s'
)
);
// SI se ha creado, mostramos mensaje OK
if( $inserted ) {
$result['type'] = 'success';
//$result['msg'] = 'ID: ' + $wpdb->insert_id;
$result['msg'] = 'Gracias por participar!';
$result = json_encode( $result );
echo $result;
wp_die();
// NO se ha creado, mostramos error en #encuesta-error
} else {
$result['type'] = 'error';
$result['msg'] = 'Error al crear el registro en la base de datos';
$result = json_encode( $result );
echo $result;
wp_die();
}
} else {
$result['type'] = 'error';
$result['msg'] = 'Error al enviar formulario';
$result = json_encode( $result );
echo $result;
wp_die();
}
}
}
}
add_action('wp_ajax_encuesta_ajax', 'encuesta_ajax' );
add_action('wp_ajax_nopriv_encuesta_ajax', 'encuesta_ajax' );
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment