sidds224
sidds224

Reputation: 167

How do I post Json data to a URL using AJAX?

<script>
$.ajax({
    type: 'POST',
    url: '/view',
    data:'{"S":"Sam"}', 
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function(data) { alert('data: ' + data); }


});
</script>

When this script gets loaded I get a (400 Bad request). Since the data is starightforward, I need to know if there is anyway I can directly make this request to a URL, or what would be the easiest way to map it to my Spring controller so that I can read that data from the External URL?

Thanks

Upvotes: 0

Views: 59

Answers (2)

Vigneshwaran
Vigneshwaran

Reputation: 397

<script>
$.ajax({
  type: 'POST',
  url: '/view',
  data: JSON.stringify({"S":"Sam"}),
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});
</script>

Upvotes: 0

Vigneshwaran
Vigneshwaran

Reputation: 397

Can you try this way if not preferred direct way, BTW, i have not tested this code...

var myData = { name: value };
var request = $.ajax({
type: 'POST',
url: '/view',
data: myData, 
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false   
});

request.done(function(data){
   alert(data);
});

Upvotes: 1

Related Questions