mmm2893 mmm2893 - 5 months ago 13
JSON Question

Trying to Convert HTML form into JSON but returning empty

I've been trying to convert an HTML form into Json. When I submit the form my alert is just returning an empty array. Any help is greatly appreciated!

Here is the form

<form action="" method="post" name="myForm">
Code (xxxx-xxx):<input type="text" name="drugcode" /> <br/>
<p><input type="submit" onClick='submitform()' /></p>
</form>


And here is the javascript

<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<script language ="javascript" type = "text/javascript" >

function submitform() {

var formData = JSON.stringify($("form[name*='myForm']").serializeArray());
alert(formData);

$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json",
processData: false
});
}

</script>


All that this is returning is:

[]

EDIT:
It now returns:

[{"name":"code","value":"1234"},{"name":"blah","value":"4321"}]

how would I would I have it return:
{"code":"1234","value":"4321"}

Answer

$("#myForm") is not going to match the form for you. # specifies an id. You need to match on the name:

$( "form[name='myForm']" )...