mmm2893
mmm2893

Reputation: 27

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"}

Upvotes: 1

Views: 46

Answers (2)

bhansa
bhansa

Reputation: 7504

You can also use simple javascript and select the form using

document.querySelector("form[name='myForm']")

or

document.forms[0]

Upvotes: 0

Robert Moskal
Robert Moskal

Reputation: 22553

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

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

Upvotes: 2

Related Questions