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" method="post">
<div >
<div >Find companies where...</div>
<div >
<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 >contains...</div>
<div >
<input type="text" ID="tbTerm" required />
</div>
<div >
<input type="submit" ID="btnSearch" 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?
CodePudding user response:
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.
CodePudding user response:
<form id="myform" onsubmit='return onSubmit(this)'>...</form>
function onSubmit(form){
var data = JSON.stringify( $(form).serializeArray() );
alert( data );
return false; //to test : prevent submiting
}