Tarek Salah uddin Mahmud Tarek Salah uddin Mahmud - 2 months ago 7
Ajax Question

API does not get any post data from ajax call

I am trying to send data in ajax post call. but this doesnot sent any data.

My html form is

<form>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="firstname">Firstname</label>
<input id="firstname" type="text" class="form-control" id="firstname">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="lastname">Lastname</label>
<input id="lastname" type="text" class="form-control" id="lastname">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="email">Email</label>
<input id="email" type="text" class="form-control" id="email">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="subject">Subject</label>
<input id="subject" type="text" class="form-control" id="subject">
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label for="message">Message</label>
<textarea id="message" class="form-control"></textarea>
</div>
</div>

<div class="col-sm-12 text-center">
<a type="submit" class="btn btn-template-main" onclick="sendMail()"><i class="fa fa-envelope-o"></i> Send message</a><span id="sentMessage" style="color:green"></span>

</div>
</div>
<!-- /.row -->
</form>


My script is

function sendMail(){
var name = document.getElementById ("firstname").value + " " + document.getElementById ("lastname").value;
var subject = document.getElementById ("subject").value;
var email = document.getElementById ("email").value;
var message = document.getElementById ("message").value;
var body = "<h3>Message from "+ name +"</h3>"+
"<h4>Email: "+ email +"</h4>"+
"<p><strong>Body : </strong> "+ message +"</p>";
var email= 'to=tsmrafee@gmail.com&subject=' + subject + '&body=' + body;
console.log("done");
$.ajax({
url: 'http://trimarkworld.com/email.php',
method: 'POST',
data: {
email: email
},
success: function(result){
console.log("done");
$("#sentMessage").html("Email has been Sent");
}
});

}


my php code is

if(isset($_POST['email'])){
echo json_decode($_POST['email']);
}


This does not print anything..I think there is a problem in the ajax call.please help..

Answer

When you send data with $.ajax, it's not sent as JSON, it's sent in application/x-www-form-urlencode format. So there's no need to call json_decode(). Just use:

echo $_POST['email'];
Comments