简体   繁体   English

如何通过ajax从html表单和php页面进行联系

[英]how to make a contact from html form and php page by ajax

I make this form to send data to a php page in another domain but always it results error. 我做这种形式发送数据到另一个域中的php页面,但始终会导致错误。 can someone explain my problem I search in Internet many times but exactly I didnt find my answer here is my code 有人可以解释我在互联网上搜索过很多次的问题,但是我没有找到答案,这是我的代码

html: 的HTML:

<form action="#" id="smail" method="post" class="form">
  <input type="text" name="name" value="Your Name *">
  <input type="text" name="mailadd" value="Your E-mail *">
  <textarea name="message" cols="0" rows="0">Your Message *</textarea>
  <input type="submit" value="send message">
</form> 

js: js:

$('#smail').submit(function(event) {
  event.preventDefault();
  var mail = $("#smail input[name=name]").val();
  var message = $("#smail input[name=mailadd]").val()+' '+$("#smail textarea[name=message]").val();
  $.ajax({
    type: "POST",
    url:"http://cofeebeen.dx.am/email.php",
    crossDomain: true,
    data:{ 
      "mail": mail,
      "message": message, 
    },
    dataType: "text",
    error: function(){
      alert("error")
    }
  }).success(function(result){
      alert(result)
  });
});

php: 的PHP:

<?php
  $subject = $_POST["mail"];
  $msg = $_POST["message"];
  mail("someone@example.com",$subject,$msg);
?>

Your PHP code is not correct, we can get data at your PHP page like below. 您的PHP代码不正确,我们可以在您的PHP页面上获取数据,如下所示。

Correct code: 正确的代码:

$subject = $_POST["mail"];
$msg = $_POST["message"]

Incorrect code: 不正确的代码:

$subject = $_POST["name"];
$msg = $_POST["mailadd"]

I hope it will work now. 我希望它现在可以工作。

Per @mpf82's comment, if this is a cross domain request, that changes things. 根据@ mpf82的评论,如果这是跨域请求,则将更改内容。 However, the AJAX request is currently passing 2 PHP post variables: 但是,AJAX请求当前正在传递2个PHP post变量:

...
data:{ 
  "mail": mail,
  "message": message, 
},
...

And you reference 3: 您参考3:

$_POST['name'];
$_POST['mailadd'];
$_POST['message'];

As @Reghbendra pointed out, you are referencing the incorrect variable names. 正如@Reghbendra指出的,您引用的变量名称不正确。 Plus, since you did the concatenation of mailadd and message in Javascript, you can skip that part in PHP. 另外,由于您是用Javascript完成mailaddmessage的串联, mailadd可以在PHP中跳过该部分。

Therefore, your code would need to reference the two post variables that were passed by their proper indexes. 因此,您的代码将需要引用由它们的正确索引传递的两个post变量。

Result code: 结果代码:

<?php
$subject = $_POST["mail"];
$msg = $_POST["message"];
mail("someone@example.com",$subject,$msg);
?>

You also should consider the headers for the PHP mail function to ensure that it sends properly and is handled correctly. 您还应该考虑PHP邮件功能的标头,以确保其正确发送和正确处理。 See the documentation for the function here . 有关功能的信息,请参见此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM