I am building a search form, and I want to use JSON formatting of the search fields to call a generic web handler using AJAX. My current challenge is this - I am using the following form code:
<form id="frmSearch" class="was-validated" method="post">
<div class="row mb-4">
<div class="col-lg-2 offset-lg-1 text-end">Find companies where...</div>
<div class="col-lg-2 text-start">
<select ID="ddlType" Class="form-control rounded" required>
<option value="" selected>Search by...</option>
<option value="company_name">Company Name</option>
<option value="city">City</option>
<option value="federal_ein">EIN</option>
<option value="state">State</option>
</select>
</div>
<div class="col-lg-1 text-center">contains...</div>
<div class="col-lg-4 d-flex">
<input type="text" ID="tbTerm" class="form-control rounded text-black" required />
</div>
<div class="col-lg-1 mx-auto">
<input type="submit" ID="btnSearch" class="btn-success btn text-white" text="search" />
</div>
</div>
</form>
Then, using an example I found here on SO, I am using jQuery to format the form fields to JSON, like so:
$(function () {
$('#frmSearch').submit(function () {
alert('got here');
var txt = JSON.stringify($('#frmSearch').serializeObject());
alert(txt)
});
})
The problem is, the alert triggers, so I know the code is executing, except the Stringify fails silently, and the second alert never triggers. I don't get any errors in the console. Any help here as to why this is happening?
I've never used jquery, nevertheless googling and with personal knowledge i came up with this.
$(function () {
$('#frmSearch').submit(function (event) {
event.preventDefault();
object= {}
formData = new FormData(event.target);
formData.forEach((value, key) => object[key] = value);
alert('got here');
var txt = JSON.stringify(object);
alert(txt)
})
});
I hope i have been able to help you! Regards.