My code:
<script type="text/javascript" src="JavaScript/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function() {
var name1 = $("#eid").val();
var pass1 = $("#p").val();
var datacontent = {
"empName": name1,
"empPassword": pass1
};
alert(JSON.stringify(datacontent));
$.ajax({
type: "POST",
accept: "application/json",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/rest_test1/empLogin.htm",
data: JSON.stringify(datacontent), // Note it is important
success: function(data) {
alert(data.empName + " " + data.empPassword);
}
// error: function(data, status, er) {
// alert("Data: " + data + "Status: " + status + "Error:" + er);
// }
});
});
});
</script>
Controller code:
#Controller
public class EmployeeRestController {
#RequestMapping(value = "/empLogin.htm", method = RequestMethod.POST)
public #ResponseBody EmployeeVo doRegister(#RequestBody EmployeeVo employeeVo){
System.out.println(employeeVo.getEmpName() + " " + employeeVo.getEmpPassword());
return employeeVo;
}
}
When I run this code values are shown in console but get error:
406 (Not Acceptable)
So below code is not working:
success: function(data) {
alert(data.empName + " " + data.empPassword);
}
I used jackson-annotations-2.3.0.jar, jackson-core-2.3.4.jar, jackson-databind-2.3.4.jar Jar files.
HTTP status code 406 means the server cannot respond in the format mandated by the request's accept header. In other words, your web service isn't configured to generate an application/json response.
Try removing the accept: "application/json" from your AJAX request, or add the content type to your response, like so:
#RequestMapping(value="/empLogin.htm", headers="Content-Type=application/json", method=RequestMethod.POST)
Related
I am trying to create a script to post a text message in a chat on Guilded, but so far I get a "POST is not allowed"
Message should be "inPrivate" so a mention of the targeted member is required.
Google sheet test file
my script:
function message () {
var url = "https://www.guilded.gg/api/v1/channels/";
var channelid = "d2ba*****";
var key = "Bearer gapi_*****"; //Q-P API temp-bot
const message = {
content : "It's alive!",
embeds :[{
author:"API",
mentions:"Raven_test",
}],
isPrivate : true,
}
const params = {
method: "POST",
headers: { Authorization: key },
contentType: "application/json",
payload: JSON.stringify(message),
muteHttpExceptions: true,
};
Logger.log(JSON.stringify(params));
const response = UrlFetchApp.fetch(url + channelid + "/messages/", params);
var data = JSON.parse(response);
Logger.log(data);
}
Guilded's API
I don't understand what I'm doing wrong (but I'm a newbie, so it makes sens)
POST is still not working, with the same answer, however, if I use the PUT method, I can update a message if written by the same bot (I just need to add the messageid in the url after /messages/
function postmessage () {
var url = "https://www.guilded.gg/api/v1/channels/";
var channelid = "d2bac803-****-****-****-a609ab9c58c4";
var key = "Bearer gapi_******"; //Q-P API temp-bot
var server = "wlVKV***"
var messageid = "ae6f1693-****-****-****-c9984d4142de";
var author = "****";
const message = {
"type": "default",
"serverId":server,
"channelId":channelid,
"content" : "test #Aaron Raven ",
"mentions":{
"users" : [{"id":author}]
},
"isPrivate":false,
"isSilent":false
};
const params = {
method: "put",
headers: { Authorization: key },
contentType: "application/json",
payload: JSON.stringify(message),
muteHttpExceptions: true,
};
Logger.log(JSON.stringify(params));
// const response = UrlFetchApp.fetch(url + channelid + "/messages/" + messageid, params);
const response = UrlFetchApp.fetch(url + channelid + "/messages/" params);
var data = JSON.parse(response);
Logger.log(response);
Logger.log(data);
Logger.log(params);
}
Another issue (aside POST method) is that "mentions" doesn't work; it appears as basic text, and not as a user tag/link
Kind regards,
I have the HTML file and try to send the request from that page with JavaScript or jQuery, but it doesn't send the "header" to the server and it gives me the error 405. I've read related questions and try out some of them but the error code was the same. I use Fiddler to see the final request and in that there is no header as well as the method change to the OPTION!
some of the codes I used:
$.ajax({
url: "URL",
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer HASHKEY');},
success: function() { alert('Success!'); }
});
or
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "URL", true);
xhttp.setRequestHeader("Authorization", "Bearer HASHKEY");
xhttp.setRequestHeader('Content-Type', 'text/plain');
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.send();
xhttp.onreadystatechange = function () {
var response = xhttp.responseText;
if (xhttp.readyState == 4 && xhttp.readyState == 200) {
var obj = JSON.parse(response);
// handle data as needed...
alert("obj" +obj);
}
};
Totally speaking I'm looking for a piece of code which can call API from the HTML which is content header: authorization.
Cheers
Try this:
$.ajax({
url: "URL",
type: "GET",
headers: {
"Authorization": "Bearer HASHKEY"
},
success: function() { alert('Success!'); }
});
Also, check that your server configuration supports CORS and explicitly allows the Authorization header.
I am new to MVC and I am trying to create an application with Knockout.js to send data back to the server dynamically. I am following an example i found at:
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-2
It works perfectly off the site, but i am trying to send data to multiple models instead just one as in the example
The Knockout code used in the example to send the data back to the server is
var urlPath = window.location.pathname;
var CreateArticleVM = {
Title: ko.observable(),
Excerpts: ko.observable(),
Content: ko.observable(),
Test: ko.observable(),
btnCreateArticle: function() {
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
error: function(err) {
if (err.responseText == "success") {
window.location.href = urlPath + '/';
}
else {
alert(err.responseText);
}
},
complete: function() {}
});
}
};
ko.applyBindings(CreateArticleVM);
How do i modify the above code to be able to accept a FormCollection? Or what is the best solution to my problem?
Thanks
Say your service is expecting more than one argument like following.
[HttpPost]
public String Create(ModelA modela, ModelB modelb)
{
//Server code.
}
In order pass the data for Create method from client side you need to form your postdata as follows.
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: {modela: { "modela data in the expected form" }, modelb : { "modelb data.." } },
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
.
.
.
.
});
I have been working on G drive API and doing upload, download delete and update of files and folders using JavaScript for windows 8 . The two problems which I encountered are;
When I upload a file or folder it gets uploaded with a title "UNTITLED" , can you tell me what I am doing wrong.? my request looks like this;
WinJs.xhr ({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
type: "post",
headers: { "Authorization": "Bearer " + accessToken, },
data: { "mimeType": "application/vnd.google-apps.folder", "title": "sampleFolder2" } }).then
(function (success) {
var response = JSON.parse(success.response);
},
function (error) {
console.log(error);
});
When I download a file I get an encrypted or some unique type of response like if I download an JPEG image I get JFIF in response text. Can you please tell me why ? cant I get the file downloaded to my disk..?
Here is the complete function of insertion of file using media as uploadtype.
function insertFile(accessToken) {
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.viewMode = Windows.Storage.Pickers.PickerViewMode.thumbnail;
openPicker.fileTypeFilter.replaceAll([".png", ".jpg", ".jpeg", ".txt"]);
openPicker.pickSingleFileAsync().then(function (file) {
if (file) {
var tMeta = {
title: file.name,
mimeType: file.contentType,
description: "xyz description."
};
WinJS.xhr({
url: 'https://www.googleapis.com/upload/drive/v2/files?uploadType=media',
type: "post",
headers: {
"Authorization": "Bearer " + accessToken,
'Content-Type': file.contentType,
'Title': file.name
},
body: tMeta,
}).then(function (success) {
var response = JSON.parse(success.response);
var file1 = response;
secondRequest(accessToken, file1 , file);
}, function (error) {
var x = 4;
});
}
});
}
function secondRequest(accessToken, file1,file) {
var x = 2;
var tMeta = {
title: file.name,
mimeType: file1.mimeType,
// description: "xyz description."
};
var URL = 'https://www.googleapis.com/upload/drive/v2/files/' + file1.id + '?uploadType=media'
WinJS.xhr({
url: URL,
type: "put",
headers: {
"Authorization": "Bearer " + accessToken,
'Content-Type': file1.mimeType,
'Title': file.name
},
body: tMeta,
data: MSApp.createFileFromStorageFile(file)
}).then(function (success) {
var secondResponse = JSON.parse(success.response);
var z = 3;
}), function (error) {
var x = 3;
}
}
If you would like to upload metadata with the file, you need to implement the multipart upload. It's explained on https://developers.google.com/drive/manage-uploads#multipart
I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...