I have an MVC 3 web app that has an Action which I need to access from a webform app via javascript.
My action returns a Json result, which I have checked works just fine. However, when accessing it with javascript from another application, I can see it reaching my action, doing all the work, returning my data, but the jquery function then gives me an error 200 and no data.
Example:
My MVC Action:
public ActionResult GetData(int categoryId)
{
var listofSeries = new List<string>
{
"foo1",
"foo2",
"foo3"
};
return Json(listofSeries, JsonRequestBehavior.AllowGet);
}
This returns me: ["foo1","foo2","foo3"]
Normally, my javascript function is used to query a database and get data back for a Highcharts chart but I have the same issue with this kind of example.
<script type="text/javascript">
$(document).ready(function () {
var foo = getData(9);
});
function getData(categoryId) {
var results;
$.ajax({
type: 'POST',
url: 'http://localhost:xxxx/Home/GetData',
//contentType: "application/json; charset=utf-8;",
async: false,
data: { "categoryId": categoryId },
dataType: "json",
success: function (data) {
console.log("results: " + data);
results = data;
}
});
return results;
}
</script>
With this I get:
http://localhost:63418/Home/GetData?categoryId=9 200 OK
results: null
If I add the contentType, I can't even see the function running in the firebug console, all I see is results: null. When I remove it I do but I get the error above.
I've been told it might not be doable because of "Cross-site scripting". And to instead have my javascript function call a webservice (or handler but I haven't quite figured out how to make one of those yet) that will then call my action, return my data to the service who then returns the data to the javascript.
But now I'm getting a 415 Unsupported Media Type error message when trying to connect to my webservice.
My IWebService.cs:
[ServiceContract]
public interface IWebService
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, Method = "POST")]
void GetData(int mileId);
}
My WebService.svc:
public void GetData(int categoryId)
{
string url = "http://localhost:63418/Home/GetWoWData?categoryId=" + categoryId;
WebRequest wr = WebRequest.Create(url);
WebResponse response = wr.GetResponse();
}
I'm not returning anything yet, it won't even go in this function. Giving me the 415 error message.
If I change the contentType to "text/xml" I get an error 400.
I would really like to have this work without using the webservice, and figure why I get an error 200 OK when I can see the action running, but if that's not possible, any idea why the webservice isn't working?
Thanks.
string url = "http://localhost:63418/Home/GetWoWData?categoryId=" + categoryId;
WebRequest wr = WebRequest.Create(url);
wr.Credentials = CredentialCache.DefaultNetworkCredentials; // uses current windows user
var response = (HttpWebResponse)wr.GetResponse();
I only just remembered I had this post and found the solution a while ago. It was solved by adding the credentials (in my case the current windows user) and getting the response as an HttpWebResponse.
200 makes me think everything is working ok, but IE is using a cached result, i've run into this problem before with IE. try adding:
$.ajaxSetup({
// Disable caching of AJAX responses */
cache: false
});
this will make it append a random parameter, and will stop IE from being stupid.
Related
I am learning JS, jquery, and trying to build a login page and after giving the credentials to my application URL I should get a response back and I should be able to perform actions accordingly.
Something like: if the response is "success" then I should get an alert for success and redirect to another page (not sure how to do that) and if the response is "fail" I should throw an alert.
Below is the relevant snippet from my js file:
$.ajax({
url: "http://localhost:8588/api/userLogin",
type: "POST",
data: credentials,
dataType: "json",
contentType: 'application/json',
success: function(response) {
alert(response);
}
});
And my java controller method snipped annotated with #RestController:
#PostMapping(value = "/userLogin", consumes = "application/json")
public String userLogin(#RequestBody UserRequest userRequest) {
System.out.println(userRequest.getUserId()+ " "+ userRequest.getPassword());
User user = userService.getUser(userRequest);
return (user != null) ? "succeess" : "fail";
}
I am not getting any error
I am able to call the API but not getting the response back on UI. What am I missing?
I've taken your code and simulated simple case like yours. Most of the code looks right but as you've said there are no errors in the console and no response to client so there's problem got to be somewhere. There are certain things you've not specified here, so for more context for other people I am assuming UserRequest as
public class UserRequest {
public String username;
public String password;
}
and for the ajax request data I'm using
JSON.stringify({username: "developer", password:"pass"})
Now, I'm getting 200 response code with success message in alert at client side. Let me know if any error pops up after trying this.
[HttpDelete]
public ActionResult DeleteCustomer(int id)
{
var cus = customerContext.Customers.Find();
customerContext.Customers.Remove(cus);
customerContext.SaveChanges();
return null;
}
Above is my controller code for delete click event. Below is my js file. Call ajax to do delete action. But when I click delete button, it always pop-up a "Not Found" dialog. I have no idea what happened in the front end or back end. So sad. Need help, please. Thank you.
self.deleteCustomer = function () {
$.ajax({
type: "DELETE",
url: "../Customer/DeleteCustomer/",
data: { id: self.cusId() },
success: function (result) {
alert("Deleted!");
GetCustomers();
$('#AddCustomer').modal('hide');
},
error: function (error) {
alert(error.statusText);
}
});
}
For what you have posted it seems like you are using a path instead of a "url" in the url property. Try to use url: "/Customer/DeleteCustomer", instead of url: "../Customer/DeleteCustomer/",. If it still doesn´t work open chrome development tools and sniff the network to see where (url) it is sending the request.
To check if your roting is correct (in backend), you can install Postman (chrome plugin) and send a DELETE request and verify if the controller receives the request.
Regards.
I'm using WCF and I am getting this error.
If I use jQuery1.14.1 I get
Type error: s.type.ToUpperCase is not a function
type = s.type.ToUpperCase();
If I use jQuery 1.12.1 locally the service gets called corrctly. However, if I try it on the server, 1.14.1 get the error above, but 1.12 i get this one:
Type error: l.type.ToUpperCase() is not a function
..+&&n.event.trigger("ajaxStart"),l.type=l.type.ToUpperCase(), l,hasContent=!Kb.tes....
Relevant code:
var Type = "POST";
var DataType = "jsonp";
var ProcessData = true;
var ContentType = "application/json; charset=utf-8";
var params = {
user: $("#userid_hidden").val().toString(),
permission: $("#permission_id_" + i).val().toString(),
enabled: true,
note: $("#permission_note_" + i).val(),
write: $("#permission_write_" + i).is(":checked")
}
SetPermission(params);
function SetPermission(params) {
//alert('setting permission');
if (params.enabled)
CallService('wsEnablePermissionJSON', params);
else
CallService('wsDisablePermissionJSON', params);
}
function CallService(wsName, params) { //Generic function to call WCF Service
alert('calling service');
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url + wsName, // Location of the service
data: JSON.stringify(params),
/*data: JSON.stringify(params), //Data sent to server*/
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function(msg) { //On Successful service call
ServiceSucceeded(msg, wsName);
},
error: ServiceFailed // When Service call fails
});
alert('service called');
}
I can't see the rest of the error because the page is then reloaded, I got those by taking a screenshot.
I don't know how to go about this, I've tried jQuery 2 and I get the first error. I've used the same ajax call with another wcf service and it's currently working fine (the only difference is that the working one uses jQuery 1.12, and that solved it locally, in the server the new one fails.)
Both pages are in the same server.
I've been trying to figure this out for most of the day, but I haven't found anything, at first I thought that using 1.12 would solve it.
I googled the error but all the results were for different cases, I didn't see anything for the $ajax call.
This was happening pecause the name of the variable Type
var Type = "POST";
I didn't think to change it before, because as I've said before I have another web app very similar, and with exactly the same ajax call working fine, and that code I got from an example somewhere.
Changing it to
var Requestype = "POST";
took care of the error
I ran into the same error, but for a different reason. I was accidentally passing the value true in the type property, instead of a POST.
If it contains any value other than the accepted verbs. Remember that it defaults to GET, if none provided.
Hope this helps somebody.
I have a javascript array that holds a couple of ids. I want to send it to a rest webservice that I have written. Here is the code that I have for that -
$.ajax({
type : 'GET',
url : 'http://localhost:portNo/GlassdoorWebProject/index/getJobsData/list/',
crossDomain : true,
data : JSON.stringify(allIds),
contentType: "application/json",
success : function(data){
alert("success in call2");
},
error : function(XMLHttpRequest,textStatus, errorThrown) {
alert("error");
}
});
When I execute this code I am getting an alert box that says error. This is how the method in my web service looks like -
#RequestMapping(value = "/getJobsData/list/{ids}", method = RequestMethod.GET)
public List<JobDetails> getJobs(#PathVariable("ids") String jobIds) {
System.out.println("ids"+jobIds);
return jobService.getJobDataForIds(jobIds);
}
When I run the it in a browser with the url in the browser it works. But when I run it through the code it does not work. Any suggestions?
Use this code snippet
#RequestMapping(value = "/getJobsData/list/", method = RequestMethod.GET)
public List<JobDetails> getJobs(#RequestParam("ids") String jobIds) {
System.out.println("ids"+jobIds);
return jobService.getJobDataForIds(jobIds);
}
the main problem is that you are sending the ids as the request parameters, but your are looking the values from the url. So i changed the code of your web service and i think it will solve your problem.
In fact, I have a JavaScript application (jQuery) that is sending a request to a Java function which is supposed to send back data (success case) to my ajax function.
In the success case, I go on with my application; in error case, I stop my procedures and display the error message to the user.
But when the Java code takes more than 5 minutes to send a response to my Ajax call, this one (ajax code) doesn't (work / respond / go on /) get any response anymore ...
I tried setting up a timeout limit to 600000 ms (so 10 minutes) but I still get the same problem (and ain't got any error messages or output, which could have been helping me).
So if anyone's got an idea on the source of this problem, I'd be grateful.
Here is some piece of code if it may make it clearer :
JSP
$(document).ready(function() {
/* performing some layout changes */
//
preValidationDisplay();
}
function preValidationDisplay() {
/* performing some layout changes */
setTimeout("getValidationResult()", 500);
}
function checkReadLogFile() {
$.ajax({
url: logFileUrl,
cache: false,
success: function(result)
{
$("#progressBarToResize").width(
'' + parseFloat(result.trim()) + '%' );
}
});
}
function getValidationResult()
{
var timer = setInterval("checkReadLogFile()", 1000);
$.ajax({
url: '<s:url value="doValidation"/>',
type: "GET",
cache: false,
dataType: "json",
async: true,
//timeout : 600000,
success: function(result, status)
{
// Do something
},
error: function(jqXHR, status, errorStr){
// Do something
}
});
}
java
#RequestMapping(value = "/doValidation", method = RequestMethod.GET)
public String processValidationResults(HttpServletRequest request, HttpServletResponse response,
#RequestHeader("Connection") String conn) {
ValidationResult validationResult = null;
JSONObject resultJson = new JSONObject();
HttpSession session = request.getSession();
JSONObject progressMap = (JSONObject) session.getAttribute("progressMap");
String uploadedFilePath = progressMap.getString("filePath");
String realMimeType = progressMap.getString("realMimeType");
long fileSize = progressMap.getLong("fileSize");
String ctxPath = request.getContextPath();
// INVOKE the VALIDATION ENGINE
try {
validationResult = validationEngineService.getValidationResult(uploadedFilePath, ctxPath);
resultJson = JSONObject.fromObject(validationResult);
} catch (Exception e) {
validationResult = null;
resultJson.put("errorMsg", e.toString());
}
try {
response.getWriter().print(resultJson);
response.flushBuffer();
} catch (Exception e) {
}
return null;
}
When you're working with HTTP, never expect a connection to take longer than half a minute.
Either use WebSockets or Comet (long polling).
See, there are many parties that might decide to stop your connection:
web browser, firewall/router/isp, web server (eg: Apache), server scripting language (eg: PHP)
The only time I disable this on the PHP side is when I want PHP to keep running even after the user stopped the connection (which, by the way, I have enable yet another setting).
Without some code, i'm not sure if i could help much but have you tried checking which event is triggering the ajax call? I made a silly mistake once by sending an ajax request on keydown, i later found out that instead of keydown , i needed to use keyup since thats the event triggered once the value of the textbox is set to the text + key recently entered.
So you could try a keyup or change the event in jQuery. If this is on localhost, its not a good sign....first determine whats causing the problem, the frontend or backend.
Things to do:
1) Change event type in jQuery
$("#elem").live("keyup",function() {//send req});
2) Check apache log. If your on ubuntu or something similar, you can go to /var/log/apache2/error.log