Jquery Html Form Ajax With Spring 405 Method Not allowed - html

I have deployed my Spring project in Tomcat and startr the tomcat. I wrote one html page to call the spring MVC using ajax.
It says 405 Method Not Allowed.
I am wondering if i run the same url in browser it is working. Please any one can help me?
I have my html page in another folder
$.ajax({
type: "post",
url: "http://localhost:8080/SampleWebService/sample/sample-user",
cache: false,
data:'firstName=' + $("#firstName").val() + "&lastName=" + $("#lastName").val() + "&currentCompany=" + $("#currentCompany").val(),
success: function(response){
alert(response);
},
error: function(){
alert('Error while request..');
}
});

Could be a cross-domain problem. Set
crossDomain: 'TRUE'
The default value is FALSE for security reasons.

Related

RESTful service do not response with ajax call using localhost

From my work gave me a project to finish with which I am having the following problem:
In solution there is web API and RESTful API in MVC
if I call directly Restful service it's responding
if i make a test and put in home controller in web API HttpWebResponse it is responding
but the request is put in .js file and the code is
return $.ajax({
type: 'GET',
url: serviceURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: urlParams,
crossDomain: true,
beforeSend: lazy(),
complete: complete()
});
and this is failing with the following message e requested resource does not support http method 'OPTIONS
in webconfig everything is settled correctly
It is not working if I call REST API locally, if I call those which is on server it is working.
I read almost everything connected to that problem, but I am still stuck.

Error parse JSON AJAX SAPUI5 consume web service spring

I have problem with AJAX call. error with parseerror. my code:
$.ajax({
type: "GET",
url: "http://localhost:8089/SpringNew/tesget",
dataType: "jsonp",
contentType: "application/json; charset=utf-8",
success: function(resp){
alert("Server said123:\n '" + resp );
},
error: function(request, errorText, errorCode){
alert('Error121212: ' + errorText);
}
});
When I use this code, error with alert "Error121212: parseerror", and when I use dataType: "json", I have error: "XMLHttpRequest cannot load".
I created web services with Java Spring, in webservices, I run in port 8089, and in frontend (I use SAPUI5) in port 8080.
my web services:
How to fix this problem?
Thanks.
Bobby
The question seems to have missed some details. I believe this is because of the CORS headers from the server side. You should allow the origin that you are requesting with.
For allowing all, you can set the header 'Access-Control-Allow-Origin' to be '*'
This should solve your issue.
Your datatype contains an typo imho. It should be "json" instead of "jsonp". You may also try ...[url to service]/[entityset]?$format=json

jQuery $.ajax failing no error message, server responded with 200 OK

