I'm trying to use AJAX to do a POST request via API. For some reason I run into this error: "error occurred while parsing request parameters".
From my understanding, this error occured because of the json parsing when I pass the url attribute into the POST request.
I've read various stackoverflow post around the internet, and seems like using the following should work:
data: { todo: { user_id: userId, body: todoBody } },
datatype : 'json',
I've also tried using this as well and it doesn't work
data: { "todo": { "user_id": userId, "body": todoBody } },
datatype : 'json',
I hope someone can help guide me to the right direction :)
The following is the full code:
index.html.erb
<div class='new-todo'>
<%= form_for todo, remote: true do |f| %>
<div class="form-group">
<%= f.label :body, 'Todo Item' %>
<%= f.text_area :body, rows: 4, class: 'form-control', placeholder: "Enter todo item" %>
</div>
<div class="form-group">
<%= f.submit "Create", class: 'btn btn-success', data: { user_id: current_user.id, user_token: current_user.auth_token} %>
</div>
<% end %>
</div>
Api.js
var superlist = {};
superlist.setupDeleteHandlers = function() {
$(document).ready(function(){
$('.new-todo').submit(function(event) {
var userId = $('.btn-success').attr("data-user-id");
var userToken = $('.btn-success').attr("data-user-token");
var todoBody = $('#todo_body').val();
var data = {"todo": {"user_id": userId, "body":todoBody}};
console.log("test", userId, userToken, todoBody, data);
$.ajax({
type : "POST",
url : "/api/users/"+userId+"/todos",
data: { "todo": { "user_id": userId, "body": todoBody } },
datatype : 'json',
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", userToken);
},
success : function() {
alert('Item successfully created!');
},
error : function(error) {
}
});
});
});
};
{ "todo": { "user_id": userId, "body": todoBody } }in ajax request data just usedatavariable.