I’m a bit of a novice with jQuery and ajax when it comes to sending data in json format to a REST API. I have created a form and the underlying js to process the form fields into the correct json format. However when I try to post the body and the header to the REST API I get the following errors in the console:
OPTIONS https://mywebspace.kintone.com/k/v1/record.json 405 (JSPs only permit GET POST or HEAD)
Failed to load https://mywebspace.kintone.com/k/v1/record.json: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘https://mywebspace.com’ is therefore not allowed access. The response had HTTP status code 405.
Here is my js for the form and ajax:
$(document).ready(function() {
alert(‘jQuery is up and running!’)
$.fn.serializeObject=function()
{
//Array to hold field object data
varobjFieldLabel= {};
//Array to hold body object data that will be sent in a json body,
//this will contain field and value data via nested arrays
varobjBody= {};
//Set the application ID for Kintone json body
objBody[‘app’] =6;
//Serialize form data into an array
varobjArray=this.serializeArray();
//Loop through the form data
$.each(objArray, function() {
//Array to hold value data that will be nested in the field label array
varobjValue= {};
if (objFieldLabel[this.name] !==undefined) {
if (!objFieldLabel[this.name].push) {
objFieldLabel[this.name] = [objFieldLabel[this.name]];
}
objValue[‘value’] =this.value||’’;
objFieldLabel[this.name].push(objValue);
}
else {
objValue[‘value’] =this.value||’’;
objFieldLabel[this.name] =objValue;
}
});
objBody[‘record’] =objFieldLabel;
returnobjBody;
};
$(’#your-form’).on(‘submit’, function(e) {
e.preventDefault();
varjsonRecordToPost=JSON.stringify($(‘form’).serializeObject());
$.ajax({
url:‘https://mywebspace.kintone.com/k/v1/record.json’,
// beforeSend: function(xhr) {
// xhr.setRequestHeader(“X-Cybozu-API-Token”,“supersecretcodestring”),
// xhr.setRequestHeader(“X-HTTP-Method-Override”,“POST”),
// xhr.setRequestHeader(“Content-Type”,“application/json”);
// },
headers : {
‘X-Cybozu-API-Token’:‘supersecretcodestring’,
‘Content-Type’ :‘application/json’,
‘X-HTTP-Method-Override’ :‘POST’
},
contentType :‘application/json’,
type:‘POST’,
datatype:‘json’,
processData:false,
data:jsonRecordToPost,
success:function(data){
console.log(jsonRecordToPost);
$(’#result’).text(jsonRecordToPost);
// console.log(json);
},
error:function(data){
console.log(data);
}
})
.done(function(response){
$(’#result’).text(response.message);
});
});
});