2016-11-25 93 views
1

我試圖表現出的警報,但它不是不要工作知道我錯過了什麼,請指出:警報()不工作在PHP,而不致印在控制檯

//my.php 

if(mail($to, $subject, $message, $headers)) { 
    $message = "Mail sent."; 
    echo "<script type='text/javascript'>alert('$message');</script>";   
} 
else { 
    echo json_encode(['success'=>false]); 
} 

上述假設在瀏覽器上顯示警報,但沒有顯示任何內容。但是它被印在控制檯上,誰知道這裏有什麼問題?

UPDATE

//myPhpCall: 

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#myForm").on('submit', function(event) { 
      event.preventDefault(); 
      var formData = $(this).serialize(); 
      $.ajax({ 
       type: 'POST', 
       url: 'sendmail.php', 
       dataType: "json", 
       data: formData, 
       success: function(response) { 
        alert("Mail sent"); // not getting called 

       }, 
       error: function(xhr, status, error) { 
        console.log(xhr); 
       } 
      }); 
     }); 
    }); 
</script> 
+1

這' alert('$ message');'可能是從服務器返回的,但沒有被執行,因爲沒有任何東西觸發它......你是重新加載空洞頁面,還是讓服務器返回就像是對它的調用?我想你可以添加到服務器的'alert()'(用戶端)'服務器正在返回的'$ message'的函數或事件中調用PHP ... –

+0

您是否使用'jQuery'來提交表單? – julekgwa

+0

@julekgwa是的,讓我試試你的方式 –

回答

1

只需將結果返回給jQuery,並從那裏發出警報。在my.php

// if mail was sent 
echo json_encode(["success" => true]); 

然後在您的jQuery在你ajax

var res = $.parseJSON(data); 
if (res.success == true) { 
    alert("Mail sent"); 
}else { 
//code here 
} 

UPDATE

$('#submit-button').on('click', function(e){ 
e.preventDefault(); 
$.post('sendmail.php', $('#myForm').serialize(), function(data){ 
     var res = $.parseJSON(data); 
     if (res.result == true) { 
      alert('Mail sent'); 
     }else if(res.result == false) { 
      alert('Mail not sent'); 
     } 
    }); 
}); 
+0

@julegwa好像我已經嘗試了你的建議,但它沒有被調用,糾正我,如果我錯了。請檢查更新後的問題 –

+0

@remyboys我測試了你的代碼,它在我身邊工作。如果你仍然有問題,你可以在我的答案中使用更新後的代碼。 – julekgwa

0

嘗試以下 -

<?php 
if(mail($to, $subject, $message, $headers)) { $message = "Mail sent."; 
?> 
<script type='text/javascript'>alert(<?php echo $message ?>);</script> 

<?php } else { echo json_encode(['success'=>false]); } 
?>