Reputation: 12487
I'm trying to return some JSON from an AJAX call and put it into the html body but I'm struggling with the below code. Can anyone tell me where I am going wrong please?
$("button").click(function() {
$.ajax({
url: 'http://jsonplaceholder.typicode.com/todos/1',
type: "POST",
dataType: 'json',
data: ({
type: 'main'
}),
success: function(result) {
$("#result").html(result);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<button id='buttonJSONP'>Echo JSONP</button>
<div id='result'></div>
Upvotes: 0
Views: 528
Reputation: 82
In the example above you're trying to post data into a Get url.
if you want to return json response from this url you must use GET instead of POST, your code should look like:
$("button").click(function() {
$.ajax({
url: 'http://jsonplaceholder.typicode.com/todos/1',
success: function(result) {
console.log(result);
$("#result").html(result.key);
}
});
});
Upvotes: 0
Reputation: 5962
There are some issues in your code -
as this is a post request you need to change your input as below also remove (
and )
data: {
"type": "main"
}
the API URL is also not correct for POST request, you will get 404 error even if the input is correct. The correct URL for POST will be as below -
url: 'http://jsonplaceholder.typicode.com/todos/'
Reference : Fake JSON api documentation
So your complete code should be like below -
$("button").click(function() {
$.ajax({
url: 'http://jsonplaceholder.typicode.com/todos/',
type: "POST",
dataType: 'json',
data:{
"type": "main"
},
success: function(result) {
$("#result").html(Object.values(result).join("-"));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<button id='buttonJSONP'>Echo JSONP</button>
<div id='result'></div>
The response status will be HTTP 201.
Upvotes: 0
Reputation: 36311
You need to make the request using a get
, otherwise you need to look into your api for making post
requests.
If it is a post
, data doesn't look like this ({})
. Remove the parentheses and just use braces {}
.
Using a get
you need to move your data
object into the url as well, because get
requests don't have a body.
$("button").click(function() {
$.ajax({
url: 'http://jsonplaceholder.typicode.com/todos/1?type=main',
type: "GET",
dataType: 'json',
success: function(result) {
$("#result").html(Object.values(result).join(','));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<button id='buttonJSONP'>Echo JSONP</button>
<div id='result'></div>
Upvotes: 1