pasring JSON from string in jQuery - javascript

http://localhost/project1/index.php
//AJAX region
$(function(){
$.ajax({
type : 'GET',
url : 'https://jsonplaceholder.typicode.com/posts/1',
success : function(data){
console.log('success \n', data);
},
error : function(data){
console.log('error', data);
}
});
});//AJAX region
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
it's easily loading data from http://localhost/project1/json.php
console:
data is string, if I use $.parseJSON(data) or JSON.parse(data) i get following error...
I want data as realtime JSON object, so that I can access each properties & values.

Observation 1: unnecessary parseJSON
No need to call parseJSON.
Use dataType property of $.ajax to load your data directly in JSON format:
$.ajax({
type : 'GET',
dataType: 'json', // here
url : 'http://localhost/project1/region.php',
success : function(data) {
// data is already a JS object :)
console.log('success \n', data);
},
error : function(data){
console.log('error', data);
}
});
Observation 2: wrong JSON
Code above will still throw the same error, because of
unexpected token ,
It refers to the trailing comma after all the last elements your object and its children. Remove that comma and there will be no more errors.
For example:
"State1" : {
"City 1",
"City 2",
"City 3",
}
There should NOT be a comma after "City 3". The same goes for other states, and for whole "country2" object too.
There is another error: your States objects are arrays, but you are writing then as objects. Change curl brackets to square brackets for "State1" and "State2".

The json object you are returning is invalid json, for the state objects, you need to make them arrays. so:
"State1":["City1","City2","City3"]
When the parser parses this object it expects a second value per city like "City1 ": "Second Value"...since there is no second value its breaking.

Related

Jquery Ajax passing array inside data obect

I am trying to pass an object into the data property of this jquery ajax request. All work's fine, but the fields property, which is an array, does not get recognized (returns all fields, when these are the two I am requesting).
I've tried JSON.stringify, but this returns an error for 'bad request'. How do I pass this object with an array inside correctly?
function energyQuery(token){
$.ajax({
type: 'GET',
url: url,
headers: {'Content-Type': 'application/json', 'Authorization': 'Token token=' + token},
data: {
'start': '2019-01-05',
'end': '2019-01-10',
'limit': 0,
'measurement': 'analysis',
'fields': ['energy_out', 'energy_in'] // if I pass 'energy_out' it works
},
success: function(data){
//console.log(data);
response = JSON.stringify(data);
console.log(response);
},
error: function(errMsg) {
console.log('Query:' + JSON.stringify(errMsg));
}
});
}
error message:
Please note that fields MUST either be a single valid field string or a list of valid field strings.
Send it as post and point to correct datatype
var array = ['energy_out', 'energy_in'];
var dataObj = {
'start': '2019-01-05',
'end': '2019-01-10',
'limit': 0,
'measurement': 'analysis',
'fields': array
};
var data = JSON.stringify(dataObj);
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: data,
contentType: "application/json"
});
Also on back-end side create correct model to recieve data.
If you are implementing also the server side, please consider to change the array of strings to a "particular string".
What I mean?
CASE 1 : pass array as string
'fields': '[\'energy_out\', \'energy_in\'])'
Then in the server side read the string and convert it to an array.
This is the solution that I use in Java: I read a String then I convert it to an array of integer,strings,... and so on.
CASE 2: use a particular separator, pass the field as a string;
'fields': 'value1,value2,value3'
Supposing you use , as separator, then you must split string by ,.
It's better to ask (via web service) arrays as a single string so each client can implement in a simple way of to pass data in the get method.
'fields': ['energy_out', 'energy_in']
It's not a standard json format. just change the type of parameter 0 'fields': 'energy_out,energy_in' and when receive use split,

Can not get value from JSON object

I'm having trouble getting the data value from JSON object. Here is my code:
var ab_id = $( "#ab_id" ).val();
$.ajax({
type: 'GET',
contentType: 'application/json',
url: 'edit_account.php',
data: {ab_id:ab_id, u_id:u_id},
success: function(data)
{
alert(data.ab_name);
},
});
When I do alert(data), I got the actual data like this:
{
"ab_id":"7",
"ab_name":"Lily's Storage Address",
"ab_ship_name":"LIly C\/O SELF STORAGE",
"ab_addr_1":"C\/O Lily",
"ab_addr_2":"16 PIUMA AVENUE, UNIT #2",
"ab_city":"CERI",
"ab_state":"CA",
"ab_postal":"90700",
"ab_phone":null,
"ab_default":"0",
"ab_is_storage":"1"
}
However, when I retrieve the data value by using data.ab_name, it returns undefined.
Am I missing something here?
Use bracket notation
alert(data['ab_name']);
for reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Parse your string to a object
data = JSON.parse(data);
alert(data.ab_name);

Undefined when trying to parse JSON

