Can't connect to web service by JQuery - javascript

I use jquery (ajax) to connect to a web service which returns string , it is not working with me. it always go to error function. here is my web service :
[HttpGet]
[ActionName("GetImage")]
public string GetImage(string base64String, string imgName,string reqTitle , string reqSubject, string reqStatus,string Creator , DateTime creationdate )
{
try
{
using (PhMobAppEntities context = new PhMobAppEntities())
{
ClaimsApproval _ca = new ClaimsApproval();
_ca.imageBasestrg = base64String;
_ca.imageName = imgName;
_ca.Creator = Creator;
_ca.CreationTime = creationdate;
_ca.ReqStatus = reqStatus;
_ca.ReqTitle = reqTitle;
_ca.ReqSubject = reqSubject;
context.ClaimsApprovals.Add(_ca);
context.SaveChanges();
return "Success";
}
}
catch (DbEntityValidationException ex)
{
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
var fullErrorMessage = string.Join("; ", errorMessages);
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
and here is my js code :
$("#sendphoto").click(function () {
var url = "http://41.128.183.109:1212/api/Data/GetImage";
var data = {
imgName: "test"
};
$.ajax({
url: url,
type: 'Get',
data: data,
success: function (data) {
alert("Success");
},
error: function (data) {
alert("Please Check Your Internet Connection");
}
});
});
It is running ok when i tested my web service in advanced rest client ,please advice .

I tried connecting to your web service and I get the following response:
{"$id":"1","Message":"No HTTP resource was found that matches the request URI 'http://41.128.183.109:1212/api/Data/GetImage'."}
I think what you have is an internal problem with your c# code, probably with your routing. Your javascript call is probably working fine, but you are passing only one parameter, "test" while you have many more in your declaration.
What http response code are you getting?

Related

Spring Web Application Returning 405 error on PUT Call

I have a Java Spring web application that creates a list of roles that can be assigned to users. However, I am having an issue creating new roles which is invoked through an AJAX PUT call that returns a 405 error. The application is running on Java 8 and Spring 5.1.1.
I have tried debugging both the front end and back end side. What I found was, the call successfully reaches the back-end, processes the call through and returns. However, the front-end will claim that an error occurred and returns a 405 error. But the issue is, the error does not provide any details on what is failing exactly. The most information I could find was this message:
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
at Function.invokeGetter (<anonymous>:2:14)
at Object.error (http://localhost:8000/xxx/admin-user-search.html:1011:10)
at fire (http://localhost:8000/xxxx/webjars/jquery/3.1.1/jquery.js:3305:31)
at Object.fireWith [as rejectWith] (http://localhost:8000/xxxx/webjars/jquery/3.1.1/jquery.js:3435:7)
at done (http://localhost:8000/xxxx/webjars/jquery/3.1.1/jquery.js:9244:14)
at XMLHttpRequest.<anonymous> (http://localhost:8000/xxxx/webjars/jquery/3.1.1/jquery.js:9484:9)
Javascript:
function submitCreateNewRole(){
isBlank = false;
var myData;
newRoleName = $('#modalUserRoleSearchText').val();
newRoleDescription = $('#modelUserRoleDescText').val();
if (newRoleName=='' || newRoleDescription==''){
isBlank = true;
}
if (isBlank){
appAPI.setErrorBannerRole("Blank data is not allowed. Please enter non-blank data to create new Role.");
} else {
var UserRoleSearchModel = {};
var userRoleAction = "createNewUserRole" ;
RoleModel.ldapName = newRoleName;
RoleModel.roleDesc = newRoleDescription;
var token = $("meta[name='_csrf']").attr("content");
var URL = "json/admin-user-search?userRoleAction=" + userRoleAction + "&roleName=" + newRoleName + "&roleDesc=" + newRoleDescription;
var req = JSON.stringify(RoleModel);
var jqxhr = $.ajax({
type: "PUT",
url: URL,
headers: { "X-CSRF-TOKEN" : token },
data: req,
contentType: "application/json",
error: function (xhr, status, error) {
console.log("Failure caught");
console.log(xhr.responseText);
},
success: function(data){
myData = data;
}
}).done(function( msg ) {
$('#alertMessageSuccess').val('Successfully create new row');
}).fail(function(jqxhr) {
$('#alertMessageError').val('failed to create role' + newRoleName);
});
}
return myData;
}
Java Spring:
#RequestMapping(value = {
"admin-user-search"
}, method = RequestMethod.PUT)
public ModelAndView createNewUserRole(#AuthenticationPrincipal Principal principal,
#RequestParam(required = false) String pageCommand,
#ModelAttribute("UserModel") UserModel userSearch,
#ModelAttribute("RoleModel") RoleModel userRoleSearch,
#RequestParam(value = "roleName", required = false) String roleName,
#RequestParam(value = "roleDesc", required = false) String roleDesc,
#RequestParam(value = "userRoleAction", required = false) String userRoleCommmand, HttpServletRequest request) {
Results results = null;
List<Role> roleVOs = null;
String roleResponseMessage;
ModelAndView rView = new ModelAndView("admin-user-search");
if ("createNewUserRole".equals(userRoleCommmand)) {
userRoleSearch.clearAlertMessages();
userSearch.clearAlertMessage();
if ("".equals(roleName)) {
roleResponseMessage = "Unable to create a new role due to invalid or blank LDAP username enterred. Please try again with valid LDAP username.";
userRoleSearch.setErrorMessages(roleResponseMessage);
} else if ("".equals(roleDesc)) {
roleResponseMessage = "Unable to create a new role due to invalid or blank Role Description entered.";
userRoleSearch.setErrorMessages(roleResponseMessage);
} else {
try {
this.tdmcRoleDao.addNewRole(roleName, roleDesc);
roleResponseMessage = String.format("New user role '%s' has been added.", userRoleSearch.getLdapDn());
userRoleSearch.setSuccessMessages(roleResponseMessage);
userSearch.setSuccessMessages(roleResponseMessage);
roleVOs = retrieveAllRoles();
} catch (final SQLException e) {
LOGGER.error(e, TDMCMessages.TDMC_0142_DATABASE_INSERT_EXCEPTION, "tdmcRoleDao.addNewRole(newRoleLdap)");
roleResponseMessage = "Unable to create a new role -'%s' due to DB problem. Please retry with a new valid role name.";
userRoleSearch.setErrorMessages(roleResponseMessage);
userSearch.setErrorMessages(roleResponseMessage);
} catch (final DuplicateKeyException dupEx) {
roleResponseMessage = "Unable to create a duplicate role'. Please retry with non-duplicated role name.";
userRoleSearch.setErrorMessages(roleResponseMessage);
userSearch.setErrorMessages(roleResponseMessage);
}
if (roleVOs != null && !roleVOs.isEmpty()) {
results = populateRolesToResults(roleVOs);
}
userRoleSearch.setResults(results);
userRoleSearch.setSelected(roleVOs);
rView.addObject("RoleModel", userRoleSearch);
}
}
return rView;
}
When I run the application and try to create a new Role, I see that the PUT call reaches the Java server and successfully returns the view. However, on the Web client side, it throws the 405 error, and it's not clear what exactly is failing. Any insight would be very helpful.
On another note, the application also makes POST and GET calls as well, but those seem to work fine, so I cannot understand why the PUT calls are failing in this case.
EDIT: Fix code
first of all your url seems to be wrong, please check.
and change to post mapping, then post through body, something
like #requesrbody

Function not returning data when called by JavaScript

Whilst debugging, using Unit Tests, the function returns the expected data, however when the same function is called from JavaScript, the function is hit but then doesn't return any data.
This function that I'm calling that's in the dll is hanging, but only when it is called by a function that has been called by a JS request, why would this be?
EDIT:
As in comments, my best guess is that it is something to do with a thread being in use, but I don't know, as the function itself is working, just not when called from a C# function called by AJAX.
AJAX call :
function getOnHoldTickets() {
$.ajax({
type: "GET",
url: "/cloud/getTicketCount/",
dataType: "json",
success: function (data) {
onHoldHandler(data);
},
failure: function () {
alert("getOnHoldTickets failled");
}
});
}
Controller :
// api gets hit from the JS call
[Route("cloud/getTicketCount")]
public List<UberTicket> getTicketCount()
{
var tickets = Dashboard.getTODTickets("On Hold");
return tickets;
}
[TestMethod] // calls the same method as JS
public void supportTicketTesting()
{
var openTickets = Dashboard.getTODTickets("On Hold");
var check = openTickets != null;
}
// method calling the dll
public static List<UberTicket> getTODTickets(string type)
{
var tickets = UberAPI.getTODTickets(type);
return tickets;
}
DLL Method:
// the method within the dll that's hanging when called by a function invoked by JS
public static async Task<RootObjectClass<T>> genericGet<T>(string function, string parameters)
{
try
{
// create credentials to pass to httpClient
var httpClientCredentials = new HttpClientHandler()
{
Credentials = new NetworkCredential(uberAPIUser, uberAPIPass)
};
using (var client = new HttpClient(httpClientCredentials))
{
// unsure if the headers are being passed in correctly - getting good response though
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
var response = await client.GetAsync(ubersmithURL + function + parameters);
var result = await response.Content.ReadAsStringAsync();
// remove nulls from json
result = Regex.Replace(result, ":null,", ":\"\",");
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var success = JsonConvert.DeserializeObject<RootObjectClass<T>>(result);
return success;
}
}
catch(Exception ex)
{
// log error
}
return new RootObjectClass<T>();
}
While this might not be addressing the issue fully, you should not be returning C# Data types as JavaScript won't be able to parse them and will result in an error similar to this in the worst case
System.Collections.Generic.List`1[...]
Like I said in my comment, you should return a JsonResult from your controller to retrieve the data in JS.
[Route("cloud/getTicketCount")]
public JsonResult getTicketCount()
{
var tickets = Dashboard.getTODTickets("On Hold");
return Json(tickets ,JsonRequestBehavior.AllowGet);
}
Understanding JsonRequestBehavior.AllowGet
and your Ajax call
$.ajax({
type: "GET",
url: "/cloud/getTicketCount/",
dataType: "json"
})
.done(function(data){
console.log(data);
})
.fail(function(xhr){
console.log(xhr.responseText);
});
Edit:
I believe this is a deadlock issue you have. Perfect answer elaborating the issue is here.

AngularJS Services call .asmx webservice - TypeError: Cannot convert object to primitive value

I am very sorry to ask this question. I am very sorry if my question is not clear. I am trying to call .asmx webservice from my AngularJS Services.
In my AngularJS Services, I have the following code snippet:
.factory('BoothDesignatedCoordsService', ['$http',function ($http) {
return {
// Might retrieved from db eventually
fnGetBoothDesignatedCoords: function (strBoothName, intFloorPlanID) {
try
{
var JSONObj = {
BoothName: strBoothName,
FloorPlanID: intFloorPlanID
};
var sendToWS = JSON.stringify(JSONObj)
}
catch(e)
{
alert("error from fnGetBoothDesignatedCoords " + e)
}
$http.post('http://localhost:4951/wsIPS.asmx?op=fnGetBoothDesignatedCoords', sendToWS).then(function (response) {
if (response.data)
alert("Post Data Submitted Successfully!");
}, function (response) {
alert("Service not Exists");
alert(response.status);
alert(response.statusText);
alert(response.headers());
});
}
}
}])
In my .asmx file, I have the following code snippet:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true)]
public void fnGetBoothDesignatedCoords(string objJSONRequest)
{
wsIPS objRequest = JsonConvert.DeserializeObject<wsIPS>(objJSONRequest);
string strBoothName = objRequest.ClientBoothName;
string strFloorPlanID = objRequest.ClientFloorPlanID;
int intFloorPlanID = int.Parse(strFloorPlanID.ToString());
double[] arrBoothDesignatedCoords = new double[0];
string strConnectionString = ConfigurationManager.ConnectionStrings["IPSConnection"].ConnectionString;
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "SELECT DesignatedCoords FROM Booth WHERE Name = #Name AND FloorPlanID = #FloorPlanID";
SqlCommand selectCmd = new SqlCommand(strCommandText, myConnect);
selectCmd.Parameters.AddWithValue("#Name", strBoothName);
selectCmd.Parameters.AddWithValue("#FloorPlanID", intFloorPlanID);
myConnect.Open();
SqlDataReader reader = selectCmd.ExecuteReader();
if (reader.Read())
{
string strBoothDesignatedCoords = reader["DesignatedCoords"].ToString();
arrBoothDesignatedCoords = Array.ConvertAll(strBoothDesignatedCoords.Split(','), double.Parse);
}
myConnect.Close();
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(arrBoothDesignatedCoords));
}
}
}
Note : my .asmx web service is running, so I can use the url to access it directly on my local computer.
However, I receive alert error that say "service not exists", and the error code is 500, and it is internal server error. And the console log gives me this error: TypeError: Cannot convert object to primitive value. Can someone please help me?
This is the screenshot of my .asmx webservice and its url:

Getting rid of irrelevant console errors (404 (Not Found))

I have a simple program that is scraping a web site for some items. I am using Angular $http service to call the below C# method to get the markup from the page and then handling everything else with JS. Everything is working perfectly fine with the exception of a minor annoyance: a bunch of 404 errors.
The 404 errors are being displayed in the developer tools once the http get call completes. It's almost like the javascript is trying to interpret the HTML and then fails on all the get requests for the images in the browser:
What I'm trying to figure out is how to get the 404 errors to go away or fail silently (not display in the console). I'm not finding anything in my research but am assuming there is some way to handle this whether it be on the server or client side
C#
public static string GetPageSource()
{
JObject result = new JObject();
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://awebpage.html");
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
result["data"] = reader.ReadToEnd();
result["success"] = true;
reader.Close();
response.Close();
}
catch (Exception ex)
{
result["data"] = ex.Message;
result["success"] = false;
}
return JsonConvert.SerializeObject(result);
}
JS
$scope.getPageSource = function () {
var ajaxProcessor = Utils.ajaxMessage('Scraping Beer Menu From Source');
ajaxProcessor.start();
$http({
method: 'POST',
url: 'AJAX/MenuHandler.aspx/GetPageSource',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: {}
}).then(function (response) {
ajaxProcessor.stop();
var result = $.parseJSON(response.data.d);
if (result.success === false) {
Utils.showMessage('error', result.data);
} else {
var beerMenu = new BeerMenu(result.data, $scope.loggedInUser, function (beerMenu) {
$scope.buildDisplayMenu(beerMenu);
});
}
}, function (err) {
ajaxProcessor.stop();
console.log(err);
Utils.showMessage('error', err.data.Message);
});
};
UPDATE
Thanks to #dandavis, my issue is narrowed down to calling $.parseHTML within the buildDisplayMenu function (which calls buildCurrentMenu). Is there anyway to make it ignore the images or any get request?
buildCurrentMenu: function () {
var html = $.parseHTML(this.pageSource);
var menuDiv = $(html).find('.TabbedPanelsContent')[0];
var categories = $(menuDiv).find('h2');
var categegoryItems = [];
var beerArray = [];
for (var i = 0; i < categories.length; i++) {
...
}
return beerArray;
}
The resolution is to remove any img tags (or any other tag that should be ignored) from the page source before calling $.parseHTML
this.pageSource = this.pageSource.replace(/<img[^>]*>/g, "");

.net mvc 4 application - call from ajax to a function in controller

I'm creating mvc 4 application where I call a function in controller from a js file using ajax.
When I call the function from ajax, its calling the respective function properly. But neither success nor error function is not firing . Could someone help me out to correct my mistake?
I would like to read the data from database convert it to json format and write it into a .js file and thereafter success function to be fired off. Help me to solve this. Thanks in advance.
Here is my Code.
$.ajax({
//url: '#Url.Action("getJsonData","Home")',
url: "Home/getJsonHugeData1",
//data: "{}",
type: "GET",
//contentType: 'application/json',
//dataType: "json",
success: function () {
alert();
alert('success getJsonHugeData');
loaddata(data);
},
error:function(){
alert('error');
}
});
Controller:
public JsonResult getJsonHugeData()
{
var users = GetUsersHugeData();
string json = "var dataSource=";
json += JsonConvert.SerializeObject(users.ToArray());
System.IO.File.WriteAllText(Server.MapPath("/Scripts/NewData.js"), json);
return Json(users, JsonRequestBehavior.AllowGet);
}
private List<UserModel> GetUsersHugeData()
{
var usersList = new List<UserModel>();
UserModel user;
List<dummyData> data = new List<dummyData>();
using (Database1Entities dataEntity = new Database1Entities())
{
data = dataEntity.dummyDatas.ToList();
}
for (int i = 0; i < data.Count; i++)
{
user = new UserModel
{
ID = data[i].Id,
ProductName = data[i].ProductName,
Revenue = data[i].Revenue,
InYear = data[i].InYear.Year
};
usersList.Add(user);
}
}
I believe your browser will block the file downloaded via ajax, this is because JavaScript cannot interact with disk. If you want to get this working, you will have to do so using a form post.
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "DownloadForm" }))
{
... form data would be here if you had any...
<button type="submit">Download</button>
}
You would then return a FileStreamResult with the contents of the file to be downloaded.
public ActionResult Action(FormModel model)
{
// Do work to get data for file and then return your file result to the browser.
return new FileStreamResult(new MemoryStream(fileData), "text/csv") // set the document type that is valid for your file
{
FileDownloadName = "users.csv"
};
}
I ran all of your code except for the following since you didn't provide the UserModel and dummydata classes in your question:
private List<UserModel> GetUsersHugeData()
{
var usersList = new List<UserModel>();
UserModel user;
List<dummyData> data = new List<dummyData>();
using (Database1Entities dataEntity = new Database1Entities())
{
data = dataEntity.dummyDatas.ToList();
}
for (int i = 0; i < data.Count; i++)
{
user = new UserModel
{
ID = data[i].Id,
ProductName = data[i].ProductName,
Revenue = data[i].Revenue,
InYear = data[i].InYear.Year
};
usersList.Add(user);
}
}
The end result was that you had a typo in your ajax 'url' parameter. Also, if you are going to check for errors, set your function to
function(jqxhr, status, error) {
alert(error);
}
to check the error being thrown.

Categories