How do I store xml as a string variable in javascript? - javascript

I trying to store a piece of xml into a string variable in javascript and in IE8 it keeps throwing an error. FireFox doesn't show the error but of course in IE8 it does. Swictching browsers isn't an option so I have to try to solve this one.
The purpose of the function is to check if the items of a list exist in an xml object or not. So if there is a better way to do that check I am open to that as well. The system we pull from has a function to convert the xml to a string. At the bottom is an output of what that retrieves. Here is the function.
function commodityExists(newCommodityCode){
var comExists = new Boolean(0);
newCommodityCode = ">" + newCommodityCode + "<"
var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
strXML = strXML.toString();
if(strXML.indexOf(newCommodityCode,0)>0){
comExists=true;
}
return comExists;
};
Here is the output from strXML.toString(); but as you can see it is essentially xml.
var strXML = ‘<variable type="NameValuePair[]">
<item type="NameValuePair">
<name type="String"><![CDATA[No Data Found]]></name>
<value type="String"><![CDATA[95990070]]></value>
</item>
</variable>’;

I don't know what you think the code is doing, here is an explanation of what it does:
> function commodityExists(newCommodityCode){
> var comExists = new Boolean(0);
Do you really want a Boolean object? This function might return a Boolean object or primitive depending on what happens later. Consider:
var comExists = false;
.
> newCommodityCode = ">" + newCommodityCode + "<"
That overwrites whatever value was passed to newCommodityCode from the call.
> var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
I can't see how that throws an error, it's a simple assignment of a string.
> strXML = strXML.toString();
That effectivly does nothing - it calls the toString method of a string, which will just return the same string.
> if(strXML.indexOf(newCommodityCode,0)>0){
That test will always be false, since the value of nweCommodityCode is hard coded in the function and does not exist in the (hard coded) value of strXML.
> comExists = true;
> }
> return comExists; };
The function will always return false (though the original will return a Boolean object with a value of false).

You're creating a string:
var strXML = 'tw.local.aribaHeader.commodities.toXMLString()'; //ERROR HERE
^--- ^---
then converting that string to... a string?
strXML = strXML.toString();
Where would this tw object be defined that you seem to be attempting to use? Because as your code is written now, you're not calling a .toXMLString() method on something in this tw object. You're just assigning the literal text of an object call as a string itself.

The approach I was trying to take will not work because I am dynamically populating the xml so there is no way for me to escape the characters (well there probably is somehow but clearly it is not worth it). Storing HTML or XML code in javascript variables
Instead I am moving the comparison to the server side instead of retrieving the xml and comparing on the client side and posting back the results via ajax unless someone has a better reccomendation.

Related

C# JSON String returned in ambiguous format

