Reputation: 752
I am having an incredibly hard time with this. I'm trying to post my value's from a form to a php file using ajax jquery. I do find the values in my console but when i execute the ajax method it doesn't post the values.
Jquery code
var formData = [];
function formValidate() {
var error = false;
$(".form .required").each(function(k, v) {
$(v).removeClass("error");
if ($(v).attr("type") === "radio" && $(v).prop("checked")) {
formData[$(v).attr("id")] = $(v).val();
} else if ($(v).val() === "") {
$(v).addClass("error");
//$(v).prop("placeholder”,”Required.”);
error = true;
} else {
formData[$(v).attr("id")] = $(v).val();
}
});
console.log(formData); //all data is successful shown
return error;
}
// send function
function formSend() {
$.ajax({
type: 'POST',
url: "include/mail.php",
data: formData,
dataType: "html",
encode: true,
success: function(response) {
alert(response);
},
error: function() {
$("form").hide();
}
});
event.preventDefault();
}
Html code
<form action="" id="form-3">
<div class="container row">
<div class="col-md-4 col-xs-12">
</div>
<div class="col-md-4 col-xs-12">
<div class="form-group">
<input type="text" class="form-control required" name="naam" placeholder="Naam" id="naam">
</div>
<div class="form-group ">
<input type="text" class="form-control required" name="telnr" placeholder="Telefoon" id="telnr">
</div>
<div class="form-group">
<input type="email" class="form-control required" name="email" placeholder="E-mail" id="email">
</div>
</div>
</div>
</form>
I do find the value's if i console.log(formData) so why won't it post it?
EDIT:
here you can see the images of the console log
When the request is made. The values need to be send to mail.php
[![enter image description here][2]][2]
And here you can see that formData does display if i use console.log
Upvotes: 1
Views: 1460
Reputation: 744
the problem is formData
is a JSONArray - but in the ajax call you need to provide a JSONObject. So initiate formData
as JSONObject in the validation function and then push the key values in it.
Rewrite the formData
initiation like:
var formData = {};
And it should work.
Upvotes: 1
Reputation: 3083
You should pass form data using serilize rather than individual field value. Try below code:
jQuery Code:
var formData = $("form").serialize();
$.ajax( {
type: "POST",
url: "YOUR PHP FILE PATH",
data: formData,
dataType: 'json',
beforeSend: function () {
//do stuff progressing
},
success: function (resp) {
//do stuff after post
},
error: function (e) {
alert('error: ' + JSON . stringify(e));
}
});
PHP Code:
<?php
print_r($_POST); //it will print array with all form input field
?>
Note: Set Form action="javascript:void(0)"
Upvotes: 1