0

I've been stuck posting JSON data using AJAX to my web server. I've looked at similar topics and tried the solutions, but nothing worked so far. How to send a JSON object using html form data

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $("#myForm").submit(function() {
//document.writeln("hello");
    var formData = JSON.stringify($("#myForm").serializeArray());
    //$('#result').text(JSON.stringify($('form').serializeObject()));
    $.ajax({
      type: 'POST',
      url: "http://localhost:8080/student-web/students/create",
      data: formData,
      success: function(){},
      dataType: 'json',
      contentType : 'application/json',
      processData: false
   `    });
   });
});

</script>
</head>

<body>
<h2>Form</h2>
<form  method="post" name="myForm">
Username:<input type="text" name="username" maxlength="12" size="12"/> <br/>
password:<input type="text" name="password" maxlength="36" size="12"/> <br/>

<p><button name="submit" onclick="submitform()">SUBMIT</button></p>
</form>

The AJAX is not executed, but I can't figure out why. I'm working with a RESTful web service and when I curl the post, it works:

curl -k -v -H "Content-Type: application/json" -X PUT -T "test" http://localhost:8080/student-web/students/create

In the test document is:

{"username":"hi","password":"bye"}    

The RESTful web service itself:

@RequestMapping(value = "/students/create", method = RequestMethod.POST)
@ResponseBody
public void insertStudent(@RequestBody Student student) {
    studentService.insertStudent(student);
}

I've also created a applicationContext.xml which allows .jsp pages and json:

 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/pages/" />
  <property name="suffix" value=".jsp" />
 </bean>
 <mvc:annotation-driven/>     

Anyone knows how to solve this? Thanks in advance.

Community
  • 1
  • 1
user3706583
  • 3
  • 1
  • 2

1 Answers1

0

I have created a Fiddle using your code here the ajax is working fine see here

http://jsfiddle.net/jF3eD/1/

$("#myForm").submit(function() { 
var formData = JSON.stringify($("#myForm").serializeArray());

$.ajax({     
  url: "/student-web/students/create",
  type: "POST",
  data: formData,
  success: function(){},
  dataType: 'json',
  contentType : 'application/json',
  processData: false
   });
});

If this doesnt soleve your problem provide more info regarding your problem.

Madhu
  • 2,416
  • 3
  • 15
  • 33