I'm trying to send a GET request to my localhost via an AJAX call and return the promise object and then play around with it. (The data is coming from a function web service call). I added the following to my web.config file and it seemed to the the 'no get request allowed' error:
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
JS
$(document).ready(function () {
function fetch() {
var data = { firstName: 'd' };
return $.ajax({
url: "../../Service.asmx/GetPersonsByName",
data: JSON.stringify(data),
dataType: "json",
success: function (results) {
console.log(results.d);
},
error: function (xhr, ajaxOptions) {
console.log(xhr);
console.log(ajaxOptions);
}
});
};
fetch().done(function () {
console.log('finished');
}).fail(function () {
//fails
console.log('fails :(');
});
});
With this code I get the error that there's a missing parameter. Web service method for good measure:
[WebMethod]
[ScriptMethod]
public List<Person> GetPersonsByName(string firstName)
{
var personList = new List<Person>();
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spGetPersonsByName", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#firstName", firstName);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Person p = new Person();
p.PersonId = Convert.ToInt32(rdr["PersonId"]);
p.FirstName = rdr["FirstName"].ToString();
p.LastName = rdr["LastName"].ToString();
personList.Add(p);
}
}
}
return personList;
}
The web service works, so what I'm pretty sure is the URL of the webservice that's at fault:
GET http://localhost:58268/Service.asmx/GetPersonsByName?{%22firstName%22:%22d%22} 500 (Internal Server Error).
EDIT: the stored procedure I'm using works.
I tried to append $.param(data) to the URL and that didn't work either. What's the best way to get this working? Should I append the data I want to the URL? Do I need to include it on the AJAX object? I've tried various things with various degrees of non-success and I'm looking for the overarching theme here that I'm not implementing correctly.
Related
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
I want to pass some value to server and it has to return one string.
Jquery version
<script src="js/jquery-3.1.1.js"></script>
Here is my code:
$('#btnSaveFile').click(function () {
var fileName = $('#txtFileName').val();
alert(fileName);
$.ajax({
url: 'ReportTotalSalesPivot.aspx/getFileExistOrNot',
method: 'GET', //method or type ?
contentType: 'application/json',
data: '{fileName:' + fileName +'}', //UPDATED Line
dataType: 'json',
success: function (data) {
alert('success');
alert(data.d.exist);
},
error: function (error) {
alert('fail');
alert(error);
}
});
});
Aspx code
[WebMethod]
public static string getFileExistOrNot(string fileName)
{
string cs = ConfigurationManager.ConnectionStrings["HQWebMatajer13"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandText = "select ReportData FROM [HQWebMatajer].[dbo].[ReportSave] where Userfilename=#UserFileName and ReportName=#ReportName";
cmd.Parameters.AddWithValue("#UserFileName", fileName);
cmd.Parameters.AddWithValue("#ReportName", "TotalSales");
con.Open();
var data = cmd.ExecuteScalar();
if (data != null)
{
string exist = "dataExist";
return exist;
}
else
{
string exist = "notExist";
return exist;
}
}
}
Error Msg
GET http://localhost:55047/ReportTotalSalesPivot.aspx/getFileExistOrNot?fileName:www} 500 (Internal Server Error)
ExceptionType:"System.InvalidOperationException"
Message:"An attempt was made to call the method 'getFileExistOrNot' using a GET request, which is not allowed."
StackTrace:" at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext context)
↵ at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)".
I think this error it occurs in server side. But I don't know what is that
Updated
Error Message:"Invalid web service call, missing value for parameter:'fileName'."
Send your data like below:
In object format
data: { fileName:fileName },
OR
As a String
data = "fileName="+filename;
After one day I found What was my mistake.
This is the answer
data:'{fileName:"'+fileName+'"}'
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:
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, "");
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?