i have an issue with my logged Json String as it replaces the double quotes with "
Controller Code :
var message = new SuccessMessagesVM()
{
Title = successMessageType == (int)EnumHelper.SuccessMessageTypes.Add ? "It's beautiful" : CustomModel.Resources.SuccessMessagesResources.EditFormSuccess,
Message = successMessageType == (int)EnumHelper.SuccessMessageTypes.Add ? CustomModel.Resources.SuccessMessagesResources.AddFormSuccess : CustomModel.Resources.SuccessMessagesResources.EditFormSuccess,
ColorCode = (int)EnumHelper.MessagesCodes.Success
};
var json = JsonConvert.SerializeObject(message);
ViewBag.SuccessMessage = successMessageType == 0 ? null : json;
Javascript just logs the ViewBag.SuccessMessage as following:
console.log('#ViewBag.SuccessMessage');
and the object is displayed as {"Message":"تم إضافة النموذج بنجاح","Title":"It's beautiful","ColorCode":3}
replacing all single quotes with ' and all double quotes with "
I expect the output to be {"Message":"تم إضافة النموذج بنجاح","Title":"It's beautiful","ColorCode":3}
This is because you are using ViewBag variable.
In order to use ViewBag, you can write it as followed:
First, in view:
#{
var jss = new System.Web.Script.Serialization.JavaScriptSerializer();
var successMessageJson = jss.Serialize(ViewBag.SuccessMessage);
}
Then use it:
<script>
//use Json.parse to convert string to Json
var successMessageInfo = JSON.parse('#Html.Raw(successMessageJson)');
</script>
There's a few different issues and a few different approaches, and the OP doesn't give us any view code, so it's a bit of guesswork.
My feeling is that you should just return the SuccessMessagesVM from your method, and access the properties individually in your view (probably using #Html.DisplayFor and HTML). This will ensure that any redundant quotation marks are never created in the first place, and will give you total control over how the values are displayed.
You should not expect console.log(#ViewBag.Anything) to display properly. If you need the data as a JavaScript object, don't stick it in the ViewBag, as it will get rendered as HTML.
If you must write to a JavaScript object you can, but it begs the question why are you not using an ajax request if all you want is data?

Javascript Trim left and right from a JSON response

I am looking for an easy way to trim left side from my json response and trim right side from my json output.
An example my json how it is:
{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]}
How i want it to be:
[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]
As you can see I wat TrimLeft all before [ and TrimRight alls behing ] and this is where I have my json response in:
function responseHandler(res) {
return res;
}
The easiest way to go would probably to just save this json to a variable and access the content of something similar like this:
var jsonOutput = {"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]};
var something = jsonOutput.something;
console.log(something);
The output should be the expected json.
Edit 1
Referring to your edit I add another piece of code to come up to your solution.
function responseHandler(response) {
var result = response.something;
return result ;
}
This should give you the expected response.
Why would you want to to that? You can access everything in that json respone. However you can just use javascript string functions, for example:
var x = '{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},
{"id":"3","name":"Test3"}]}';
y = x.substr(x.indexOf("["),x.lastIndexOf("]")-x.indexOf("[")+1);
console.log(y);
if you your ({"something":) this content is fixed you can use below code.
<script>
var str = '{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]}';
str = str.substring(0, str.length - 1).replace('{"something":','');
console.log(str);
</script>
var obj={"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]};
var str=String(obj);
var output=str.substr(x.indexOf("["),x.lastIndexOf("]")-x.indexOf("[")+1);
JSON.parse(output);
The String() function converts the value of an object to a string.
The indexOf() method returns the index within the calling String
object of the first occurrence of the specified value, starting the
search at fromIndex. Returns -1 if the value is not found.
The lastIndexOf() method returns the index within the calling String
object of the last occurrence of the specified value, searching
backwards from fromIndex. Returns -1 if the value is not found.
The JSON.parse() method parses a string as JSON, optionally
transforming the value produced by parsing.

passing mixed string and int parameters to javascript

I've had a look around and can't seem to find a working solution, so here's the requirements.
I'm building a system that takes data from a master page and loads it into a modal style window for quick data processing. I have a javascript function passing 4 status parameters, and whilst 3 of them will always be integers, one of them can be integer or string.
The function works if all 4 parameters are integer, but fails when a string is passed.
function passJob(jobid,equipid,status,location) {
var a = document.getElementById('jobnumber');
var b = document.getElementById('equipid');
var c = document.getElementById('status');
var d = document.getElementById('location');
a.value = jobid;
b.value = equipid;
c.value = status;
d.value = location;
}
PHP
<a href='#' onclick='passJob($sr,$eid,$ss,$sl);'>Modify Job</a>
$sr, $ss and $sl will always be numeric, $eid will either be integer, or a string starting with M and then having a number after it.
I've tried adding quotes to the variables, around the variables, inside the function etc and no luck :(
You need to pass as string if you do not know what they are - also make sure you do not nest the same type of quote:
onclick='passJob($sr,"$eid",$ss,$sl);'
Just wrap it in quotes. This treats it like a string at all times to avoid any potential JavaScript parsing errors.
Modify Job
That is because you do not properly encode the variables in a Javascript notation. Try:
echo "<a href='#' onclick='passJob(".json_encode($sr).",".json_encode($eid).",".json_encode($ss).",".json_encode($sl).");'>Modify Job</a>";
Do like below
Modify Job

Read Value of JSON Result in Jquery

Here is my output of WebMethod through Ajax call:
var item=""[{\"Column1\":\"false\"}]""
There is always one row output,i-e true or false,i want to get the value of Column1,i already try Jquery.ParseJson(item),but it gives Illegal Token o error,Kindly help me how to read this value.Kindly check the inverted commas,this is the exact outcome of my web method, and this outcome and format is a necessary condition of scenario.Thanks.On using loop it gives the error:
If I understand your problem correctly, I think your extra quotes around the strings are a problem, this is invalid syntax.
This works:
var item = "[{\"Column1\":\"false\"}]";
var parsed = JSON.parse(item);
parsed.forEach(function(row) {
console.log(row.Column1);
});
console.log(parsed[0].Column1);
Here is a jsfiddle.
See here about jQuery.ParseJson vs JSON.parse, I prefer JSON.parse, but either should work fine.
In the case of older browsers without forEach use a for loop or a library like underscore.
var item="[{\"Column1\":\"false\"}]";
var parsed = JSON.parse(item);
//if forEach is not supported:
for (var i = 0; i < parsed.length; i++) {
console.log(parsed[i].Column1);
}
console.log(parsed[0].Column1);
Here is a for loop jsfiddle.
I understand that above solutions not work perfectly with your browsers, here is another alternate solution, though I know that it may not fit your scenario, but as your output is either true or false .Instead of using JsonConvert on server end, simply return the object array to client end and read value like this.
var tempo=item[0].Column1;
Not sure about the output of your service but I think you could try this:
str = 'var item=""[{\"Column1\":\"false\"}]""';
str = str.replace(/"/g, '');//remove quotes and slashes to make valid json
eval(str);//evaluate the string
console.log(item[0].Column1);

How to handle failed JQuery DOM conversion

I have a common function to display errors as a result of an AJAX call. Some of those messages are HTML strings, which I want to convert to a DOM object then search for elements inside it using .find(). Others will be just strings (not HTML). In this case, I don't know how to handle this...it is generating exceptions.
var messageTest = "" + this;
if ($(messageTest).length == 0) {
message += this;
} else {
message += $(messageTest).find('.message-error').html();
}
FYI, "this" in this case seems to be a String object with an array in which each item is a character, so in the inspector, it isn't showing "my message here" but:
[0]: "m"
[1]: "y"
etc
When it is just a string, which is not HTML, I get an error at the if statement line:
Uncaught Error: Syntax error, unrecognized expression:<The contents of messageText>
So how to I gracefully handle this when the input could be an HTML string or just a string?
Note...in the end, I just want the string, as I am going to wrap it in it's own HTML.
If it's either a string or HTML, it can always be appended to an element, and then sorted out:
var msg = $('<div />').append(this),
err = msg.find('.message-error'),
txt = err.length ? err.text() : msg.text();
message += txt;
append the string or HTML to an empty div, if the div contains a .message-error element, get the text of that element, otherwise get the text of the div, which would equal the original string etc.
One way, very close to what you have, is to catch the exception, and in this case consider it's a string (assuming this contains the response string):
var messageString = this;
var messageDOM;
try {
messageDOM = $(messageString);
} catch(ex) {
// If we got here, messageString is not HTML
messageDOM = $('<div/>').text(messageString);
}
I know this doesn't answer your question, but I feel like what you're wanting can be better accomplished by a slight change in methodology.
If you have control of the server sending these responses, i would recommend sending them back as JSON objects, if you make every result a JSON object then you can set an error property to true/false in the object that comes back along with a message value with your HTML or error message.
This is faster on the client system as well since its a native object to javascript and jquery has excellent JSON support using $.getJSON.

Categories