在ajax函数之前没有填充jQuery变量。

时间:2015-07-08 11:46:11

标签: javascript jquery ajax forms click

请看一下我的[小提琴] [1]。

我试图获取包含在给定div中的所选复选框的所有表格。然后这些表将作为变量$ content发送到我的ajax函数,然后发送到我的邮件功能。

然而,当我点击发送按钮时,我收到错误 - 内容未定义。

 jQuery('#search-query-send').click(function(){                     

                jQuery('.selectthis input:checked').each(function() {
                    var content = jQuery(this).parents('div.apartment-entry-container').html();
                    var email = jQuery('#email').val();
                });


                jQuery.ajax({
                    url:"http://www.greenmonkeypublicrelations.com/scpads/wp-admin/admin-ajax.php",
                    type:'POST',
                    data:'action=apartmentsearchemail&email=' + email + '&content=' + content,                                    
                    success:function(result){
                    //got it back, now assign it to its fields.                     
                        alert('Your message has been sent.');
                        console.log(result);             
                    }   
                }); 
            }); 

3 个答案:

答案 0 :(得分:0)

您已将这些声明为.each()回调函数的本地,因此它们不存在于点击回调的范围内。

jQuery('#search-query-send').click(function () {
    var content = '',
        email = '';
    jQuery('.selectthis input:checked').each(function () {
        content = jQuery(this).parents('div.apartment-entry-container').html();
        email = jQuery('#email').val();
    });


    jQuery.ajax({
        url: "http://www.greenmonkeypublicrelations.com/scpads/wp-admin/admin-ajax.php",
        type: 'POST',
        data: 'action=apartmentsearchemail&email=' + email + '&content=' + content,
        success: function (result) {
            //got it back, now assign it to its fields.                     
            alert('Your message has been sent.');
            console.log(result);
        }
    });
});

答案 1 :(得分:0)

这里的变量content是一个局部变量,只包含当前表格的HTML。如果您想将它们一起发送,则必须使用+=附加/加入值:

jQuery('#search-query-send').click(function() {

  var content = '', email = '';

  jQuery('.selectthis input:checked').each(function() {
    content += jQuery(this).parents('div.apartment-entry-container').html();
    var email += jQuery('#email').val();
  });

  jQuery.ajax({
    url: "http://www.greenmonkeypublicrelations.com/scpads/wp-admin/admin-ajax.php",
    type: 'POST',
    data: 'action=apartmentsearchemail&email=' + email + '&content=' + content,
    success: function(result) {
      //got it back, now assign it to its fields.                     
      alert('Your message has been sent.');
      console.log(result);
    }
  });
});

但是,建议不要通过GET方法发送HTML代码。你可以尝试做一个POST吗?

答案 2 :(得分:0)

This solved my problem. Didnt have to use the GET method. Ive stuck with the POST method as I will eventually nee dto record these emails.

wp_mail($to, stripslashes($subject), stripslashes($message), $headers);