I want to POST and upload image via AJAX with Google reCaptcha v2 validation. but I am facing an issue that I am not not able to send image with caption text with google recaptcha token in Ajax. I coded two function as I know but both was not working. The function I made is the code snippet.
Please help me how I send Image with text in Ajax with reCaptcha token in PHP / jQuery/ AJAX.
$(document).ready(function() {
$("form#addbanner").unbind("submit").bind("submit", function(e) {
//debugger;
e.preventDefault();
grecaptcha.ready(function() {
grecaptcha.execute('MY_RECAPTCHA_CODE', {
action: 'add_web_banner'
}).then(function(token) {
/*let formData = {
imagehere : $('input[name="imagehere"]').val(),
bannertitle : $('input[name="bannertitle"]').val(),
action : 'add_web_banner',
type: 'add_web_banner'
};*/ //not working
/*let formData = {
var formData = new FormData($("form#addWeb-Banner")[0]);
formData.append('token': token);
};*/ //not working
//*POST Image sent in (binary way), I dont want to use JSON in types*//
$.ajax({
type: 'POST',
data: formData,
cache: false,
success: function(response) {
hide_loader();
if (response.status == "success") {
$("form#addWeb-Banner")[0].reset();
alert("Great");
} else {
alert("Ops!");
}
},
});
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="bs-example form-horizontal AddWebBanner" id="addbanner" enctype="multipart/form-data" method="POST">
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Upload Image</label>
<div class="col-lg-8">
<input type="file" class="form-control" title="Upload Photo" id="BannerImage" name="imagehere" accept="image/png,image/jpg,image/jpeg" />
</div>
</div>
<div class="form-group col-sm-6">
<label class="col-lg-4 control-label">Caption of Banner</label>
<div class="col-lg-8">
<input type="text" class="form-control" title="Caption of Banner" name="bannertitle" />
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-lg-12">
<button type="submit" name="submit" class="btn btn-sm btn-default pull-right" id="addBannerBtn">POST</button>
</div>
</div>
</form>
2
Answers
thank for @AlwaysHelping but there was one mistake but I has been fix that..below are the correct answer for future user troubles.. I not mentioned
processData: false, contentType: false,
in ajax.. so the final code will be..peace :)
Change your HTML and formData to the following
Give an id selector your caption banner.
Store using the formData like this and then sent formData via
ajax
You can also use jQuery .serialize method to send data to your backend via ajax