通过AJAX发送字段表单数组并在Wordpress中的php上获取它

时间:2015-03-24 17:00:15

标签: php ajax wordpress plugins

我在Wordpress上制作插件,向我们的客户发送电子邮件。我遇到了字段数组类型的问题,因为我无法在PHP函数上获得它。我可以获取单个字段,作为主题或消息,但不是电子邮件字段(它是为具有多个电子邮件的客户端动态创建的数组)

这是我的表单代码

echo '<form id="myform" method="post">';

    echo "<ul>";

    echo "<li><strong>¿Cual es el destinatario del email? (pueden ser varios)</strong></li>";

    if( get_field('contactos',$post_id) ): 
        while( has_sub_field('contactos',$post_id) ): 

            echo "<li style='margin-left: 45px; margin-top: 15px;'><input type='checkbox' id='emails[]' value='".get_sub_field('email',$post_id)."'>"
        .get_sub_field('nombre',$post_id)." (".get_sub_field('email',$post_id)." )</li>";

        endwhile;

    endif;  

    echo '<li style="margin-top: 15px;"><strong><label for="subject">Asunto: </label></strong>';
    echo '<input id="subject" maxlength="45" size="30" name="subject"></li>';

    echo "<p>Texto del mensaje</p>";
    echo '<textarea id="cuerpo" class="textarea" name="cuerpo" placeholder="" style="
        width: 600px;
        height: 200px;
    "></textarea><br>';

    echo '<li style="margin-top: 35px;"><input id="send" name="submit" type="submit" value="Enviar eMail" class="button button-primary button-large"></li>';

    echo "</form>";

这里是ajax.js

$( "#myform" ).submit(function( event ) {
            event.preventDefault(); 
            alert( "Handler for .submit() called." );
            $(function() { 
                $('#sendingemails').fadeIn();
                var subject = $("#subject").val();
                var cuerpo = $("#cuerpo").val();
                $.ajax({
                        type: 'POST',
                        url: GestionAjax.ajaxurl,
                        data: { action: 'email', subject : subject, cuerpo : cuerpo, emails :  $('#emails').serialize() },
                        // Mostramos un mensaje con la respuesta de PHP
                        success: function(data) {
                            alert("enviado");
                            $('#sendingemails').fadeOut();
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) { 
                            alert("Status: " + textStatus); alert("Error: " + errorThrown);
                            alert (jsonString);
                    }   
                    })
            });

        });

这里是recive数据的函数:

function AC_ONEmail() {

    $emails = array();

    $emails = $_POST['emails'];
    $message = $_POST['cuerpo'];
    $subject = $_POST['subject'];

    add_action('phpmailer_init','send_smtp_email');

    $headers[] = 'From: '.$current_user->display_name.' '.$current_user->user_email;
    add_filter( 'wp_mail_content_type', 'my_custom_email_content_type' );

    $message .= '<br><br>'.nl2br($current_user->firma);

    foreach ($emails as $email) {
        $result=wp_mail( $email, $subject, $message, $headers);

        if (!$result) {
            global $ts_mail_errors;
            global $phpmailer;
            if (!isset($ts_mail_errors)) $ts_mail_errors = array();
            if (isset($phpmailer)) {
                $ts_mail_errors[] = $phpmailer->ErrorInfo;
                }
        } else { 
                global $wpdb;
                $wpdb->insert( 
                    'wp_comunicaciones', 
                    array( 
                        'post_id' => $idcliente,
                        'asunto' => $datos2,
                        'cuerpo' => $message,
                        'fecha' => date("Ymd"),
                        'responsable' => $current_user->display_name,
                        'email' => $email[0]
                    )
                );

                /*envio del email a una carpeta del servidor
                $mail_string = "From: ".$current_user->user_email."\r\n". "To: ".$value."\r\n"."Subject: ".$_POST['subject']."\r\n"."\r\n".$_POST['cuerpo']."\r\n";
                $stream = imap_open("{smtp.office365.com}Elementos enviados", $current_user->cuenta_usuario, $current_user->passwordSMTP);
                imap_append($stream, "{smtp.office365.com}Elementos enviados", $mail_string, "\\Seen");
                */
                }

    }

    $arr = array( "asunto" => $_POST['subject'], "cuerpo" => $_POST['cuerpo'], "emails" => $_POST['emails']);

    echo json_encode($arr);

    wp_die();
}

正如我所说,我在控制台上调试vars(chrome上的网络选项卡),主题和消息都有值,但不是clientes(数组类型字段)

我在这里看到很多信息,在stackoverflow上,我尝试以不同的方式做,但我花了两天时间,现在我需要你的知识。我该怎么办?

由于

更新解决方案

我采取解决方案

在ajax脚本上,我使用此data: { action: 'email', datos : $('#myform').serialize() }更改数据行,并在重新插入数据的函数中插入parse_str($_POST['datos'], $arraydatos);然后我使用$arraydatos['emails']或我想要的字段获取数据。它工作正常!

1 个答案:

答案 0 :(得分:0)

我采取解决方案来做到这一点

我用这个

更改ajax.js
$( "#myform" ).submit(function( event ) {
            event.preventDefault(); 
            $(function() { 
                $('#sendingemails').fadeIn();
                tinyMCE.triggerSave();
                $.ajax({
                        type: 'POST',
                        url: GestionAjax.ajaxurl,
                        data: { action: 'email', datos :  $('#myform').serialize() },
                        // Mostramos un mensaje con la respuesta de PHP
                        success: function(data) {
                            alert("eMail enviado con éxito");
                            $('#sendingemails').fadeOut();
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) { 
                            alert("Status: " + textStatus); alert("Error: " + errorThrown);
                            alert (jsonString);
                    }   
                    })
            });

        });

以及通过此

更改数据的功能
function AC_ONEmail() {

    $current_user = wp_get_current_user();
    $attachments = array();
    $num_archivos = 0;

    parse_str($_POST['datos'], $arraydatos);

    add_action('phpmailer_init','send_smtp_email');
    add_filter( 'wp_mail_content_type', 'my_custom_email_content_type' );

    $headers[] = 'From: '.$current_user->display_name.' '.$current_user->user_email;

    $archivos = $arraydatos['archivos'];
    foreach ($archivos as $archivo=>$i) {
        array_push($attachments, get_attached_file( $i ));
        $num_archivos++;
    }

    $message = $arraydatos['cuerpo'];

    $message .= '<br><br>'.nl2br($current_user->firma);

    $emails = $arraydatos['emails'];

    foreach ($emails as $email) {
        $result=wp_mail( $email, $arraydatos['subject'], $message, $headers, $attachments);

        if (!$result) {
            global $ts_mail_errors;
            global $phpmailer;
            if (!isset($ts_mail_errors)) $ts_mail_errors = array();
            if (isset($phpmailer)) {
                $ts_mail_errors[] = $phpmailer->ErrorInfo;
                }
        } else { 
                global $wpdb;
                $wpdb->insert( 
                    'wp_comunicaciones', 
                    array( 
                        'post_id' => $arraydatos['post_id'],
                        'asunto' => $arraydatos['subject'],
                        'cuerpo' => $arraydatos['cuerpo'],
                        'fecha' => date("Ymd"),
                        'responsable' => $current_user->display_name,
                        'email' => $email,
                        archivos => $num_archivos
                    )
                );

                /*$mail_string = "From: ".$current_user->user_email."\r\n". "To: ".$value."\r\n"."Subject: ".$_POST['subject']."\r\n"."\r\n".$_POST['cuerpo']."\r\n";
                $stream = imap_open("{smtp.office365.com}Elementos enviados", $current_user->cuenta_usuario, $current_user->passwordSMTP);
                imap_append($stream, "{smtp.office365.com}Elementos enviados", $mail_string, "\\Seen");*/
                }

    }

    echo $result;

    wp_die();
}

我解释了变化。我将所有表格序列化发送到回收数据的php函数。在PHP函数上,我读取数据并将其解析为数组parse_str($_POST['datos'], $arraydatos);

然后我可以使用$arraydatos['form_field']获取所有数据,并使用它,包括表单数组字段。

对于内容我使用wp_editor函数。为了获得它的PHP函数我包含在ajax tinyMCE.triggerSave()上。没有它,'cuerpo'字段是空的

由于