0

I make this form to send data to a php page in another domain but always it results error. can someone explain my problem I search in Internet many times but exactly I didnt find my answer here is my code

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:

$('#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
  $subject = $_POST["mail"];
  $msg = $_POST["message"];
  mail("someone@example.com",$subject,$msg);
?>
  • 3
    Possible duplicate of [Cross domain ajax request](http://stackoverflow.com/questions/15477527/cross-domain-ajax-request) – Mike Scotty Jun 15 '16 at 11:54

2 Answers2

0

Your PHP code is not correct, we can get data at your PHP page like below.

Correct code:

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

Incorrect code:

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

I hope it will work now.

Raghbendra Nayak
  • 1,606
  • 3
  • 22
  • 47
  • Also please return some result from PHP page like echo the email result or echo1 for success..but we must return something to ajax call. – Raghbendra Nayak Jun 15 '16 at 12:20
0

Per @mpf82's comment, if this is a cross domain request, that changes things. However, the AJAX request is currently passing 2 PHP post variables:

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

And you reference 3:

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

As @Reghbendra pointed out, you are referencing the incorrect variable names. Plus, since you did the concatenation of mailadd and message in Javascript, you can skip that part in PHP.

Therefore, your code would need to reference the two post variables that were passed by their proper indexes.

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. See the documentation for the function here.

kchason
  • 2,836
  • 19
  • 25