I have the below code in my ASPX page to get some data from a webservice. I cannot use WCF so I am using the ASMX and .Net 3.5. However, what I get back is the yellow ASP.net error page talking about setting the web.config error tag to OFF. If I call my method from code behind and response.write it to the page I get a Json string that I have viewed in JSON Viewer and it parses fine. My issue here is the URL format. What am I doing wrong here. Every example I have found uses the webservice.asmx/Method format. I have also added the protocols to my web.config
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
Page Script:
$.ajax({
type: 'GET',
contentType: "application/json; charset=utf-8",
url: 'http://myserver/mywebservice.asmx/MyMethod',
dataType: 'jsondata',
success: function (msg) {
var table = "<table><tr><th>ID</th><th>Title</th></tr>"
for (var i = 0; i <= msg.length - 1; i++) {
var row = "<tr>";
row += "<td>" + msg[i].ID + "</td>";
row += "<td>" + msg[i].Title + "</td>";
row += "</tr>";
table += row;
}
table += "</table>";
$("#myDiv").html(table);
},
complete: function () {
alert("complete");
}
});
Webservice:
<WebMethod(), ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function MyMethod() As String
'removed for shorter post
End Function
UPDATE: So using the dev tools in Chrome I have found that part of my problem was the server was returning a 403 Forbidden error. After som tweaking I have come up with a partial solution that gives me back my data with json formatting. However, that json formatted text is now wrapped in XML. :-(
I have yet been able to figure out how to get the XML out of my json. Any ideas?
You should have
contentType: "application/json; charset=utf-8",
url: 'http://myserver/mywebservice.asmx/MyMethod',
dataType: 'jsondata',
similar to:
contentType: "application/json",
url: '/folderonmyserver/mywebservice.asmx/MyMethod',
dataType: 'json',
data: "{}", // needed for .Net not to blow up sometimes - or send real data
and in your success: reference msg.d (or have a translation to isolate that for .Net) given your .net version
success: function (msg) {
var mydata = msg.d;
var table = "<table><tr><th>ID</th><th>Title</th></tr>"
for (var i = 0; i <= mydata.length - 1; i++) {
Related
can someone please suggest a better means to accomplish what i'm doing below. The commented out return works in all browsers besides after IE7. I know this is totally ghetto, but this is the only way I've gotten it to work because IE7 can't parse json that I know of. It seems like this is just one thing piling up on top of the other when I use webforms and jquery Validation. I can't get my webservice to reply if the values are in the query string so I have to add rules manually. i.e. /webservices/ipmws.asmx/SiteValid?tbSiteName=WHATEVER.... If that would work perhaps all this wouldn't be required?
Thanks in advance.
$('#form2').validate();
$("#tbSiteName").rules("add", {
remote: function () {
var r = {
url: "/webservices/ipmws.asmx/SiteValid",
type: "POST",
data: "{'tbSiteName': '" + $("#tbSiteName").val() + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) {
var str = data.split(':');
return str[1].substring(0, str[1].length -1)
//return (JSON.parse(data)).d;
}
}
return r;
},
messages: {
remote: "The site code is either not present or invalid."
}
});
Have you tried jQuery's $.parseJSON() method?
http://api.jquery.com/jQuery.parseJSON/
I have an asp.net WebMethod that returns an XmlDocument object.
I can successfully call the method using jquery ajax, but can't seem to get the function to succeed (server side webmethod gets called with correct parameters but client side method fails with 'undefined parser error').
To reproduce, Asp.net C#:
[WebMethod]
public static XmlDocument test(string name)
{
XmlDocument result = new XmlDocument();
XmlElement root = result.CreateElement("Data");
result.AppendChild(root);
XmlElement element = result.CreateElement("AnElement");
element.SetAttribute("Name", name);
root.AppendChild(element);
return result;
}
JavaScript:
function CallForData(name) {
$.ajax({
type: "POST",
url: "AppName.aspx/test",
data: "{'name': " + name+ "'}",
contentType: "application/json; charset=utf-8",
dataType: "xml",
success: function (response) { ParseXML(response); },
error: function (data, textStat, req) { alert(data + ' - ' + textStat + ' - ' + req); }
});
}
If dataType: "xml" is commented out (automatic) the success function is called but the data is a load of square brackets that seem to indicate an empty json structure.
I want an XML response that I can parse using jQuery.
I think I possibly need to add some format identification to the XML document but aren't sure. Can anyone point out the problem?
Fixed by adding
[System.Web.Script.Services.ScriptMethod(ResponseFormat=System.Web.Script.Services.ResponseFormat.Xml)]
to the web method.
Credit to riteshtandon23 in
this thread
I have passed some JSON to my page via a webservice. I used JSON.NET to convert XML to JSON. The JSON output looks ok to me, but I am unable to access some of the items in the response. I am not sure why it is not working. I am using jQuery to read the response and make the webservice call. Even when I try to read the length of the array it says 'undefined'
function GetFeed(){
document.getElementById("marq").innerHTML = '';
$.ajax({
type: "POST",
url: "ticker.asmx/GetStockTicker",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var obj = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
for (var i = 0; i < obj.length; i++) {
$('#marq').html(obj[i].person);
}
}
});
}
This is a copy and paste of my response as it appeared in firebug:
{"d":"{\"?xml\":{\"#version\":\"1.0\",\"#standalone\":\"no\"},\"root\":{\"person\":[{\"#id\":\"1\",\"name\":\"Alan\",\"url\":\"http://www.google.com\"},{\"#id\":\"2\",\"name\":\"Louis\",\"url\":\"http://www.yahoo.com\"}]}}"}
You should be able to read response without calling the ternary operator... anyway if you're trying to iterate over the persons array you should target response.d.root.person object, and not it's parent:
for (var i = 0; i < response.d.root.person.length; i++) {
$('#marq').html(d.root.person[i].name //.url, ...);
}
I know that Jquery's Ajax complete had issue that it's always get called twice when request complete. I'm not sure if that's the case for success.
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)]
I have an ASP.NET application in which i want to post data using jQuery to another page. It means i want post the data of page.
How can i do this with jQuery or AJAX?
Please help me.
$(document).ready(function() {
alert("start");
$("#btnSave").click(function() {
alert("start1");
var aa = 'bb';
var json = "{'ItemName':'" + aa + "'}";
alert("start2");
var ajaxPage = "Default3.aspx?Save=1"; //this page is where data is to be retrieved and processed
alert("start3");
var options = {
type: "POST",
url: ajaxPage,
data: json,
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function(response) {
alert("success: " + response);
},
error: function(msg) { alert("failed: " + msg); }
};
alert("start4");
});
});
I am using this code I am getting all alert response but its posting page.
Jquery and JSON works great with ASP.NET. You can call a code behind method directly from javascript and return complex objects, not just string. (for this example to work you need json2.js found here https://github.com/douglascrockford/JSON-js)
//javascript
function postMethod(text){
var jsonText = JSON.stringify({ name:text });
$.ajax({
type: "POST",
url: "yourpage.aspx/GetPerson",
contentType: "application/json; charset=utf-8",
data: jsonText,
dataType: "json",
success: function(response) {
var person = response.d;
alert(person.Name);
}
});
}
//aspx code behind
[WebMethod]
public static Person GetPerson(string name)
{
Person person = new Person(name);
return person;
}
There is load function.
You may use it like this:
$('#somediv').load('http://someaddress',{key:value}, function callback(){});
Second parameter is important - only written in this way performs post.(if you pass array then it performs get)
PS> This is good when you want to read the data, if you want to just do the POST and don't care about what comes back then you may want to use:
http://docs.jquery.com/Ajax/jQuery.post#urldatacallbacktype
Look at $.post() - http://docs.jquery.com/Ajax/jQuery.post
Add all your relevant data, and post away, handling the response with the supplied callback method.
There is a post function in jQuery:
$.post("test.php", { name: "John", time: "2pm" } );
This is copied directly from the jQuery API, so for more details and examples you can look there.
jQuery api
choose Ajax > Ajax Requests > $.post