Ajax GET call to webAPI - javascript

In my javascript file i am trying to make a GET Request to my webAPI, the entire request is ignored. the two alerts before and after the request are outputted but nothing within my request.
This is my GET request made in my javascript file:
alert("before Get");
$.ajax({
url: '/api/Map/',
type: 'GET',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function () {
alert("error in request");
}
});
alert("after Get");
My WebAPI file and the method im trying to get:
// GET: api/Map
public IEnumerable<string> Get()
{
SetContext();
List<ICoordinate> BoundingBox = CreateBoundingBox(_LoadedConfiguration.StartPosition);
List<string> LayerNames = _LoadedConfiguration.GetAllLayerNames();
Map LoadedMap = new Map(BoundingBox, LayerNames, _persistenceFactory, _LoadedConfiguration);
GeoJson.IGeoJsonGeometry MapFeatureCollections = (IGeoJsonGeometry)LoadedMap.GetAsGeoJsonObject();
return new string[] { MapFeatureCollections.ToString()};
}
I am trying to return the string of "MapFeatureCollections"

Related

Send ararylist from js to spring controller

I want to send an arrayList from javaScript to spring controller, I have written this code but it doesn't work, when I call this function nothing happens.
function order_(){
var itemOrder = $('#sortable').sortable("toArray");
$.ajax({
contentType:"application/json;",
type : "POST",
url : "/my_url",
data : (itemOrder),
dataType: "json",
success: function (data) { alert("Mapping Successful") },
failure: function (data) { alert("not working..."); }
});
}
My spring controller
#RequestMapping(value = "/my_url", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String getItemOrder(#RequestBody String[] itemOrder) {
// code to get itemOrder }
Is there something wrong in this code?

RequestBody is null in controller

I'm trying to send JSON object from frontend to backend via jQuery AJAX.
The ajax call is performed successfully on the requested path "/survey" with a POST method.
Problem is, my #RequestBody final HmmSurveyForm hmmSurveyForm has null values for my fields "answer1" and "heading".
When I checked request in google chrome developer request is sent:
But the response is null for populated fields from frontend:
I have following code in frontend:
postSurvey: function() {
$.ajax({
url: this.encodedContextPath + "/survey",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: ACC.hmmSurvey.getJSONDataForSurvey(),
async: true,
success: function (response) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("The following error occurred: " + textStatus, errorThrown);
}
});
}
getJSONDataForSurvey: function () {
var json = [];
json.push({"answer1": "1"});
json.push({"heading": "Test"});
return JSON.stringify({"hmmSurveyForm": json});
}
and in backend:
#RequestMapping(value = "/survey", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody HmmSurveyForm postSurvey(#RequestBody final HmmSurveyForm hmmSurveyForm, final Model model) {
System.out.println(hmmSurveyForm);
return hmmSurveyForm;
}
public class HmmSurveyForm {
private String heading;
private String answer1;
// getter, setters
}
You are declaring your RQ body incorrectly in JS
var json = [];
json.push({"answer1": "1"});
json.push({"heading": "Test"});
console.log({"hmmSurveyForm": json});
which has the root hmmSurveyForm as an array of distinct objects, which has no relation to what your backend expects.
You should be using the code below;
var json = {};
json["answer1"] = "1";
json["heading"] = "Test";
console.log({"hmmSurveyForm": json});
Check more on JSON Object in JS here

How to return data from controller method to a jquery ajax post

My Jquery ajax call -
var formdata = $('#emailrequest').serializeArray();
// Ajax call to server
$.ajax({
url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
type: 'POST',
data: formdata,
sucess: function(data) {
alert(data.sucess);
},
error: function() {
alert('error');
}
});//End Ajax
My controller -
public ActionResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new {success = true});
But all is get is error in alert . Where am I going wrong? Please help . I just need to return a confimation from controller , be it any format.
You spelled success wrong so it will never hit. It should work with the ActionResult but a JsonResult is better.
var formdata = $('#emailrequest').serializeArray();
// Ajax call to server
$.ajax({
url: sitePath + 'supply-chain-pressure/ProcessEmailrequest',
type: 'POST',
data: formdata,
success: function(data) {
alert(data.sucess);
},
error: function() {
alert('error');
}
});//End Ajax
Try to set your controller method return type to JsonResult instead of ActionResult, so:
public JsonResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new {success = true});
}
If that doesn't help set your ajax error function to receive following parameters:
error: function (xhr, ajaxOptions, thrownError) {
...
}
Then debug in browser and set a break point to error function and in the xhr object (responseText property) you'll be able to see exact error.
you shoudn't return json like that. use [ ] instead of {}
public JsonResult ProcessEmailrequest()
{
// some code
// retun the response
return Json(new [success = true]);
}

