How do I serialize a parameter incoming from my controller? - javascript

So I am sending a list of objects from my ASP.NET MVC controller back to my ajax success response:
...
success: function (data) {
var predefinedData = data.serialize();
...
When I debug from browser, I see that the data parameter is reading as an array, which is ok, but the following error occurs:
Uncaught TypeError: data.serialize is not a function
I've read that I have to convert the "vanilla" parameter into jQuery so I did the following:
var makeJqueryArray = $.makeArray(data) //this passes ok
var predefinedData = $.param(makeJqueryArray).serialize(); //but then this reports the same error as before
Upon further inspection I see that $.makeArray(data) literally doesn't do anything since it stays exactly the same as before, an array with n number of elements.
Doing JSON.stringify(data); works however, but it is out of the question since that gives me a completely different format than what I need here.
So does anyone have any suggestions?
EDIT 1:
So here is the data I am receiving (as seen from the browser debugger watch):
data: Array[3]
0:Object
_int:false
avg:false
max:false
min:false
sensorID:5
sum:false
val:true
__proto__: Object
1:Object
2:Object
length:3
__proto__:Array[0]
And here is how i want to format it (the values don't match because I'm using different samples, but you get the point):
"SensorID=1&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=2&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=3&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=4&val=true&val=false&min=true&min=false&avg=true&avg=false&max=true&max=false&sum=true&sum=false&_int=true&_int=false&SensorID=5&val=true&val=false&min=true&min=false&avg=true&avg=false&max=true&max=false&sum=true&sum=false&_int=true&_int=false&SensorID=6&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=7&val=false&min=false&avg=false&max=false&sum=false&_int=false&SensorID=9&val=false&min=false&avg=false&max=false&sum=false&_int=false"

If you have an array and you want to make a request where the parameters are the key-value pairs of it, you can use simply $.param(yourArray);.
It will return a string ready to be used in your URL.
For example (taken from the jQuery.param page) :
var params = { width:1680, height:1050 };
var str = jQuery.param( params ); // str = "width=1680&height=1050"
This should the same in your case. So, try this :
var makeJqueryArray = $.makeArray(data) //this passes ok
var finalString = $.param(makeJqueryArray); // Should contain the string you want

Related

Get JSON data from WFS/Geoserver

I am struggling with getting data from WFS in my GeoServer. I want to get specific properties from the JSON returned by WFS and use it in my html page filling a table. I have read lots of posts and documentation but I can't seem to make it work. I have:
(a) changed the web.inf file in my geoserver folder to enable jsonp
(b) tried combinations of outputFormat (json or text/javascript)
(c) tried different ways to parse the JSON (use . or [], JSON.parse or parseJSON etc),
(d) used JSON.stringify to test whether the ajax call works correctly (it does!!)
but, in the end, it always returns undefined!!
function wfs(longitude, latitude){
function getJson(data) {
var myVar1=data['avgtemp1'];
document.getElementById("v1").innerHTML = myVar;
}
var JsonUrl = "http://88.99.13.199:8080/geoserver/agristats/wfs?service=wfs&version=2.0.0&request=GetFeature&typeNames=agristats:beekeeping&cql_filter=INTERSECTS(geom,POINT(" + longitude + " " + latitude + "))&outputFormat=text/javascript&format_options=callback:getJson";
$.ajax({
type: 'GET',
url: JsonUrl,
dataType: 'jsonp',
jsonpCallback:'getJson',
success: getJson
});
}
wfs(38, 23);
Could you please help me?
You are close to it. First, you have a typo in the variable name you are writing (myVar1 vs myVar). Secondly, your function is receiving a Json object, so you must dive into its structure. First you get the features, then the 1st one, then the property array, then the property of your choice.
I suggest you read a tutorial on Json Objects, as you will surely want to loop through properties/items, validate they are not null etc.
function getJson(data) {
var myVar1=data.features[0].properties['avgtemp1'];
document.getElementById("v1").innerHTML = myVar1;
}
At last, don't forget to use the debugger in your favorite browser. put a breakpoint in your function and check the structure and content of data.

JSON.parse() not working

I have a json from my server which is -
{"canApprove": true,"hasDisplayed": false}
I can parse the json like this -
var msg = JSON.parse('{"canApprove": true,"hasDisplayed": false}');
alert(msg.canApprove); //shows true.
At my ajax response function I caught the same json mentioned earlier by a method parameter jsonObject -
//response function
function(jsonObject){
//here jsonObject contains the same json - {"canApprove":true,"hasDisplayed": false}
//But without the surrounding single quote
//I have confirmed about this by seeing my server side log.
var msg = JSON.parse(jsonObject); // this gives the error
}
But now I got the following error -
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of
the JSON data
Can anyone tell me why I am getting the error?
Your JsonObject seems is a Json Object. The reasons why you can't parse Json from a String:
the String is surround by " ". and use \" escape inside. Here is an example:
"{\"name\":\"alan\",\"age\":34}"
when you try to parse above string by JSON.parse(), still return the a string:{"name":"alan","age":34}, and \" is replace by ". But use the JSON.parse() function again, it will return the object you want. So in this case,you can do this:
JSON.parse(JSON.parse("{\"name\":\"alan\",\"age\":34}" ))
Your string use ' instead of " . example:
{'name':'alan','age':34}
if you try to parse above string by JSON.parse(), may cause error
I dont think you should call JSON.parse(jsonObject) if the server is sending valid JSON as it will be parsed automatically when it retrieves the response. I believe that if You set the Content-type: application/json header it will be parsed automatically.
Try using jsonObject as if it was already parsed, something like:
console.log(jsonObject.canApprove);
Without calling JSON.parse before.
This answer might help someone who's storing JSON as a string in SQL databse.
I was storing the value of following
JSON.stringify({hi:hello})
in MySQL. The JSON stored in SQL was {"hi":"hello"}
Problem was when I read this value from db and fed it to JSON.parse() it gave me error.
I tried wrapping it in quotes but didn't work.
Finally following worked
JSON.parse(JSON.stringify(jsonFromDb))
This worked and JSON was parsed correctly.
I know the storing mechanisim might not be appropriate however those were client needs.
Its already an object, no need to parse it. Simply try
alert(jsonObject.canApprove)
in your response function.
Json.parse is expecting a string.
Your jsonObject seems already parsed, you need to test if this is the case.
function(jsonObject){
var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}
It's also possible that your call back is empty, it's generates the same error if you try to parse an empty string. So test the call back value.
function(jsonObject){
if(jsonObject) {
var msg = (typeof jsonObject == "object" ? jsonObject : JSON.parse(jsonObject));
}
}
var text = '{"canApprove": true,"hasDisplayed": false}';
var parsedJSON = JSON.parse(text);
alert(parsedJSON.canApprove);
This works. It is possible that you use " instead of ' while creating a String.
Here is an example of how to make an ajax call and parse the result:
var query = {
sUserIds: JSON.stringify(userIds),
};
$.ajax({
type: "POST",
url: your-url,
data: JSON.stringify(query),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (response) {
var your_object = JSON.parse(response.d);
},
failure: function (msg) {
alert(msg);
},
error: function (a, b, c) {
}
});
I faced similar problem and now it's solved. I'm using ASP.Net MVC to send value to .js file. The problem was that I was returning JsonResult from the Action method, because of this JSON.parse was failing in .js file. I changed the return type of Action method to string, now JSON.parse is working fine.
As someone mentioned up there, this actually fixes the problem. What I learnt from this is that may be how PHP encodes a json object is not familiar to JavaScript.
var receivedData = data.toString()
receivedData = JSON.parse(receivedData)
console.log(receivedData.canApprove)
This will work.

How can I iterate this json?

"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there

Knockout.js ko.mapping.toJS not refreshing data in my view

I fetch a json object from the server and populate my view. I then change the data, push it back to the server. I then fetch a new copy of the data hoping it will refresh my view with any changes. However that doesn't happen. TIA
$(document).ready(function() {
var customer_id = get_customer_id();
var data = load_model();
contract_model = ko.mapping.fromJS(data,{});
ko.applyBindings(contract_model);
}
function load_model(){
var url = '/ar/contract_json?contract_id='+get_contract_id();
var data = '';
$.ajax({
type:'GET',
url:url,
async:false,
success: function(returningValue){
data = returningValue;
}
});
return data;
}
This initial load works fine. I then do some stuff and change one of the observables and push that data back to server. Server gets the update and then I do a new fetch of the data so that view will refresh (i know i can pass back the new data in one step but this in code i haven't refactored yet).
function refresh_data(contract_model){
var url = '/ar/contract_json?contract_id='+get_contract_id();
$.post(url,function(data){
console.log(data);
ko.mapping.fromJS(contract_model,{},data);
ko.applyBindings(contract_model);
console.log(ko.mapping.toJS(contract_model))
});
}
function refresh_data(contract_model){
var url = '/ar/contract_json?contract_id='+get_contract_id();
$.post(url,function(data){
console.log(data);
ko.mapping.fromJS(contract_model,{},data);
console.log(ko.mapping.toJS(contract_model))
});
}
function push_model(contract_model,refresh){
var url = '/ar/update_contract';
var data = {'contract':ko.mapping.toJSON(contract_model)}
delete data['lines'];
$.post(url,data,function(return_value){
if (refresh){
refresh_data(contract_model);
};
});
}
The console messages all show the new data coming back but my view never updates.
I believe the problem is with the order of parameters you pass into the ko.mapping.fromJS function when you are updating contract_model.
You have:
ko.mapping.fromJS(contract_model,{},data);
you want:
ko.mapping.fromJS(data, {}, contract_model);
#seth.miller's answer is correct. You can also leave out the middle "options" parameter if your contract_model is the same one that was mapped earlier. If there are only two arguments, ko.mapping.fromJS checks if the second argument has a "__ko_mapping__" property. If so, it treats it as a target, otherwise it treats it as an options object.
Based upon #DBueno's observation - for anyone using typescript I strongly recommend commenting out this method signature from your knockout.mapping.d.ts file.
// fromJS(jsObject: any, targetOrOptions: any): any;
Yes - just comment it out.
You'll then get a compile time error if you try to do :
ko.mapping.fromJS(item.data, item.target);
and you can replace it with the much safer
ko.mapping.fromJS(item.data, {}, item.target);
Safer because whether or not item.target has been previously mapped (and therfore would have a __ko_mapping__ property) it will always copy the properties.

How do I display values of an JSON object?

Here is what I got so far. Please read the comment in the code. It contains my questions.
var customer; //global variable
function getCustomerOption(ddId){
$.getJSON("http://localhost:8080/WebApps/DDListJASON?dd="+ddId, function(opts) {
$('>option', dd).remove(); // Remove all the previous option of the drop down
if(opts){
customer = jQuery.parseJSON(opts); //Attempt to parse the JSON Object.
}
});
}
function getFacilityOption(){
//How do I display the value of "customer" here. If I use alert(customer), I got null
}
Here is what my json object should look like: {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}. What I ultimately want is that, if I pass in key 3, I want to get Stanley Furniture back, and if I pass in Stanley Furniture, I got a 3 back. Since 3 is the customerId and Stanley Furniture is customerName in my database.
If the servlet already returns JSON (as the URL seem to suggest), you don't need to parse it in jQuery's $.getJSON() function, but just handle it as JSON. Get rid of that jQuery.parseJSON(). It would make things potentially more worse. The getFacilityOption() function should be used as callback function of $.getJSON() or you need to write its logic in the function(opts) (which is actually the current callback function).
A JSON string of
{"3":"Stanley Furniture","2":"Shaw","1":"First Quality"}
...would return "Stanley Furniture" when accessed as follows
var json = {"3":"Stanley Furniture","2":"Shaw","1":"First Quality"};
alert(json['3']);
// or
var key = '3';
alert(json[key]);
To learn more about JSON, I strongly recommend to go through this article. To learn more about $.getJSON, check its documentation.
getJSON will fire an asynchronous XHR request. Since it's asynchronous there is no telling when it will complete, and that's why you pass a callback to getJSON -- so that jQuery can let you know when it's done. So, the variable customer is only assigned once the request has completed, and not a moment before.
parseJSON returns a JavaScript object:
var parsed = jQuery.parseJSON('{"foo":"bar"}');
alert(parsed.foo); // => alerts "bar"
.. but, as BalusC has said, you don't need to parse anything since jQuery does that for you and then passes the resulting JS object to your callback function.
var customer; //global variable
function getCustomerOption(ddId){
$.getJSON("http://localhost:8080/WebApps/DDListJASON?dd="+ddId, function(opts) {
$('>option', dd).remove(); // Remove all the previous option of the drop down
if(opts){
customer = opts; //Attempt to parse the JSON Object.
}
});
}
function getFacilityOption(){
for(key in costumer)
{
alert(key + ':' + costumer[key]);
}
}

Categories

Resources