2017-01-03 82 views
0

我收到下面的示例表单,其中beforeSend函数显示正在发送的消息,一旦发送了其他函数,则称为.done(function (data),显示消息已发送的消息。所有我想要做的就是使用其中不发送该邮件的另一个功能,显示消息“的错误,则不会发送消息”未发送电子邮件时显示错误

var form = $('#main-contact-form'); 
form.submit(function (event) { 
    $.ajax({ 
     type: 'POST', 
     url: '../sendemail.php', 
     data: { 
      Name: name, 
      Subject: $form.find("input[name='subject']").val(), 
      Email: email, 
      message: $form.find("textarea[name=message]").val(), 
     }, 
     beforeSend: function() { 
      // message is sending... 
     }     
    }) //end ajax 
    .done(function (data) { 
     // message sent! 
}); 
});//end contact form 
+0

尝试发送电子邮件之前提高的标志(假)和如果邮件发送成功,并且检查标志已完成,对于相应的消息,则提升标志(True) – Vaibhav

+0

这不是短信它是电子邮件 – csandreas1

回答

1
  1. 您可以使用失效API,如下所示处理错误。
  2. 另外,在$ .ajax({constObj})中,您可以使用apis来处理相同的成功和错误。

参见 here for more info

//1. 

$.ajax({ 
      type: 'POST', 
      url: '../sendemail.php', 
      data: { 
       Name: name, 
       Subject: $form.find("input[name='subject']").val(), 
       Email: email, 
       message: $form.find("textarea[name=message]").val(), 
      }, 
      beforeSend: function() { 
      // message is sending... 
      }     
     }) //end ajax 

     .done(function (data) { 
     // message sent! 

     }) 
     .fail(function(){ 
      //handle error here 
     }); 

// 2。

constObj.success(function(data){ 
}); 

constObj.error(function(error){ 
}); 
+0

当我添加失败功能时,我的整个联系表单不起作用我是否需要包含任何库? – csandreas1

+0

实际上我得到一个错误 – csandreas1

+0

添加fail()函数时,你得到了什么错误。无论如何使用方法2是更优选的。 –

1

代替.done使用AJAX选项successerror。发送电子邮件失败时在服务器上发生错误。

$.ajax({ 
    success: function() { 
     // message sent! 
    }, 
    error: function() { 
     // message sent failed! 
    } 
}); 

在服务器端:

if ($this->sendMessage()) { 
    echo "ok"; 
} else { 
    throw new Exception('Email failed to send.', 500); 
} 

如果用户实际收到的电子邮件(我想有一些复杂的方式来弄明白)你不能告诉。

0

您使用done(),它是在SUCCESSFUL ajax请求(通常返回HTTP 200)后执行的。如果您阅读http://api.jquery.com/jquery.ajax/,则会出现fail(),这是在FAILED ajax请求后执行的。

它也取决于sendemail.php的输出。如果你的PHP返回比HTTP 200其他错误时,你可以利用失败()承诺的方法,例如...

$.ajax({ 
    beforeSend: function() { 
     $('msg').text('Sending email...'); 
    } 
}).done(function() { 
    $('#msg').text('Success!'); 
}).fail(function() { 
    $('#msg').text('Failed!'); 
}); 

但是,如果你的PHP也返回HTTP 200错误时,你可以这样做的下面...

PHP:

$response = array(
    'status' => null, 
    'error' => null 
); 

if ($mailer->send()) { 
    $response['status'] = true; 
} else { 
    $response['status'] = false; 
    $response['error'] = 'Unable to send email'; 
} 

的jQuery:

$.ajax({ 
    beforeSend: function() { 
     $('msg').text('Sending email...'); 
    } 
}).done(function(data) { 
    if (data.status === true) { 
     $('#msg').text('Success!'); 
    } else { 
     $('#msg').text('Failed: ' + data.error); 
    } 
}); 
+0

我认为你的jQuery代码是错误的,我尝试你的代码,我得到错误,但电子邮件发送。并且beforeSend函数永远加载 – csandreas1

+0

这不是一个完整的jQuery代码,只是一个例子,如何使用done()和fail()promise方法 –

相关问题