.NET MVC JSON Post Call response does not hit complete or success

I am new to .NET MVC so please bear with me.
I wrote a function that gets triggered when there is a blur action on the textarea control:
function extractURLInfo(url) {
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
complete: function (data) {
alert(data);
},
success: function (data) {
alert(data);
},
async: true
})
.done(function (r) {
$("#url-extracts").html(r);
});
}
jQuery(document).ready(function ($) {
$("#input-post-url").blur(function () {
extractURLInfo(this.value);
});
});
This works fine and will hit the controller:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
I get the intended results if the URL is valid; it will return a partialview to the .done() function and I just display it in code. However, if the URL is not valid i want it to hit either complete, success, or done (I have been playing around to see which it will hit but no luck!) and do something with the returned data. I had it at some point trigger either complete or success but the data was 'undefined'. Can someone help me out on this?
Thanks!
In both cases your controller action is returning 200 status code, so it's gonna hit your success callback:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
if (data.message) {
// Your controller action return a JSON result with an error message
// => display that message to the user
alert(data.message);
} else {
// Your controller action returned a text/html partial view
// => inject this partial to the desired portion of your DOM
$('#url-extracts').html(data);
}
}
});
But of course a much better and semantically correct approach is to set the proper status code when errors occur instead of just returning some 200 status code:
[HttpPost]
public ActionResult Url(string url)
{
UrlCrawler crawler = new UrlCrawler();
if (crawler.IsValidUrl(url))
{
MasterModel model = new MasterModel();
model.NewPostModel = new NewPostModel();
return PartialView("~/Views/Shared/Partials/_ModalURLPartial.cshtml", model);
}
else
{
Response.StatusCode = 400;
Response.TrySkipIisCustomErrors = true;
return Json(new { valid = false, message = "This URL is not valid." }, JsonRequestBehavior.AllowGet);
}
}
and then in your AJAX call you would handle those cases appropriately:
$.ajax({
url: "/Popup/Url",
type: "POST",
data: { url: url },
success: function (data) {
$('#url-extracts').html(data);
},
error: function(xhr) {
if (xhr.status == 400) {
// The server returned Bad Request status code
// => we could parse the JSON result
var data = JSON.parse(xhr.responseText);
// and display the error message to the user
alert(data.message);
}
}
});
Also don't forget that you have some standard way of returning your error messages you could subscribe to a global .ajaxError() handler in jQuery instead of placing this code in all your AJAX requests.

How to pass string value from javascript to function in ASHX

I'm used this code to pass parameter from jQuery to ASHX, actually I want to upload file using Uploadify Plugin and send Parameter named 'Id' to ASHX
function CallHandler() {
$.ajax({
url: "PIU.ashx/MyMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { 'Id': '10000' },
responseType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result) {
alert('Request Failed');
}
and this ASHX code:
public void ProcessRequest(HttpContext context)
{
var employee = Convert.ToInt32(context.Request["Id"]);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string serEmployee = javaScriptSerializer.Serialize(employee);
context.Response.ContentType = "text/html/plain";
context.Response.Write(serEmployee);
parent MyParent = (parent)context.Session["mahdZNUparent"];
//the file data is the file that posted by Uploadify plugin
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string FileName = PostedFile.FileName; // whene i comment this line, the code works
// properly, but when uncomment this line, the code get to 'Request Failed'
}
public bool IsReusable
{
get
{
return false;
}
}
how can I Solve this problem!!!!!!!
You may want to take a loot at this: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And this one too: Using jQuery for AJAX with ASP.NET Webforms

Categories

Resources