I'm trying to parse a JSON response with JQuery:
<script>
$(document).ready(function() {
$("button").click(function() {
$.ajax({
url : 'test.php',
type : 'GET',
data : {
name : "Peter",
},
dataType : 'json',
success : function(response) {
console.log(response);
alert(response.name)
},
error : function() {
console.log("error")
}
});
});
});
</script>
I want to get the name into the alert box, but everything I get is an undefined.
This is the result in the console:
Object {results: Array[1]}
results: Array[1]
0: Object
id: "4"
name: "Peter"
When I do alert(JSON.stringify(response)); I get {"results":[{"id":"4","name":"Peter"}]}, so there is definitely valid JSON.
In response there is not property name. name there is in in first element in results array, so to get name you need do
console.log(response.results[0].name)
response is an object which contains an array in results, you need to iterate over ressponse.results or if you're sure it well have only one element, use response.results[0].name
The JSON data contains an array, so you need use an index:
var data = {"results":[{"id":"4","name":"Peter"}]}
document.write(data.results[0].name)

Parsing response text as key value pairs in an elegant way

Can't seem to find what I'm looking for in searches so this might be a duplicate but I haven't found an original yet sooo....
I have a an ajax call:
$.ajax({
url: "/events/instructor/",
type: 'POST',
data: {
instructorID: $(this).attr("id")
},
complete: function (data) {
$("#name").html(data["responseText"]["name"]);
$("#email").html(data["responseText"]["email"]);
$("#photo").html(data["responseText"]["photo"]);
$("#summary").html(data["responseText"]["summary"]);
$("#url").html(data["responseText"]["url"]);
}
});
The data being returned is encoded in JSON by the server (C#).
Obviously, data["responseText"]["fieldName"] isn't doing the trick. I could do splits and whatnot but that would mean that if the format changes, I'd need to make sure that the code above keeps up with the changed shape of the data.
How can I say something as simple as data["responseText']["fieldName"] to get the value out of that key?
i think you need to parse json first. look at the api.jquery.com/jquery.parsejson
// data = '{ "name": "John" }'
var obj = jQuery.parseJSON( data );
console.log( obj.name);
// result will be "John"
P.S. also better use 'succes' instead 'complete', you can read about this here Difference between .success() and .complete()?
success: function(data) {
console.log("response is good", data);
},
error: function (){
console.log("something is went wrong");
}
try using like this:
complete: function (data) {
var data=JSON.parse(data);
$("#name").html(data.responseText.name);
$("#email").html(data.responseText.email);
$("#photo").html(data.responseText.photo);
$("#summary").html(data.responseText.summary);
$("#url").html(data.responseText.url);
}
to get only correct response use success.

Uncaught TypeError: Cannot use 'in' operator to search for '' in JSON string

I've use token input in my website, and here's how I initialize the token input:
$(document).ready(function () {
var populateValue = document.getElementById('<%= hiddentokenPrePopulate.ClientID%>').value
$("#<%= tokenEmployee.ClientID%>").tokenInput("../Employee/getEmployeeDetails.ashx", {
deleteText: "X",
theme: "facebook",
preventDuplicates: true,
tokenDelimiter: ";",
minChars: 3,
tokenLimit: 1,
prePopulate: populateValue
});
});
The script was stuck on this line:
prePopulate: populateValue
When I remove this line, there won't be any javascript error, but I need this as I need to pre-populate the token input. The populateValue is:
[{
"id": "11566",
"name": "Smith - White"
}]
There was a javascript error:
Uncaught TypeError: Cannot use 'in' operator to search for '47' in [{"id":"11566","name":"Smith - White"}]`
How can I fix this error?
You need to parse the string in your populateValue variable to an object:
prePopulate: $.parseJSON(populateValue)
Or alternatively, in plain JS:
prePopulate: JSON.parse(populateValue)
You may get this error if you are using a string as an array. Say that if you got a json from an ajax, and you forgot to parse the result, and using the result as an array. The remedy is as above, to parse the json before using it.
Your server side code means .CS page where you have written your WebMethod, should always return .ToList() means array of json
Here is my .CS page code:
WebMethod
public static string PopulateDetails(Guid id){
var prx = new ProductProxy();
var result = prx.GetFirstorDefault(id); // this method is having List<ClassObject> return type
return JsonConvert.SerializeObject(result);
}
Then in my jQuery post method:
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "Productjq.aspx/PopulateDetails",
data: JSON.stringify({id: id}), // This is Id of selected record, to fetch data
success: function(result) {
var rspns = eval(result.d); // eval is used to get only text from json, because raw json looks like "Id"\"1234"
$.each(rspns, function() {
$('#<%=txtProductName.ClientID %>').val(this.Name);
});
},
error: function(xhr, textStatus, error) {
alert('Error' + error);
}
});
I was getting this error as well.
C# Api returning Serialized Dictionary data.
return JsonConvert.SerializeObject(dic_data);
return new JavaScriptSerializer().Serialize(dic_data);
Kept on getting this error message, until i just returned the Dictionary data directly without trying to Serialize
return dic_data;
No more errors on the browser side. Not sure why.

Categories

Resources