I am trying to submit my form using jQuery ajax, but my data isn’t posting to PHP it returns empty array nothing in $_POST
array.
This is my code – here is my form:
<form action = "/webdevelopmentpakistan/send_mail.php" method = "post" class = "myForm" >
<div class="row">
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" id="fname" type="text" required name= "full_name" placeholder="Full Name"
/>
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" type="tel" required name = "phone" placeholder="+92" id="phone" onkeypress="return isNumberKey(event)" />
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="form-control" type="email" required name = "email" id="email" placeholder="Email"/>
</div>
</div>
<div class="col-md-3 col-sm-12">
<div class="form-group">
<input class="btn popup" type="submit" name = "submit" value="CONTACT OUR CONSULTANT"/>
</div>
</div>
</div>
</form>
its an ajax part:
$('form').on('submit', function (e) {
e.preventDefault();
var url = $(this).attr("action");
var form_data = $(this).serialize();
$.ajax({
type: 'POST',
url: url,
data: $('.myForm').serialize() ,
dataType : 'JSON',
//contentType: "application/x-www-form-urlencoded",
success: function (data) { // here I'm adding data as a parameter which stores the response
console.log(data); // instead of alert I'm changing this to console.log which logs all the response in console.
},
error:function(xhr, textStatus, thrownError, data)
{
console.log("Error: " + thrownError);
console.log("Error: " + textStatus);
}
});
// var popup = document.getElementById("myPopup");
// popup.classList.toggle("show");
console.log(form_data);
});
PHP CODE using at other page:
if(isset($_POST)) {
echo json_encode($_POST);
}
and this is my serialize array which I am getting on submission of form but it isn’t getting passed to php
full_name=talha&phone=012345678&email=admin%40gmail.com
2
Answers
The form action needs to be either absolute url i.e.
https://somewebsite.com
or a relative url on you site so ideally it should be/some-url.php
. Read about form action hereSo your form opening tag should be,
So in your javascript code when you do
I also believe that in your ajax call, the
type
needs to bemethod
, so,welcome to stackoverflow, here are the changes, hope it will works
this should print array of post parameters in your console, however you will get an array in php.