POST call not working for webapi - javascript

I am trying to post data in webapi for some operations . My web api contains multiple POST method.When I post data using postman it's hit to the controller method but data is passed as null.When i hit same method from web application it does not work and shows 404 error,
POST Call :
var urlstring = "/api/Membership/BulkUpload"
$.post(
urlstring,
JSON.stringify(exceljson)).
success(function(data)
{
console.log(data);
}
);
Controller Method:
[HttpRoute("api/Membership/BulkUpload")]
public HttpResponseMessage BulkUpload([FromBody]string studentDetails)
{
Some Code Here
}
when i remove [FromBody] then it does not hit from postman too. I am not getting what going wrong in post call

Try the following code,
var urlstring = "/api/Membership/BulkUpload"
$.post(
urlstring,
{JSON.stringify(exceljson))})
.done(function(data)
{
console.log(data);
}
);

You could try one of the following:
1 - Without [From Body]
Client Side
var urlstring = `/api/Membership/BulkUpload?studentDetails=${value}`
$.post(
urlstring,
{}).
success(function(data)
{
console.log(data);
}
);
[HttpRoute("api/Membership/BulkUpload")]
public HttpResponseMessage BulkUpload(string studentDetails)
{
Some Code Here
}
2 - MAP to C# object
Client Side
var urlstring = '/api/Membership/BulkUpload'
$.post(
urlstring,
{
studentDetails : value
}).
success(function(data)
{
console.log(data);
}
);
Server Side
[HttpRoute("api/Membership/BulkUpload")]
public HttpResponseMessage BulkUpload([FromBody]studentApiModel dataIn)
{
Some Code Here
}
public class studentApiModel
{
public string studentDetails { get; set; }
}

Related

Spring Boot + Bootstrap + jQuery : Error 404 in $ajax call on Firefox

I've an application using Spring Boot + Bootstrap + Thymeleaf. I am trying to make an AJAX call to fill a combox use the jquery. In the Chrome workes well. In the Firefox gives me the 404 message. What could be happend?
The Firefox console.log message:
enter image description here
My AJAX code:
function carregaComboAtivoAjax(url) {
var Id = document.getElementById('idUo').value;
$.ajax({
url: url,
dataType: 'html',
data: { Id: Id },
success: function(data) {
if (data != null) {
$("body").html(data);
}
}
});
}
My Controller Code:
#RequestMapping(value = "/carregaComboAtivoCadastraCampo", method = RequestMethod.GET)
private String carregaComboAtivo(#RequestParam UUID Id, Model model) {
...
}
Best,
If you have the same problem, that is the solution:
In the spring boot controller method you need write like this:
#RequestMapping(value = "/carregaComboAtivoCadastraCampo", method = RequestMethod.GET, produces = { MediaType.TEXT_HTML_VALUE })
#ResponseBody
public ModelAndView carregaComboAtivo(#RequestParam UUID uoId, Model model) {
...
}
You need to set the media type produces.

How to post js string to C# in ASP.NET Core MVC

I am new to ASP and I am trying to take a string in my JS code and post it to my controller so that I can use it to query my database.
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (response) {
alert(userCounty);
},
error: function (response) {
alert("failed");
}
});
}
Controller
[HttpPost]
public ActionResult Index (string userCounty)
{
var query = //use linq to query database
return View(query);
}
I only ever get the "success" alert when I use a JsonResult function in my Controller but I need it to eventually return a LINQ query to the View(); function and that hasn't worked when using a JsonResult function. Any ideas would be helpful. I don't necessarily have to use ajax if there is a better way. I just need a way to pass the string stored in userCounty to my controller.
Please change your controller method like this
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
var query = //use linq to query database
return View(query);
}
For viewing the page, you'll need
[HttpGet]
public ActionResult Index()
{
return View();
}

Sending JSON object to ASPNET controller method and body content is null

I was trying to figure out how I get the body of the JSON object, that I was sending with the listed AJAX POST request.
While debugging the UploadJSON method gets called but is having a jsoninput with null content.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IFormCollection jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}
//javascript
function uploadJSON(plistArrayForJSON) {
var sendobj = JSON.stringify({ plistArrayForJSON });
$.ajax({
url: 'https://localhost:5001/home/uploadjson',
type: 'POST',
data: sendobj,
contentType: "application/json",
});
}
The JSON you send is not deserializable as IFormCollection.
//ASP.NET Core
[HttpPost]
public IActionResult UploadJSON([FromBody] IList<PlayList> jsoninput)
{
var inputBody = jsoninput;
// Writing JSON object content into a file....
return RedirectToAction("Index");
}

Ajax post request in Spring MVC

