2013-04-02 128 views
0

我正在使用ajax函数发送数据。在php过程中,我运行phpmailer使用smtp gmail发送电子邮件。一切进展顺利,但有条件让我想让用户等待正在进行的过程。我的代码:jQuery ajax等待php响应过程

LoadingProccess(); 
var FormData = $('#subscribe').serialize(); 
$.ajax({ 
    type: "POST", 
    url: "proses_corporate.php", 
    data: FormData, 
    cache: false, 
    dataType: "json", 
    success: function(data){ 
     var cek = data.result; 
     $.unblockUI(); 
     if(cek=='Success'){ 
     $('#subscribe')[0].reset(); 
     $.blockUI({ 
      message: '<h4>'+data.status+'</h4>', 
      timeout: 8000 , 
      css: { 
       top: ($(window).height() - 100) /2 + 'px', 
       left: ($(window).width() - 650) /2 + 'px', 
       width: '650px' 
     }); 
      setTimeout(function() { 
       window.location.href = 'http://www.domain.com/'; 
      }, 8000); 
    } 
     setTimeout(function() { 
      window.location.href = 'http://www.domain.com/'; 
     }, 8000); 
    } 
    }, 
     error: function() { 
      alert('Error'); 
     } 

}); 

情景:当我提交,申请将被锁定,显示信息,该过程正在进行的用户。对于该PHP需要几秒钟通过smtp gmail处理发送邮件。

在我的PHP回声json_encode给予命令的jquery显示进程已成功的信息。我PHP代码

function smtpmailer($to, $from, $from_name, $subject, $body) { 
    global $error; 
    $mail = new PHPMailer(); // create a new object 
    $mail->IsSMTP(); // enable SMTP 
    $mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only 
    $mail->SMTPAuth = true; // authentication enabled 
    $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail 
    $mail->Host = 'smtp.gmail.com'; 
    $mail->Port = 465; 
    $mail->Username = GUSER; 
    $mail->Password = GPWD;   
    $mail->SetFrom($from, $from_name); 
    $mail->Subject = $subject; 
    $mail->Body = $body; 
    $mail->AddAddress($to); 
    if(!$mail->Send()) { 
     $error = 'Mail error: '.$mail->ErrorInfo; 
     return $error; 
    } else { 
     $error = 'Message sent!'; 
     return $error; 
    } 
} 

使用

smtpmailer('[email protected]','[email protected]','GMAIL','Testing Form GMail','Test...Test...Test...Test...'); 
echo json_encode(array('status' => 'Data has been sent.', 'result' => 'Success')); 

正如上面的代码中,表单将一个成功的过程之后被路由到一个特定的页面。在我的情况下,jQuery如何在翻页之前等待动态php的结果?

你必须使用一个超时:10000对jQuery?它看起来不是动态的,因为时钟是手动设置的。有另一种方法吗?

+0

是否要重定向到Success上的另一个页面,并在出现任何错误时显示错误消息? – Amit

+0

yes ....但在php进程之后 –

+0

如果PHP进程没有返回“成功”,您可以为“if(cek =='Success')”语句添加一个else块并显示错误/重定向到另一个页面 – Amit

回答

0

您在等待响应时会使您的ajax请求超时。例如

$.ajax({ 
    type: "POST", 
    url: "proses_corporate.php", 
    data: FormData, 
    cache: false, 
    timeout: 30000, // 3 second 
    dataType: "json", 
    success: function(res){ }, 
    failed: function(err){ } 
} 
0

的页面,您可以使用beforeSend函数添加蒙版。 和完整功能删除面具。