unsupported_grant_type in Web Api 2 - ajax

i am beginner in Web Api and implementing authorization and authentication but getting some error as i mentioned below:
I am getting this error while getting token from webApi
{"readyState":4,"responseText":"{\"error\":\"unsupported_grant_type\"}","responseJSON":{"error":"unsupported_grant_type"},"status":400,"statusText":"Bad Request"}
This is my jQuery code to make request for token
$(document).ready(function () {
$("#login").click(function () {
debugger;
var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
console.log(details);
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: details,
url: "http://localhost:59926/token",
success: function (data) { console.log(JSON.stringify(data)); },
error: function (data) { console.log(JSON.stringify(data)); }
});
});

Your data should be like query string, not JSON object. And you should encode params if need
data: 'username=' + encodeURIComponent(user.username) + '&password=' + encodeURIComponent(user.password) + '&grant_type=password'

contentType is wrong. It should be application/json
$(document).ready(function () {
$("#login").click(function () {
debugger;
var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
console.log(details);
$.ajax({
type: "POST",
contentType: "application/json",
data: details,
url: "http://localhost:59926/token",
success: function (data) { console.log(JSON.stringify(data)); },
error: function (data) { console.log(JSON.stringify(data)); }
});
});

Related

Syntax Error JSON file read with AJAX

I am getting a syntax error for the square bracket '[' from my JSON file. Given below is the JSON.
[
{
"Product Name":"CPE 10281",
"Application":"Tyres",
"Weight":150,
"Cost to Produce":5000,
"Grade":"A",
"Cost to Sell":40000,
"Strength":100
},
{
"Product Name":"CPE 10282",
"Application":"computers",
"Weight":250,
"Cost to Produce":4000,
"Grade":"H",
"Cost to Sell":25000,
"Strength":90
}
]
I am trying to use AJAX to read my JSON file.
$.ajax({
url: "dataProductJSON.json",
dataType: 'json',
mimeType: "application/json",
success: function (data) {
var item = [];
$.each(data, function (key, val) {
item.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'interest-list',
html: item.join('')
}).appendTo('body');
},
});
I am running my html from Eclipse with Apache Geronimo as the server.
Please Help.
You are missing a { in the below line
success: function (data)
Make it
success: function (data) {
Edit
You are having parsing the data incorrectly , do it as below
$.ajax({
url: "test.html",
dataType: 'json',
mimeType: "application/json",
success: function (data) {
var item = [];
$.each(data, function (key, val){
$.each(val, function (innerKey, innerValue){
item.push('<li id="' + innerKey + '">' + innerValue + '</li>');
});
});
$('<ul/>', {
'class': 'interest-list',
html: item.join('')
}).appendTo('body');
},
});
You need to use 2 loop , one for the array and the other to loop through the object property
I tried things and it is working fine

Error In Ajax Call In html

If I Run The Following Code It's Directly Go To Error:Ajax Failed And Error Show on Fire Bug [Reference Error: Ajax Failed is not defined"].
Plz Tell Where I Make Mistake....?
Its My base 64 Encode Value For Name,Email,Gender,Password
var encodeRname = Base64.encode(name);
var encodeRemail = Base64.encode(email);
var encodeRgender = Base64.encode(lookingfor);
var encodeRpwd = Base64.encode(Pword);
var test = '.1!qkr*';
var decodertr = Base64.decode(test);
IT's My AJAX Call For Post
$.ajax({
//https://www.xxxxxxxxx.com/yyyyyyyyy/zzzzzzzzzzzz.svc/InsertRegistrationDetailsoverHTTPS?AuthToken={AUTHTOKEN}&RegName={REGNAME}&selGender={SELGENDER}&UserName={USERNAME}&UserPass={USERPASS}
url: "https://www.XXXXXXX/YYYYYY/ZZZZZZZZ.svc /InsertRegistrationDetailsoverHTTPS?AuthToken=" + decodertr + "&RegName=" + encodeRname + "&selGender=" + encodeRgender + "&UserName=" + encodeRemail + "&UserPass=" + encodeRpwd,
type: "POST",
contentType: "application/javascript",
dataType: "jsonp",
success: function (msg) {
},
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("success");
}
function AjaxFailed(result) {
alert('Error is : ' + result.status + ' ' + result.statusText);
}
Your error handling function must be defined like the following:
$.ajax({
//https://www.xxxxxxxxx.com/yyyyyyyyy/zzzzzzzzzzzz.svc/InsertRegistrationDetailsoverHTTPS?AuthToken={AUTHTOKEN}&RegName={REGNAME}&selGender={SELGENDER}&UserName={USERNAME}&UserPass={USERPASS}
url: "https://www.XXXXXXX/YYYYYY/ZZZZZZZZ.svc /InsertRegistrationDetailsoverHTTPS?AuthToken=" + decodertr + "&RegName=" + encodeRname + "&selGender=" + encodeRgender + "&UserName=" + encodeRemail + "&UserPass=" + encodeRpwd,
type: "POST",
contentType: "application/javascript",
dataType: "jsonp",
success: function (msg) {
},
error: function (error) {
// your error handling
}
});

Force.com : Rest API Bad Request in Query Like

I got 'bad request" message on the below Rest API Ajax call, When I tested on Developer console it return data successfully.
var _url = auth.get("instance_url") +
"/services/data/v28.0/query/?q=SELECT Id, Name FROM Account WHERE Website LIKE '%gmail.com%' ";
$.ajax({
url: _url,
cache: false,
async: false,
type: 'GET',
contentType: 'application/json',
headers: {
'Authorization': 'OAuth ' + auth.getAccessToken()
},
success: function (data) {
console.log("accounts: " + JSON.stringify(data));
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + +errorThrown);
}
});
You need to URLEncode the query parameter, spaces are not valid in a query string, e.g.
var _url = auth.get("instance_url") + "/services/data/v28.0/query?q=" + encodeURIComponent("select id,name from account");

ajax jquery pass null value

I get null values in the controller when I process the request using jquery ajax
Controller
[HttpPost]
public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid)
{
var replacetext=string.Empty;
if (answers.Length>0)
replacetext = answers.Replace("\n", ",");
_service.UpdateAnswers(eventid, replacetext, controlid);
return PartialView("CustomizedQuestions");
}
Jquery - Ajax Code
var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }";
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/html; charset=utf-8',
context: $(this),
// data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}",
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
Your contentType is wrong. Why did you set it to application/html when you pass JSON? Try like this:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
contentType: 'application/json; charset=utf-8',
context: $(this),
data: JSON.stringify(test),
success: function (result) {
$(this).dialog("close");
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});
or using application/x-www-form-urlencoded which is the default:
var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid };
$.ajax({
url: '#Url.Action("UpdateAnswers")',
type: 'POST',
dataType: 'html',
context: $(this),
data: test,
success: function (result) {
$(this).dialog('close');
},
error: function () {
//xhr, ajaxOptions, thrownError
alert('there was a problem saving the new answers, please try again');
}
});

Ajax Json multiple parameters

This code below sitting on a ASP.Net application on the Site.Mater....
I need to pass another two parameters from the default.aspx page, one asp:label and one asp:textbox
What is the easiest way to do that?
Thanks
<script type="text/javascript">
$(function () {
$(".tb").autocomplete({
source: function (request, response) {
$.ajax({
url: "TestWebService.asmx/FetchList",
data: "{ 'testName': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.Name
}
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
});
In your jQuery autocomplete, You need to change your data parameter to this:
data: "{ 'testName': '" + request.term + "' ,lbl: '" + $(".lblClass").text() + "' ,txt: '" + $(".txtClass").val() + "'}"
And then change your service method like this:
[WebMethod]
public List<string> FetchList(string testName, string lbl, string txt)
{
//...
}
Note:
.lblClass and .txtClass are classes for ASP:Lable and ASP:TextBox respectively.

Resources