I have a asp.net webservice, which is pulling some data from my database, and outputting this JSON string:
{
"NumberOfCustomers": 15,
"Customer": [
{
"CusID": "1",
"FirstName": "Ina",
"LastName": "Williamson"
},
{
"CusID": "2",
"FirstName": "Hyacinth",
"LastName": "Brady"
},
{
"CusID": "3",
"FirstName": "Coby",
"LastName": "Shannon"
}
]
}
I then try to use jQuery to display each of the customers, but i can't get it working. The purpose for this, is to use the data as a suggestion to a search field, that updates for each character written.
function FinalTest() {
$.ajax({
type: "POST",
url: "http://localhost:12724/VetWebservice.asmx/GetCustomer",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
glb = data; //variable for inspecting in Chrome
$("#testdiv3").html(data.d.NumberOfCustomers);
$.each(data.d.Customer, function () {
$("#testdiv3").append(this.CusID + ", ");
});
}
});
};
Giving me this error:
TypeError: a is undefined
jquery.min.js (linje 2)
It has something to do with the pointing to specific parts of the JSON array. But i can't figure out why it isnt working.
The "d" of the data.d path, is because asp.net webservice for some unknown reason wraps it in a d key property.
data.d.NumberOfCustomers
Its also possible to change the JSON string that i create from my webservice, if that would help solving it somehow. But my JSON syntax validates on jsonlint.com
Any help or suggestions will be highly appreciated.
EDIT: added glb object for inspecting + the result of it from Chrome
Inspecting the "glb" gives this result:
Object {d: "{"NumberOfCustomers":15, "Customer":[{"CusID":"1",…D":"15","FirstName":"Adele","LastName":"Woods"}]}"}
Which looks like what i expect; wrapped in the "d" property cause of the asp.net webservice.
When running my jquery snippet in Chrome, im also getting this error:
Uncaught TypeError: Cannot read property 'length' of undefined jquery.min.js:2
n.extend.each jquery.min.js:2
FinalTest.$.ajax.success Customers.aspx:226
j jquery.min.js:2
k.fireWith jquery.min.js:2
x jquery.min.js:4
b jquery.min.js:4
You should be using
data.NumberOfCustomers
instead of
data.d.NumberOfCustomers
and
data.Customer
instead of
data.d.Customer
.
i've tried the following code in the chrome console and it worked:
data = {
"NumberOfCustomers": 15,
"Customer": [
{
"CusID": "1",
"FirstName": "Ina",
"LastName": "Williamson"
},
{
"CusID": "2",
"FirstName": "Hyacinth",
"LastName": "Brady"
},
{
"CusID": "3",
"FirstName": "Coby",
"LastName": "Shannon"
}
]}
$.each(data.Customer,function() { alert(this.CusID); });
I remember asp.net webmethod put the result in property d but perhaps its structure a bit different then what you expect.
I would suggest to add an assignment to global var the value returned from service and investigate it using the console.
in the ajax success add line at the head of the function as follows:
glb = data; //glb will be a global scope var which you can investigate on console upon end of execution.
than on chrome console just type glb and press enter. then you would be able to investigate the object and try the each function without doing the ajax call.
Related
Building a RestAPI with Postman.
I have some JSON data:
{
"progress-update": {
"#type": "parallel-progress",
"job": {
"#href": "/api/space/job-management/jobs/4691268"
},
"taskId": 4691268,
"jobName": "Compare Config-4691268",
"state": "DONE",
"status": "SUCCESS",
"percentage": 100,
"data": "<![CDATA[Total requests: 3<br>InSync count : 3<br>OutOfSync count : 0<br>]]>",
"subTask": [
{
I want to pull the "state" value into an environment Variable that i can then use to determine wether to continue on to the next request or wait until the state is DONE.
The problem i'm running into is "progress-update": has a hyphen in it, causing my script to not recognize it.
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData.progress-update.state);
Postman returns the following error:
There was an error in evaluating the test script: ReferenceError:
update is not defined
You should be able to access your JSON data with
var jsonData = JSON.parse(responseBody);
pm.environment.set("JobStatus", jsonData['progress-update'].state);
using the object bracket notation
I keep getting this error message when I load my human.json file via AJAX.
The whole error message reads
JSON.parse: expected ',' or '}' after property value
in object at line 2 column 22 of the JSON data.
I looked online for it, and there have been people who had similar error messages, however, they are not calling via AJAX.
In addition to that, they are not nesting arrays within objects within objects. I think that is the reason why I am getting this error message. Are you not allowed to nest that many properties into each other?
Here's my AJAX code:
var request = new XMLHttpRequest();
request.open('GET','human.json');
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var obj = JSON.parse(request.responseText);
console.log(obj);
}
}
request.send();
and my human.json file:
{
"sex":{
"male":{"fname":["Michael", "Tom"]},
"female"
},
"age":[16, 80],
"job":[]
}
Your object isn't valid JSON. Specifically at the part:
,"female"}
A JSON property must have a value. Maybe that should that be:
,"female":{}}
or:
,"female":null}
Your JSON file has a syntax error. The following is reformatted to highlight the error:
{
"sex":{
"male":{"fname":["Michael","Tom"]},
"female" <----------------- SYNTAX ERROR
},
"age":[16,80],
"job":[]
}
In JSON, objects have the syntax:
{"name" : "value"}
The syntax {"foo"} is invalid according to JSON spec. Therefore you need to provide some value for the female attribute:
{
"sex":{
"male":{"fname":["Michael","Tom"]},
"female":{}
},
"age":[16,80],
"job":[]
}
Your JSON is indeed invalid.
{
"sex": {
"male":{
"fname": ["Michael","Tom"]
},
"female" ## Here is the problem
},
"age": [16,80],
"job": []
}
Perhaps change that line to:
"female": {}
It all depends on what you're wanting to do
your "female" is error, need a key or value
you can change the json file to
{
"sex":{"male":{"fname":["Michael","Tom"]} ,"female":null},
"age":[16,80],
"job":[]
}
JSON file used by you is invalid json. JSON is a collection of name/value pair. Each key in the JSON should contain value. In your case, key "Female" doesn't have any value. Below shown is the valid JSON format.
{
"sex": {
"male": {
"fname": ["Michael", "Tom"]
},
"female": "XXX"
},
"age": [16, 80],
"job": []
}
I'm trying to update a JSON file with the value of a textarea using jquery push. I'm receiving the following error: " JavaScript runtime error: Unable to get property 'push' of undefined or null reference"
My jquery:
function submittedMsg(ctx) {
var id = $('.msg-input form').attr('id');
var newMsg = $('.msg-input textarea').val();
var url = "/ajax.aspx?vtl=ajax-conversation-json&cv=" + id;
$.getJSON(url, function (messageString, message) {
var message = [];
message.push({
msgcontent: newMsg,
sendname: sendRname,
mbrhref: mbrUrl,
datetime: ""
});
});
}
My JSON:
{
"messageString" :
[
{ "subject": "hello",
"msgstring": "5",
"unread": "1",
"datetime": "Oct 1 2013 9:59PM",
"orderid": "17",
"recipient": [
{
"mbrname": "Jane Doe",
"mbrhref": "/profile.aspx?mem=1227"
},
{
"mbrname": "John Smith",
"mbrhref": "/profile.aspx?mem=1337"
}
],
"message": [
{
"datetime":"2013-10-01T21:59:33.063",
"sendname":"Jane Doe",
"mbrhref":"/profile.aspx?mem=1227",
"msgcontent": "<p>Hi. I would like to talk with you about Dwarf Beryl Beauty</p>"
},
{
"datetime":"2013-11-26T16:29:17.037",
"sendname":"John Smith",
"mbrhref":"/profile.aspx?mem=1337",
"msgcontent": "Tough luck."
}
]
}
]
}
I don't necessarily need to use push to update the JSON file if there is a better way, I'm open to suggestions. I've verified my URL path is correct. Am I just missing something obvious? I'm new to JSON and only have passable jquery skills. Help!
Thanks in advance for any direction.
Try to use:
data.message.push
instead of:
data.messageString.message.push
Ah I see the issue, you have a local var and parameter of the same name message:
$.getJSON(url, function (messageString, message) { //here is param message
var message = []; //here is a local var parameter
message.push({ //this is probably referencing the parameter which is not an array or object that supports .push
Instead:
$.getJSON(url, function (data) { //I renamed the param to be more consistent with documentation, although it doesn't really matter, just will generate confusion
data.messageString.push({ //modify the json we were passed in the data param
For some reason I can't get [object Object] out of the form. I'm using hte method found here:
http://badwing.com/multipart-form-data-ajax-uploads-with-angularjs/#comment-431
The JSON i'm sending is pretty complicated (sample):
{
"challenge_id": 262,
"priority": "0",
"cause_id": "29",
"timestamp": "2013-11-29 12:06:01",
"translations": {
"en": {
"name": "asdfgsfd",
"description": "sdfghfs"
}
},
"actions": {
"1": {
"type": "chek",
"step": "1",
"translations": {
"en": {
"description": "adsfas"
}
}
},
"2": {
"type": "chek",
"step": "2",
"translations": {
"en": {
"description": "fsdgsd"
}
}
}
}
}
My response looks like this:
Content-Disposition: form-data; name="challenge_json"
[object Object]
My request looks like this:
return $http.post( REQUEST_URL + '/ENDPOINT', {challenge_json:data}, {
transformRequest: function(data) {
console.log(data);
var fd = new FormData();
angular.forEach(data, function(value, key) {
fd.append(key, value);
});
console.log(fd);
return fd;
}
Im modifying the headers with a httpProvider configuration change. But have tried doing it in line and am getting the same result.
any help would be appreciated.
It seems you were close to the solution, but needed to unset the 'content-type' header in the options passed to $http, so that the xmlhttprequest object can add it automatically when it gets a formdata on its send method.
https://groups.google.com/d/topic/angular/MBf8qvBpuVE/discussion
see a playground here http://jsfiddle.net/Lv1n55db/1/
(providing FormData object directly and a no-op transform, or your way of providing a normal data object and transforming it to FormData in transformRequest is no significant difference, the key is in the headers option)
headers:{'Content-Type':undefined},
It may vary with differnt browsers and different angularjs versions too.
A more certain and stable approach, at least if you do not need file fields and such, could be to not use native FormData but implement the serialization to string yourself, as FormData polyfills do it.
I am writing some code to educate myself in the ways of ExtJS. I am also new to JSON so hopefully this question will be easy for you to answer. I am trying to retrieve some data from a basic web service that I have written which should be returning its results as JSON (seeing as I am new to JSON - it could be that that is broken).
The error I am getting is
SyntaxError: missing ) in
parenthetical
The JSON that I am returning from my web service is
{
"rows": [
{
"id": "100000",
"genre_name": "Action",
"sort_order": "100000"
}, {
"id": "100002",
"genre_name": "Comedy",
"sort_order": "100002"
}, {
"id": "100001",
"genre_name": "Drama",
"sort_order": "100001"
}]
}
My ExtJS code is as below. The loadexception callback is where I have retrieved the JSON and error above from
var genres = new Ext.data.Store({
proxy: new Ext.data.HttpProxy({
method: 'POST',
url: 'http://localhost/extjs_training/Demo_WebService/Utility.asmx/GetGenres',
failure: function(response, options){
Ext.get('my_id').dom.innerHTML = 'Load failed: ' + response.status;
}
}),
reader: new Ext.data.JsonReader({
fields: ['id', 'genre_name'],
root: 'rows'
}),
listeners: {
loadexception: function (proxy, options, response, e) {
var result = response.responseText;
Ext.MessageBox.alert('Load failure', e + " ..... " + result);
}
}
});
var loadSuccess = genres.load({
callback: function(r, options, success){
Ext.get('my_id').dom.innerHTML = 'Load status: success=' + success;
}
});
Is the JSON you included above what is actually being returned from the call, or what you are anticipating it should look like? The string you included looks clean, but it looks like you formatted it as well. I'm not sure if the space after "id": is allowed, either. It might not be a big deal, though.
The missing parenthetical typically indicates that something in the JSON is wrong. It could be an extra character before/after the string. Use Firebug to examine what you are getting back, and make sure it is clear of any extra characters.
http://www.sencha.com/forum/showthread.php?10117-Solved-missing-%29-in-parenthetical.
Echoeing two statements was the reason in my case. So check your echoes again.