Force.com : Rest API Bad Request in Query Like - apex-code

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");

Related

How to send success or failure status to AJAX calls from Asp.Net Web API

I am working on an asp.net C# Web API project. I am posting data from a client using jQuery AJAX. The code is given below. I have tried two types of AJAX calls as shown below. Whether the API succeeds or not, the code under either success or error is never reached in the AJAX.
Asp.Net Web API Code:
[HttpPost]
[Route("SendCustomerDetails")]
public async Task<IHttpActionResult> SendCustomerDetails([FromBody] String jsonData)
{
//Code to process json
//...
//...
resp = await client.PostAsJsonAsync("customer/newcustomer", jObject);
if (resp.IsSuccessStatusCode)
{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
else{
//log resp
return Created(Request.RequestUri.ToString(), resp.StatusCode);
}
}
Jquery AJAX code1:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json"
}).done(function (data) {
alert("Success: " + data);
$('#value1').text(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
alert("failure: " + jqXHR.responseText || textStatus);
$('#value1').text(jqXHR.responseText || textStatus);
});
Jquery AJAX code2:
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
dataType: 'json',
//data: jsonData,
data: JSON.stringify(jsonData),
contentType: "application/json",
success: function(data) {
alert("Success: " + data);
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});
fix the action
[HttpPost]
[Route("~/SendCustomerDetails")]
public IActionResult SendCustomerDetails(JObject model)
{
return Ok(" It is Success");
}
try this code
$.ajax({
type: 'POST',
url: 'http://localhost:49918/SendCustomerDetails',
data: { model:jsonData},
success: function(data) {
alert("Success: " + JSON.stringify(data));
},
error: function (data) {
alert("error: " + JSON.stringify(data));
}
});

How to send post ajax request from (.js) file to Spring MVC Controller?

(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem

Empty data result ajax with codeigniter

I'm trying to retrieve data from my controller function but this very simple example fails and sends me nothing back. The ajax function is successfully executed but the data is empty.
function company_select() {
var data;
var username = $('[name="username"]').val();
var url = base_url+'/admin/user/get_companies2';
alert(url);
$.ajax({
url: url,
type: 'POST',
dataType: 'text',
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus + " " + errorThrown) }
});
}
codeigniter function
public function get_companies2(){
echo 'test';
}
You Should Use "data" instead of "dataType" Or Passed your require variables one by one as into curli braces of data (as data:{variable1:})
function company_select(){
var data;
var username = $('[name="username"]').val();
var url = base_url+'/admin/user/get_companies2';
alert(url);
$.ajax({
url: url,
type: 'POST',
data: {username :username},
success: function(data){
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus + " " + errorThrown) }
});
}

unsupported_grant_type in Web Api 2

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)); }
});
});

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');
}
});

Resources