I have an ajax call that works fine locally, but when I published it into the server, the code is never executed but returns "200 OK" anyway. No "success" code is ejecuted, nor the "error" code. Here's my ajax call:
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(data) {
var myObj = JSON.parse(data.d);
for (var i = 0; i < myObj.length; i++) {
var element = document.getElementById("LbItem " + myObj[i].MenuItemID);
element.innerHTML = "<b>" + element.innerHTML + " (" + myObj[i].Cantidad + ")</b>";
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
I also tried to put the complete url in the "url" field but still no luck.
The weird thing is that when I put the complete url directly into the browser, it is still not executing the code. And it works fine locally!!
I know there's a similar post (jQuery $.ajax failing silently, no error messages, and server responded with 200 OK) but is not resolved and it's driving crazy here.
PD: this is NOT cross-domain, my ajax code is in a .ascx and I am trying to call a method on an .aspx
Thanks very much!!!!
EDIT: I tried to remove the System.web.extensions reference of my web project and add the dll to my bin, but it's still not working (the 1.0.61025.0 version). Besides, I am running the ASP.NET website in IIS with framework 2.0, and I don't have framework 3.5 installed on my server (but locally I do). Maybe that's the problem? I can't install it because of the client security policies, what shall I do?
EDIT 2: I tried doing a simple response from my .aspx, just to test if the problem was in that method, but it is still not executing the success function. Here's my .aspx code:
[WebMethod]
public static string ObtenerContadores()
{
return new JavaScriptSerializer().Serialize("true");
}
and adapted the .ascx
$.ajax({
type: "POST",
url: "/CargadorContadores.aspx/ObtenerContadores",
contentType: "application/json; charset=utf-8",
data: "",
async: false,
dataType: "json",
success: function(dictionary) {
alert("hello");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
});
Here's your problem: "The weird thing is that when I put the complete url directly into the browser, it is still not executing the code." Your JavaScript is expecting -- requiring -- a JSON response, and is apparently getting no response at all. This is not a JavaScript problem, but a problem with your .aspx page.
EDIT: Based on your comments below, it's clear that the problem is that your .aspx page is not returning what you expect. Because the .aspx doesn't produce the expected output even when you go to it directly, the problem is in that page, not in the jQuery.
Pretend the .aspx produces {}, false, or true. Your success code will run, but not do anything. Try putting an alert("Foo"); in there and watch what happens. The problem isn't that your jQuery is busted; it's that it isn't getting meaningful input from your .aspx page.
P.S. I would recommend using a variable name other than data in your success function, just in case it's getting messed up by the data object attribute in your .ajax call.
Okay, I believe I've figured this out, so I'm posting a second answer to preserve the prior discussion.
Here's the fix. Remove this line:
contentType: "application/json; charset=utf-8",
In my test script, this caused jQuery to send the Content-Type header application/json; charset=utf-8, as expected, but the actual contents of the request were not properly sent as JSON. For example, rather than sending {"foo":"bar"}, it was sending foo=bar. As a result, the receiving script acted as if no data was posted at all. When I commented out the line above, my test script worked fine and did whatever I expected with the values received from the target URL.
Note that this will post your data as normal post data. For example, if your $.ajax() call looks like this, the posted data will contain a variable named foo and one named who:
$.ajax({
...
data: {foo : "bar",
who : "what"},
...
});
If you want to post already-serialized JSON, do it like this:
$.ajax({
...
data: { somevariablename: '{"foo":"bar","who":"what"}' },
...
});
Then, you just have to parse the POST parameter somevariablename on the server side.
Hope this helps!
If its VS2012, try for adding Mime Type Handler, since VS2012 has IIS express and it need to add Mime type handler externally,
Add below code to web.config
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
.. and if its not VS2012 then follow this link
add .json handler support in IIS 7
I want to thank everyone for your help.
I finally had to install the 3.5 Framework on the server, I had no choice.
The second I installed it, and updated the web.config dll's references to 3.5, it worked like a charm.
Thanks again!!!!!

Moving HTML/Javascript file to different server stops it from working

I've got 2 servers with different versions of .NET installed. Server 1 has .NET 1.1 and Server 2 has .NET 3.5.
I have a webservice on the .NET 3.5 server, where the following works fine:
function selectedDateTime(strDate, strHours, strMinutes) {
$.ajax({
url: 'webservice.asmx/GetCount',
type: 'POST',
data: '{strMeetingDate: "' + strDate + ' ' + strHours + ':' + strMinutes + ':00"}',
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
success: function(department) {
console.log("success: " + department.d);
},
error: function(xhr, status, error) {
console.log("status message: " + status);
console.log("error message: " + error);
console.log("xhr message: " + xhr.responseText);
}
});
}
$("#btnTest").click(function(event) {
selectedDateTime("01/07/2013", "13", "00");
});
I want to use the same script on the older .NET 1.1 server too, but can't move the webservice to the old server because it's written using .NET 3.5, so when I tried and it just gave lots of error messages.
So I thought I should just move the html/javascript above to the old server and tell it to point to the webservice on the new server:
I did, and changed the script above a little to point to the new server:
url: 'http://server2/webservice.asmx/GetCount',
It gave the following message:
http://server2/webservice.asmx/GetDayCount 401 (Unauthorized)
http://server2/webservice.asmx/GetDayCount Origin http://server1 is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load http://server2/webservice.asmx/GetDayCount. Origin http://intranet is not allowed by Access-Control-Allow-Origin.
So I changed the script above a little again, by changing the json bit to jsonp, as I think jsonp allows crossdomain?
dataType: 'jsonp',
But that didn't solve the problem either, I am now getting:
GET http://server2/webservice.asmx/GetCount?callback=jQuery…2680346152&{strMeetingDate:%20%2201/07/2013%2013:00:00%22}&_=1372680346153 500 (Internal Server Error)
Anyone know why this is not working, as the webservice and script clearly worked on the new server when both files were together on the same server.
Look at this topic.
It is not possible to do an asynchronous POST to a service on another domain, due to the (quite sensible) limitation of the same origin policy. JSON-P only works because you're allowed to insert <script> tags into the DOM, and they can point anywhere.
About how jsonp works

JSON, invalid label, issue consuming JSON

I have an issue with my JSON. We area getting it from a SOAP service I believe. I am using jQuery AJAX to try to consume the JSON. We are using the Asp.NET solution so I know about the "d" security feature and have in my dataFilter a way to try to get around that. I am getting the JSON back in Firebug but not to my local machine. The Service is on a domain separate from my local machine. I know about the cross domain policy issue but seems to be consuming the JSON in Firebug when I put the dataType as "jsonp" in the jQuery AJAX call.
If I set my dataType as "json" I get nothing back in Firebug.
The thing is my JSON has "\" slashes in it. I guess that is why Firebug is giving me an "invalid label" error. But I am not sure of that.
How can I filter out the "\" without doing the server side code again.
How can I just get the JSON back and alert on my page.
My jQuery Ajax call is below.
$(document).ready(function () {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
async: false,
url: "http://www.myexternaldomain.com/jservice/myservice.svc/CurrentJsonDataFullWeatherPanel",
data: "{}",
dataType: "jsonp",
dataFilter: function(data) {
// This boils the response string down
// into a proper JavaScript Object().
var msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
success: function(msg) {
// This will now output the same thing
// across any current version of .NET.
alert(msg);
},
error: function (result) {
alert('Failed: ' + result.status + ' ' + result.statusText);
}
});
});
My JSON output in Firebug shows like this.
{"d":"[{\"AirTemperature\":\"57.3\",\"BarometricPressure\":\"30.08\",\"CurrentRainRate\":\"\",\"DewPointTemperature\":\"30.7\",\"HeatIndex\":\"57.3\",\"HourlyRainAmount\":\"0.00\",\"LocalObservationTime\":\"10/14/2011 11:16:07 AM\",\"MonthlyRainAmount\":\"\",\"RelativeHumidity\":\"36\",\"SnowDepth\":\"0.0\",\"SolarRadiation\":\"\",\"SunRise\":\"7:09 AM\",\"SunSet\":\"6:22 PM\",\"TodayRainAmount\":\"0.00\",\"Visibility\":\"6561\",\"WindChill\":\"57.3\",\"WindDirection\":\"2\",\"WindGust\":\"11.4\",\"WindGustDirection\":\"92\",\"WindSpeed\":\"4.9\",\"YearlyRainAmount\":\"22.24\",\"StationTime\":\"10/14/2011 11:15:24 AM\"}]"}
Any suggestions?
Do I need to use a different way than jQuery to consume my JSON?
I should add that my fail alert is sending back 200 success but hitting the error.
Help is much appreciated. Thanks in advance.
Replace eval('(' + data + ')'); with $.parseJSON(data)
Docs: http://api.jquery.com/jQuery.parseJSON/