jquery ajax posting problems getting null value in alert - asp.net

I'm using xml service to get response but i get null response from service.please help me solve this problem.............
By this service i am sending username and password but both wrong and right is going to succeess part because my service will return nulll value but it will be work fine in POSTMAN.........
<script>
function callXMLConnection() {
alert("call Xml method call");
var un=$("#user").val();
var pw=$("#pwd").val();
var myurl="http://192.162.1.153/EServices/retrieve.aspx";
$.support.cors = true;
$.ajax({
data :"",
type: "POST",
url:myurl,
dataType: "xml",
contentType: "application/xml; charset=utf-8",
crossDomain:true,
success: function(data, textStatus, jqXHR){
alert("text : "+data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("No data found."+jqXHR);
}
});
}
$(document).unbind('pageinit').bind('pageinit', function () {
$("#userInfo").click(function () {
callXMLConnection();
});
});
</script>
this is my get authentication method
Private Sub GenerateXMLPostMethod(ByVal Format As String, ByRef iostream As Stream)
Try
Dim WSCOMMAND As String, TMPSTR As String As String
WS_USERID = Page.Request.Item("username")
WSCOMMAND = Page.Request.Item("command")
Select Case WSCOMMAND
Case "get_authentication"
Application_Error("Responded at:" & System.DateTime.Now)
WSCOMMAND = Page.Request.Item("username")
TMPSTR = Page.Request.Item("password")
DeviceID = Page.Request.Item("deviceid")
TMPSTR = Page.Request.Item("command")&"&username"&Page.Request.Item("username") & "&password"&Page.Request.Item("username")
TMPSTR = Page.Request.Item("password") 'Passowrd
LBFN_GET_USER(WSCOMMAND, TMPSTR, iostream)
End Select
Catch ex As Exception
Application_Error("GenerateXMLPostMethod :" + ex.Message)
End Try

In code there is no data(username, password ) pass to the server, modify the your code, with
data:"" // sending null value
use like this
data:{usename:un,password:pw}
In server page you can get the values from username,password using post method

Related

return json error on asp.net not working

I m trying to test an error in Json notation, via an ajax call. This is my server method
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string publicarError()
{
try
{
throw new Exception("error");
}
catch (Exception ex)
{
Dictionary<string, object> error = new Dictionary<string, object>();
error.Add("success", false);
error.Add("message", "Something really bad happened");
string output = JsonConvert.SerializeObject(error);
return output;
}
}
This is my ajax call
$.ajax({
type: "POST",
url: pageUrl + '/publicarError',
data: '{valor: ' + $('#<%=classroomDropDownList.ClientID%>').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { alert('ok'); },
error: function (xhr, textStatus, exceptionThrown) {
var json = xhr.responseText;
var result = [];
result = eval('(' + json + ')');
var errorMessages = [];
//this ugly loop is because List<> is serialized to an object instead of an array
for (var key in result) {
errorMessages.push(result[key]);
}
$('#result').html(errorMessages.join("<br />"));
},
But when I run the example , it always enter on succes function, and not on the error one.
I dont know why. Is there any mistake?
That's the normal behaviour. You are not returning an error, you are returning a valid JSON object, so it goes to the success function. To go to the error function, you need to throw an exception. Comment out the try ... catch and the throw new Exception("error"); will go to the error function.

javascript post 500 serrver internal error

i'm using ajax and web methods and when i execute this code appear an error thar say
post POST 500 (Internal Server Error)
but this path Exist!!!
this code is i'm using in this moment
function fnSendID() {
$.ajax({
type: "POST",
url: "GMap.aspx/SendCommands",
data: '{IDMobile: "'+$("#<%=Ddl_MobileCustomer.ClientID%>").val()+'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log("Entro : " + response.d);
},
failure: function (response) {
console.log("Fallo : " + response.d);
}
});
<WebMethod()> _
Public Shared Function SendCommands(ByVal IDMobile As String) As String
'iIDMobile = GetMobileID(iIDMobile)
Dim sResponse As String = IDMobile + "Buenas"
Return sResponse
End Function
A 500 means the path you are hitting caused an error on the server side not that the path doesn't exist.
Debug the code and set a breakpoint at Dim sResponse As String = IDMobile + "Buenas".
Does it reach here? Is there any exception before the return?

unknown web method using ajax/jquery

ERROR: unknown web method DoIt Parameter name: methodName
I'm trying to pass a date into a DB Query function backended by VB.NET but am having problems with the webside of things.
var dat = $("#Date").val(); //textbox with a date
$.ajax({
type: "POST",
url: "file.aspx/DoIt",
cache: false,
contentType: "application/json; charset=utf-8",
data: {param:dat},
dataType: "json",
success: function (data, status) {
var response = $.parseJSON(data.d);
alert(response.message);
alert(status);
},
error: function (xmlRequest) {
alert(xmlRequest.status + ' \n\r ' + xmlRequest.statusText + '\n\r' + xmlRequest.responseText);
}
});
The file.aspx.vb file:
(at the end of the file)
<System.Web.Services.WebMethod()> _
Public Function DoIt(ByVal param As String) As String
UpdateDB(param) 'function is above
End Function
I'm just not entirely sure whats going wrong or what it means ;/
Check out this answer. You may need to declare the function as Shared
<System.Web.Services.WebMethod()> _
Public Shared Function DoIt(ByVal param As String) As String
UpdateDB(param) 'function is above
End Function
Something that might be worth checking out is to ensure that your database is setup to receive a datetime datatype.
Also something to try in your web-service declaration:
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
<WebMethod()> _
Public Function DoIt(ByVal param As String) As String
UpdateDB(param) 'function is above
End Function
Reference: webservice - unknown web method parameter name methodname

why does [XMLHttpReequest] Message come?

I am calling below javascript/ajax page method from code behind, then
why does [XMLHttpReequest] Message come?
var options = {
type: "POST",
url: "Test.aspx/SendMessage",
data: "{'toMailAddress':'" + val + "','rno':'" + rno+ "', 'nonrno':'" + nonrno+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var val1 = response.d;
alert(val1);
if (val1 == "1") {
// Below code is used to close the window, if message has been sent to the user sucessfully.
var windowObj = window.self;
windowObj.opener = window.self;
windowObj.close();
}
},
error: function (result) {
alert("Error in " + result);
}
};
$.ajax(options);
I expect the message you are in fact seeing is "Error in XMLHttpRequest". This is what you would see if an error occurred during the call, because you have the wrong arguments for the error call back.
The method signature for the jQuery ajax error callback is:
error(XMLHttpRequest, textStatus, errorThrown)
So your error alert is being passed the XMLHttpRequest object, which is probably not what you meant to do. The code implicitly calls the toString() method on the XMLHttpRequest which will return "[object XMLHttpRequest]".
If that message isn't coming from the error callback, then there must be another bit of code somewhere passing the XMLHttpRequest object to alert(). I suggest you set a break point after your own alert() and single step through to see where the other alert() is.

Calling Linq to SQL method in Web service with jQuery

I have a test web service called: MySimpleService.svc with a method called:GetUserNamesByInitials. below is the Linq to SQL code:
[OperationContract]
public static string GetUserNamesByInitials(string initials)
{
string result = "";
//obtain the data source
var testDB = new TestDBDataContext();
//create the query
var query = from c in testDB.TestTables
where c.initials == initials
select c;
//execute the query
foreach (var c in query)
{
result = result + c.full_name;
}
return result;
}
I have used that code in page behind and it works well. However when i try to call it using jQuery I don't get any result, no errors nothing. below is the code i use in jQuery:
$('#TextBox3').live('keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
//call function here
$.ajax({
type: "POST",
url: "/MySimpleService.svc/GetUserNamesByInitials",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"word":"' + $('#TextBox3').val() + '"}',
success: function(data) {
$('#TextBox4').val(data.d);
}
});
}
});
});
what I do is to type the user id in one textbox (TextBox3) and when I press the Tab key the result is shown in another textbox (TextBox4).
The jQuery call works well with other methods that do not call the database, for example using this other web service method it works:
[OperationContract]
public string ParameterizedConnectionTest(string word)
{
return string.Format("You entered the word: {0}", word);
}
However with the Linq method it just does not work. Maybe i am doing something wrong? thank you in advance.
The web service is expecting a string named "initials" and you're sending it a string called "word". More than likely it is throwing an exception that it's not being passed the expected parameter.
Try adding an error: function() in your $.ajax() call to catch the error. I would also suggest installing FireBug or Fiddler to be able to view and debug the AJAX request and response. Here's the updated $.ajax() call with the right parameter name and an error function which should invoke your chosen javascript debugger if you have it open:
$.ajax({
type: "POST",
url: "/MySimpleService.svc/GetUserNamesByInitials",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{"initials":"' + $('#TextBox3').val() + '"}',
success: function(data) {
$('#TextBox4').val(data.d);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error!');
debugger; // Will let you see the response in FireBug, IE8 debugger, etc.
}
});
Update
So I just noticed that you're using WCF services instead of normal ASP.Net (ASMX) services... Some additional suggestions:
Enable IncludeExceptionDetailInFaults in your web.config so that you can debug any errors happening. ASP.Net services will return an error by default but you need to explicitly turn this on for WCF.
Try adding an additional attribute below your [OperationContract] attribute to specify you're expecting a post with JSON data:
[WebInvoke(Method = "POST",BodyStyle=WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]

Resources