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.
Related
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++) {
I have in my .js file a function that call a webservices method called getStudents:
[WebMethod(Description = "white student list")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Job> getStudents(long classId)
{
return (new classManager()).getStudents(classId);
}
the method is callled like:
function loadStudents() {
var parameters = JSON.stringify({ 'classId': 0 });
alert(parameters);
$("#ProcessingDiv").show('fast', function() {
$.ajax({
type: "POST",
url: "myWebService.asmx/getStudents",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$("#ProcessingDiv").hide();
var students= response.d;
alert('yes');
},
error: function(request, status, error) {
alert(request.responseText);
}
,
failure: function(msg) {
alert('somethin went wrong' + msg);
}
});
});
}
$(document).ready(function() {
loadStudents();
});
when i debug,the service web method is executed successfully but i don't get my alert('yes') and neither msg error.
What's wrong?
If you're returning (serialized to JSON) List of objects, then in response you will get JS array of JS objects, so (assuming Job has property p) try response[0].p for p value from first element.
note: I don't know ASP.NET, so maybe response is serialized in another way, thats where tools like Firebug (or other browsers Dev tools) are extremely useful - because you can look how exactly you'r http requests and responses looks like.
ps. And change alert to console.log and look for logs in Firebug console - its better than alert in many, many ways ;]
I've got a jqGrid setup to post to a URL using the content type of application/json:
$("#jqCategoryGrid").jqGrid({
datatype: "json",
mtype: 'POST',
url: "Webservices/TroubleTicketCategory.asmx/getCategoryData",
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
// **UPDATE - This is the fix, as per Oleg's response**
serializeGridData: function (postData) {
if (postData.searchField === undefined) postData.searchField = null;
if (postData.searchString === undefined) postData.searchString = null;
if (postData.searchOper === undefined) postData.searchOper = null;
//if (postData.filters === undefined) postData.filters = null;
return JSON.stringify(postData);
},
});
The problem is that the jqGrid is still trying to pass parameters using a non-json format so I'm getting an error "Invalid JSON Primitive"
Is there a way to instruct the jqGrid to serialize the data using Json?
Thanks
UPDATE
I edited the provided source code in my question to include the fix I used, which came from Oleg's response below.
You should include JSON serialization of the posted data for example with respect of json2.js which can be downloaded from http://www.json.org/js.html:
serializeRowData: function (data) { return JSON.stringify(data); }
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