This is my APIController method -
[HttpPost]
public HttpResponseMessage Get(string url) {
string responseString = GetWebApiData(url);
HttpResponseMessage response = new HttpResponseMessage();
if (!string.IsNullOrEmpty(responseString) && responseString.ToString().IsValid()) {
response.ReasonPhrase = "Valid";
response.StatusCode = HttpStatusCode.OK;
} else {
response.ReasonPhrase = "Invalid";
response.StatusCode = HttpStatusCode.BadRequest;
}
return response;
}
This is my ajax call to above method -
$.ajax({
type: "POST",
url: "http://localhost:50/api/DC/" + formData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, xhr) {
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
I am not able to read the HttpResponseMessage returned by the API Method. For both the conditions of OK and Bad Request, status code returned in 'xhr' of ajax method is '204' & 'No Content'. I need to validate based on response code. Any help pls!
I tried success: function(response) too, response was undefined.
The response is 204 No content because you literally don't add any content. All you're doing is setting the response code. You can add content to the response like this:
response.Content = new StringContent("Return data goes here");
Alternatively use the Request.CreateResponse()/CreateErrorResponse() to create the HttpResponseMessage for you:
[HttpPost]
public HttpResponseMessage Get(string url)
{
string responseString = GetWebApiData(url);
if (!string.IsNullOrEmpty(responseString) && responseString.ToString().IsValid())
{
return Request.CreateResponse("Valid"); // I'd suggest returning an object here to be serialised to JSON or XML
}
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Invalid");
}
Related
My ajax request shown below sends a json object to a backend function which is supposed to return $request->all() but instead returns nothing if i send the json cordinates that i'm currently sending but if i send a simple JSON it returns just fine.
AJAX
var JSONObj = {"test" : "test1"};
var PointsOnCanvas = [{"PX":486,"PY":447,"CX":485,"CY":447},{"PX":485,"PY":447,"CX":487,"CY":443},{"PX":487,"PY":443,"CX":490,"CY":438},{"PX":490,"PY":438,"CX":499,"CY":423},{"PX":499,"PY":423,"CX":500,"CY":421},{"PX":500,"PY":421,"CX":512,"CY":402},{"PX":512,"PY":402,"CX":519,"CY":392},{"PX":519,"PY":392,"CX":532,"CY":371}]
$.ajax({
url: "/Ajax",
type: "GET",
//datatype: "json", //could be xml, json, html, text or script
contentType: "application/json",
data: JSONObj,//JSON.stringify(PointsOnCanvas),
error: function (response) {
console.log(response)
},
success: function (response) {
console.log(JSON.stringify(PointsOnCanvas))
console.log("response is " + response)
console.log("json response is " + JSON.stringify(response))
PointsOnCanvas = [];
}
});
I have commented out //JSON.stringify(PointsOnCanvas) above this is the code that i believe is causing the problem.
The laravel code is below
public function RecieveAjax(Request $request){
if($request->ajax()){
return response()->json(['result' => $request->all()]);
}else{
return "Not Helo";
}
}
I am trying to pass some variables through JSON from JSP to servlet through ajax call. But i am getting null value at servlet side. Please some one help me on to find out where i am making mistake/ what i missed
//JSON
var masterdata = new Object();
masterdata.grn = $('#grn').val();
masterdata.pono = $('#pono').val();
masterdata.podt = $('#podt').val();
//call the servlet to insert the data only when error = 0
if (error != 1){
$.ajax({
url : 'insertserv',
type: 'POST',
dataType: 'json',
data: {test : JSON.stringify(masterdata)},
contentType: 'application/json',
mimeType: 'application/json',
success : function(data) {
alert('Hi');
}
});
}
else{
alert("Save cannot be performed. Please check the entered data!");
}
});
public class insertserv extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("I am inside insert");
String masterdata = request.getParameter("test");
System.out.println("masterdata : "+masterdata);
response.setContentType("text/plain");
}
}
Replace your ajax code with my code...
//JSON
var masterdata = new Object();
masterdata.grn = $('#grn').val();
masterdata.pono = $('#pono').val();
masterdata.podt = $('#podt').val();
//call the servlet to insert the data only when error = 0
if (error != 1){
$.ajax({
url : 'insertserv',
type: 'POST',
dataType: 'json',
data: JSON.stringify({"test" :masterdata}),
contentType: 'application/json',
mimeType: 'application/json',
success : function(data) {
alert('Hi');
}
});
}
else{
alert("Save cannot be performed. Please check the entered data!");
}
});
To get data in servlet
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
String json = "";
if (br != null) {
json = br.readLine();
}
JSONObject wholedata= new JSONObject(json);
now the object wholedata has a your json..
if you are using JSON.stringify() then you have to use
BufferedReader in servlet ,
You can use request.getparameter in servlet when you are passing data in URL of servlet.
If your backend is responding with json content then only dataType:"json" works. Try change the response type:
response.setContentType("application/json");
Because your ajax is expecting json from the backend with dataType:"json",.
or vice-versa.
change the dataType to text: dataType:"text", as the response header says response.setContentType("text/plain");. But in this case you have to use JSON.parse() to parse the json string.
//JSON
var masterdata = new Object();
masterdata.grn = $('#grn').val();
masterdata.pono = $('#pono').val();
masterdata.podt = $('#podt').val();
//call the servlet to insert the data only when error = 0
if (error != 1) {
$.ajax({
url: 'insertserv',
type: 'POST',
dataType: 'text', //<------change this
data: {
test: JSON.stringify(masterdata)
},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
alert('Hi');
}
});
} else {
alert("Save cannot be performed. Please check the entered data!");
}
});
So I have a basic controller accepting a post..
[HttpPost]
public ActionResult Submit(string postCost)
{
//Do stuff here before sending back redirect details...
return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") });
}
And I'm posting via jquery ajax method:
$.ajax({
url: partyURL,
dataType: 'json',
contentType: 'application/json', //charset=utf-8',
type: 'POST',
data: { postCost: postageCost}, //**This fails!**
//data: "{'postCost':'3.50'}", //**This works**
success: function (response) {
if (response.result == 'SoldOut') {
$("#soldOut").show();
}
else if (response.result == 'Redirect') {
//All good, onward to confirmation page
window.location = response.url;
}
},
error: function (xhr, status, error) {
// Error handling here
}
});
where the postageCost variable sent in when it fails returning status 500:
postageCost = '3.50';
postageCost = JSON.stringify(postageCost); //also fails with this
but if I hard-code the data definition as
data: "{'postCost':'3.50'}",
It works fine.
The key must therefore lie in what I'm doing with the data element?
you need to do
var datum = {'postCost': '3.50'};
data: JSON.stringify(datum), //Ajax call data
I am calling this action of api from client. The client code also see below.
API Action:
public class StudentTestController : ApiController
{
[HttpPost]
public HttpResponseMessage GetLessonInfo(int request)
{
HttpResponseMessage result = null;
result = Request.CreateResponse(HttpStatusCode.OK,StudentTest.GetLessonInfo(request));
return result;
}
}
JavaScript client script:
function SendRequest() {
var url = "http://localhost:1938/api/StudentTest/GetLessonInfo";
var data1 = "request=293";
$.ajax({
type: 'POST',
url: url,
data: data1,
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
success: function (data) {
$('#txtResponce').val(JSON.stringify(data.Data));
},
error: function (xhr, status, error) {
var errorText = xhr.status + "\r\n" + status + "\r\n" + error;
$('#txtResponce').val(errorText);
}
});
}
When i am trying to call Action with the above snippet it will not calling the controller action. How to solve this?
Pavan.
Have you tried this instead:
var url = "/api/StudentTest/GetLessonInfo";
var data1 = "293";
Maybe "request=293" can be considered as a string and not the "int" expected as parameter.
And since the int parameter is not nullable, maybe it's giving you a Bad Request response.
Check with Fiddler what is being sent to the server.
I want to parse JSON results, containing status or error messages, returned from controller method or custom exception filter and display the messages.
$.ajax({
url: "/Account/LogOn",
type: "POST",
dataType: "json",
data: form.serialize(),
success: function (result) {
alert(result);
}
});
I think that with this code I can do it for a specific Action Result or method. Is there a way to do this for every JSON result returned to the page?
No, there's no way to do this for every possible JSON returned by your controller actions because the structure will be different and the properties of this result variable won't be the same.
The correct way would be to have a custom error handler which will intercept all exceptions and wrap them in a well defined JSON structure. Then you could use the error callback in the AJAX request to handle this case.
public class AjaxErrorHandler : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.Result = new JsonResult
{
Data = new
{
ErrorMessage = filterContext.Exception.Message
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.ExceptionHandled = true;
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
}
}
}
which could be registered as a global action filter:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new AjaxErrorHandlerAttribute());
}
and on the client you could also have a global AJAX error handler for all AJAX requests on the same page:
$(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) {
var json = $.parseJSON(jqXHR.response);
alert(json.ErrorMessage);
});
$.ajax({
url: "/Account/LogOn",
type: "POST",
dataType: "json",
data: form.serialize(),
success: function (result) {
alert(result);
}
error: function (req, status, error) {
//your logic
}
});