I am currently trying to call an ajax request from a JavaScript onchange handler to call a Spring MVC controller. I believe the way I am currently calling the URL in my view is wrong since I get an 404 error on the browser when the event is triggered and call for url. Can anyone shine some light if I have everything setup correctly?
Here is my code:
#Controller
public class DataTableController
{
#RequestMapping(value = "/table", method = RequestMethod.GET)
public String home(Model model) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> gpnList = new ArrayList<GPN>();
gpnList.add("GPN-1"); gpnList.add("GPN-2"); gpnList.add("GPN-3");
model.addAttribute("gpnList", mapper.writeValueAsString(gpnList));
return "index"; //name of my view
}
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(sectors);
}
}
Jquery Code:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
var filters = { "market" : market }
filters = JSON.stringify(filters);
$.ajax({
url: "/getsector",
type: "POST",
dataType : 'json',
contentType : "application/json",
data: JSON.stringify(filters),
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
The main thing I want to achieve is being able to call my controllers via ajax calls. Any other tips on Spring Controller Mapping and conventions will be appreciated.
If your a requesting information you should use GET requests, not POST.
You are mixing #RequestParam with a json payload. If you want to receive your filter as a request param it has to go at the url, not as a json payload, using something like:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
$.ajax({
url: "/getsector?market="+market,
type: "GET",
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
#RequestMapping(value = "/getsector", method = RequestMethod.GET)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
.... your logic.
}
On the other hand, if you really want to use POST requests with a json payload, you need to use #RequestBody at the controller and bind the json object to a bean with the same properties.
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestBody Market market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
return sectors;
}
public class Market
{
String market;
//getter and setter...
}
Bear in mind your javascript is wrong as well, you are using JSON.stringify twice.
If you use #ResponseBody and spring is configured fine it will make the serialisation for you when returning the response, so you do not have to do it manually.
This code has not been tested, it is just for you to get an idea.

jQuery.ajax() parsererror

when i try to get JSON from http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json with:
(jQuery 1.6.2)
$.ajax({
type: "GET",
url: url,
dataType: "jsonp",
success: function (result) {
alert("SUCCESS!!!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
alert(xhr.responseText);
alert(xhr.status);
alert(thrownError);
}
});
I get: parsererror; 200; undefined; jquery162******************** was not called
but with the JSON from http://search.twitter.com/search.json?q=beethoven&callback=?&count=5 works fine.
Both are valid JSON formats. So what is this error about?
[UPDATE]
#3ngima, i have implemented this in asp.net, it works fine:
$.ajax({
type: "POST",
url: "WebService.asmx/GetTestData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert(result.d);
}
});
WebService.asmx:
[WebMethod]
public string GetTestData()
{
try
{
var req = System.Net.HttpWebRequest.Create("http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json");
using (var resp = req.GetResponse())
using (var stream = resp.GetResponseStream())
using (var reader = new System.IO.StreamReader(stream))
return reader.ReadToEnd();
}
catch (Exception) { return null; }
}
It's because you're telling jQuery that you're expecting JSON-P, not JSON, back. But the return is JSON. JSON-P is horribly mis-named, named in a way that causes no end of confusion. It's a convention for conveying data to a function via a script tag. In contrast, JSON is a data format.
Example of JSON:
{"foo": "bar"}
Example of JSON-P:
yourCallback({"foo": "bar"});
JSON-P works because JSON is a subset of JavaScript literal notation. JSON-P is nothing more than a promise that if you tell the service you're calling what function name to call back (usually by putting a callback parameter in the request), the response will be in the form of functionname(data), where data will be "JSON" (or more usually, a JavaScript literal, which may not be the quite the same thing). You're meant to use a JSON-P URL in a script tag's src (which jQuery does for you), to get around the Same Origin Policy which prevents ajax requests from requesting data from origins other than the document they originate in (unless the server supports CORS and your browser does as well).
in case the server does not support the cross domain request you can:
create a server side proxy
do ajax request to your proxy which in turn will get json from the service, and
return the response and then you can manipulate it ...
in php you can do it like this
proxy.php contains the following code
<?php
if(isset($_POST['geturl']) and !empty($_POST['geturl'])) {
$data = file_get_contents($_POST['geturl']);
print $data;
}
?>
and you do the ajax request to you proxy like this
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
alert("abt to do ajax");
$.ajax({
url:'proxy.php',
type:"POST",
data:{geturl:'http://api-v3.deezer.com/1.0/search/album/?q=beethoven&index=2&nb_items=2&output=json'},
success:function(data){
alert("success");
alert(data);
}
});
});
});
</script>
tried and tested i get the json response back...
At last i have found the solution. First of all, the webmethods in a webservice or page doesn't work for me, it always returns xml, in local works fine but in a service provider like godaddy it doesn't.
My solution was to create an .ahsx, a handler in .net and wrap the content with the jquery callback function that pass the jsonp, and it works .
[System.Web.Script.Services.ScriptService]
public class HandlerExterno : IHttpHandler
{
string respuesta = string.Empty;
public void ProcessRequest ( HttpContext context )
{
string calls= context.Request.QueryString["callback"].ToString();
respuesta = ObtenerRespuesta();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write( calls +"("+ respuesta +")");
}
public bool IsReusable
{
get
{
return false;
}
}
[System.Web.Services.WebMethod]
private string ObtenerRespuesta ()
{
System.Web.Script.Serialization.JavaScriptSerializer j = new System.Web.Script.Serialization.JavaScriptSerializer();
Employee[] e = new Employee[2];
e[0] = new Employee();
e[0].Name = "Ajay Singh";
e[0].Company = "Birlasoft Ltd.";
e[0].Address = "LosAngeles California";
e[0].Phone = "1204675";
e[0].Country = "US";
e[1] = new Employee();
e[1].Name = "Ajay Singh";
e[1].Company = "Birlasoft Ltd.";
e[1].Address = "D-195 Sector Noida";
e[1].Phone = "1204675";
e[1].Country = "India";
respuesta = j.Serialize(e).ToString();
return respuesta;
}
}//class
public class Employee
{
public string Name
{
get;
set;
}
public string Company
{
get;
set;
}
public string Address
{
get;
set;
}
public string Phone
{
get;
set;
}
public string Country
{
get;
set;
}
}
And here is the call with jquery:
$(document).ready(function () {
$.ajax({
// url: "http://www.wookmark.com/api/json",
url: 'http://www.gjgsoftware.com/handlerexterno.ashx',
dataType: "jsonp",
success: function (data) {
alert(data[0].Name);
},
error: function (data, status, errorThrown) {
$('p').html(status + ">> " + errorThrown);
}
});
});
and works perfectly
Gabriel

Categories