I have ajax call on my aspx page as:
$.ajax({
url: "/SiteAdmin3/UpsIntegration.aspx/addUpdatePackageData",
data: JSON.stringify({
'_OrderNumber': $("#txtOrderNumber").val(),
'_PackageNumber': $("#lblPackageNumber").html(),
'_Height': $("#txtPackageHeight").val(),
'_Width': $("#txtPackageWidth").val(),
'_Lenght': $("#txtPackageLenght").val(),
'_Weight': $("#txtPackageWeight").val(),
'_ReferanceNumber1': $("#txtPackageReferanceNumber1").val(),
'_ReferanceNumber2': $("#txtPackageReferanceNumber2").val(),
'_ReferanceNumber3': $("#txtPackageReferanceNumber3").val(),
'_ReferanceNumber4': $("#txtPackageReferanceNumber4").val(),
'_ReferanceNumber5': $("#txtPackageReferanceNumber5").val(),
'_PackageType': $("#ddlAddPackageType").val()
}),
contentType: 'application/json;',
dataType: "json",
type: 'POST',
cache: false,
success: function (Data) {
//whatever operation to be performed
},
error: function (err) {
alert("Error in Saving.Please try later." + JSON.stringify(err));
}
});
On cs page my addUpdatePackageData method is:
[WebMethod()]
public static ShipStationIntegration[] addUpdatePackageData(string _OrderNumber, string _PackageNumber, string _Height, string _Width, string _Lenght, string _Weight, string _ReferanceNumber1, string _ReferanceNumber2, string _ReferanceNumber3, string _ReferanceNumber4, string _ReferanceNumber5, string _PackageType)
{
System.Collections.Generic.List<ShipStationIntegration> lst = new List<ShipStationIntegration>();
try
{
lst = bindPackageListFromPageMethod();
return lst.ToArray();
}
catch (Exception)
{
return lst.ToArray();
}
}
This returns correct list.
Butafter getting responce it always goes in error block of ajax as and gives error as:
I am not understanding what is wrong in it?
I also tried with:
contentType: 'application/json; charset=utf-8',
But still error was there.
Please help me.
If you are using the VS 2010 integrated web server (Cassini), it does not support Integrated Pipeline mode. You'll need to download IIS Express and set your project to use it instead.
When your return from a webmethod and the response format should be JSON the response pass to a httpModule that serialize the response into JSON and try to execute Response.Headers.Add("Content-type", "application/json"); BUT this way to add http headers are not supported by Cassini because this way needs Integrated Pipeline mode and as #Kevin says:
Cassini does not support Integrated Pipeline
Related
After 3 hours browsing on stackoverflow I don't find solution of my problem.
So I suspect something in my project is special.
I have a ASP.NET Core (2.0) WebApplications Project on Visual Studios 2017. I try to make a ajax call from my Kalender.cshtml file:
return $.ajax({
type: 'GET',
url: myurl,
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) { //REQUEST SUCCESS
alert(result);
},
with myurl:
var myurl = '#Url.Action("EventsRead","Kalender")';
but I recognize that alert(myurl) return an empty string. So the ajax call must fail. I guess the url should something like:
/Kalender/EventsRead
but if I use this, ajax return 404 Not found.
My Kalender.cshtml.cs Action looks like:
[HttpGet]
public IActionResult EventsRead()
{
//DATABASE READOUT
var events = DataBase.Events.ToList();
return new JsonResult(events);
}
And the class of the PageModel looks like:
public class KalenderModel : PageModel
Here is everything auto generated. I try about 100 different version but never get a breakpoint into the EventsRead() action.
SIDE INFORMATION:
In my Startup.cs I suppress AntiforgeryToken:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute());
});
I really need some help before I get insane, thankful for any response.
Martin
Everybody who interested into the solution:
I changed in Startup.cs:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//ROUTES DEFAULT SETTINGS
app.UseMvc();
}
to:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//ROUTES CUSTOM SETTINGS
app.UseMvcWithDefaultRoute();
}
after this
'#Url.Action("TestGet","Kalender")'
will return correkt path.
Now I go to my bed and cry.
Your Controller setup looks just fine. When you used /Kalender/EventsRead as url and have a response 404 because of your data field. You've put curly braces as string. Try this in your ajax call
return $.ajax({
type: 'GET',
url: '/Kalender/EventsRead',
data:{},
success: function (result) { //REQUEST SUCCESS
console.log(result);
},
error: function (response){
console.log(response)
});
This may help you.
I am working on a Spring-MVC application in which for this single method I am getting an error as Unsupported media type. None of the other methods have this problem. Any help would be nice. Thank you-.
Java Code :
#RequestMapping(value = "/setnotificationlevels")
public
#ResponseBody
boolean setNotificationLevels(#RequestParam("groupid") long groupid, #RequestBody GroupMembers member) {
System.out.println("Set notification levels is called. ");
return this.groupMembersService.setNotificationLevels(member, groupid);
}
JS code :
setEmailNotifications : function (groupid, settings){
return $.ajax({
url: "/setnotificationlevels?groupid=" + groupid,
type: 'POST',
cache:false,
data : JSON.stringify(settings),
contentType: "application/json; charset=utf-8"
});
},
Error log :
description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
Thank you.
tell your java code that its a post or get http methd:
#RequestMapping(value = url, method = RequestMethod.POST)
public#ResponseBody StringOrAnyResponseObject fName(#RequestBody final Object o)
{}
and in your js:
in any function
return $http.post(url,parameterMap);
Try to add consumes = "application/json;charset=UTF-8" to #RequestMapping annotation.
so I'm trying to send data as a json to a Python file, however my Python I'm getting the error
Uncaught TypeError: d.type.toUpperCase is not a function
I'm a newbie to JS so I'm not sure how everything fully works, however I did just add in the GET by the POST because before that I was getting 405 errors.
Now, I'm getting this d.type.toUpperCase error. Here is my code. Please help!!
JavaScript:
function on_request_success(response) {
console.debug('response', response);
document.write("Success!!!");
}
function on_request_error(r, text_status, error_thrown) {
console.log(r);
console.debug('error' + text_status + ", " + error_thrown + ":\n" + r.responseText);
document.write("Failure line 11");
}
var request = {"Data":"Success!!"};
function addTrack() {
$.ajax({
url: 'http://mattprice09.github.io/addTrack.py',
type: ['GET','POST'],
cache: false,
data: JSON.stringify(request),
contentType: 'application/json',
processData: false,
success: on_request_success,
error: on_request_error
});
}
Python:
import json
import sys
request = json.load(sys.stdin)
file_open = open('http://mattprice09.github.io/database.txt', a)
file.write(request)
file.close()
You need to set the type argument to a string, not a list:
type: 'POST',
From the $.ajax() documentation:
type (default: 'GET')
Type: String
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
The error tells you that a list cannot be uppercased.
However, you'll have other major issues here:
GitHub pages doesn't support server-side scripts. Your Python code is not going to be executed.
You cannot open a remote URL for writing; the open() function can only open files on the local filesystem.
I'm working on a ASP.NET web API with a C# project that I try to call from JavaScript.
Here is my JavaScript:
function LoadGraph() {
var file = document.getElementById("file-datas");
if ('files' in file)
{
if (file.files.length == 0) {
Console.log("Empty file");
} else {
var text = file.files;
/*$.ajax({
url: "api/Graph",
type: "POST",
dataType: "json",
processData: false,
contentType: false,
data: $(text).serialize(),
cache: false,
success: function (data) {
console.log(data);
}
})*/
//$.getJSON('api/Graph', file, function (data) { console.log(data) });
}
}
And here is my Controller:
[Authorize]
[RoutePrefix("api/Graph")]
public class GraphController : ApiController
{
// POST: api/Graph
[HttpPost]
[Route("All", Name = "LoadGraph")]
public IHttpActionResult LoadGraph(string text)
{
RecursiveGraph result = test.SecondMethodFruchterman(text);
return Ok(result.name);
}
}
As you see I tried two methods in my JavaScript:
The first one with $.ajax makes POST http://localhost:53497/Home/api/Graph 404 (Not Found).
The second one with $.getJSON makes Uncaught RangeError: Maximum call stack size exceeded.
result.name is a string but I want to transfer result itself after solving these problems and getting something that works.
I don't know which one of the two method is better to use.
I don't know why I get a 404 error on $.ajax and no on $.getJSON.
And I don't know why I get this Max call stack error since it seems to appear when recursive functions are called and it's not the case here.
The first problem is that the resolved URL is POST http://localhost:53497/Home/api/Graph 404 (Not Found) which is wrong since your URL is actually supposed to be http://localhost:53497/api/Graph. To fix, prepend your AJAX urls with a /.
The second problem is likely the server error being returned as text to your web client. It is probably due to your recursion never terminating. I can't see that code in detail, but RecursiveGraph result tips me off. I'd bet on your recursive method never terminating, which would definitely max out the callstack.
I think you shall change your ajax call to this:
$.ajax({
url: '#Url.Action("LoadGraph", "Graph")',
type: "POST",
traditional: true,
data: {
text: $(text).serialize()
},
cache: false,
success: function (data) {
console.log(data);
}
})
You get the 404 (not found error code) because your ajax post url api/Graph is just your referring to your controller
Why did you even change your controller RoutePrefix to "api/Graph"? Is there a special reason for doing this?
Here the corrected code
//[Authorize]
[RoutePrefix("api/Graph")]
public class GraphController : ApiController
{
// POST: api/Graph
[Route("LoadGraph", Name = "LoadGraph")]
public IHttpActionResult LoadGraph([FromBody] string text)
{
RecursiveGraph result = test.SecondMethodFruchterman(text);
return Ok(result);
}
}
I need to add [FromBody] because string is not a model.
I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.