Output a value in jQuery from Django - javascript

The value of 'content' is some parsed json. I want to now use this value in my query script. Bellow is what I have so far. The value needs to be in between var siteData = { } how can I do this?
What I have so far, but it does not work.
On my HTML Page:
<script type="text/javascript">
var temp = {{ content }};
</script>
In the builder.js:
$(document).on('pagebeforeshow', '#index', function (event) {
var siteData = {
temp;
}
});
this is the error:
**var temp = {"name":"dsaadsa","logo":"**

i think your variable temp has value, what you need.
if content equals "{a:1, b:2}", html under rendering will be var temp = {a:1, b:2};
and then you can write
$(document).on('pagebeforeshow', '#index', function (event) {
var siteData = temp; // window.temp
});

Django is escaping the JSON string try {{ content|safe }}
To expand a bit, Django offers all sorts of filters (of which 'safe' is one) that you can apply to variables you are outputting to templates.
Another example would be {{ content|lower }} to output lower case text.
The docs for this are here

Please post exact errors with full traceback, as they appear in Javascript console, without them is just a shot in the dark..
I believe you have incorrect syntax
var temp is global it will be accessible in builder.js, but siteData is invalid syntax for object literal; should be something like:
var siteData = { key: value}

Related

while using #htm.raw getting Syntax error "returns mark up that is not html encoded" [duplicate]

Vs'12 asp.net C# MVC4 - Int.Appl.Template EF Code First
Here is my very simple Script
<script class="TractsScript">
$('#Add').click(function (e) {
var val = #ViewBag.ForSection;
alert(val);
});
</script>
As per example I am wanting to simply set a variable in my script or USE a Viewbag. or Model.
I haven't been able to find an answer in any of the following forums: StckTrace1,StackTraceBetterAnswer
Other Things i have tried:
var model = #Html.Raw(Json.Encode(Model))
alert(model.Sections);
alert(#ViewBag.ForSection);
What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.
var val = '#ViewBag.ForSection';
If it's an integer you need to parse it as one i.e.
var val = parseInt(#ViewBag.ForSection);
You can do this way, providing Json or Any other variable:
1) For exemple, in the controller, you can use Json.NET to provide Json to the ViewBag:
ViewBag.Number = 10;
ViewBag.FooObj = JsonConvert.SerializeObject(new Foo { Text = "Im a foo." });
2) In the View, put the script like this at the bottom of the page.
<script type="text/javascript">
var number = parseInt(#ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = #Html.Raw(#ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>
try this method
<script type="text/javascript">
function set(value) {
return value;
}
alert(set(#Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
alert(set(#Html.Raw(Json.Encode(ViewBag.UrMessage))));
</script>
Thanks
Use single quotation marks ('):
var val = '#ViewBag.ForSection';
alert(val);
When you're doing this
var model = #Html.Raw(Json.Encode(Model));
You're probably getting a JSON string, and not a JavaScript object.
You need to parse it in to an object:
var model = JSON.parse(model); //or $.parseJSON() since if jQuery is included
console.log(model.Sections);

Modify a json array in hidden input?

I have a hidden input:
<input type="hidden" id="paidIds" name="paidIds" value="[]">
It starts with an empty array as its value.
I want to add and remove items from it but I cant work out how.
This is my code so far:
TO APPEND:
var $paidIds = $('#paidIds').val();
$paidIds.push($id);
$('#paidIds').val($paidIds);
TO REMOVE:
var $paidIds = $('#paidIds').val();
var $index = paidIds.indexOf($id);
if($index != -1) {
$('#paidIds').val().splice($index, 1);
}
$('#paidIds').val($paidIds);
So far one of the issues is $paidIds is still undefined after:
var $paidIds = $('#paidIds').val();
At a loss, and google is not helping -__-
EDIT
Got it working partly, in the debugger $paidIds = [4] but it did not set the value.
var $paidIds = JSON.parse($('#paidIds').val());
$paidIds.push($id);
$paidIds = JSON.stringify($paidIds)
$('#paidIds').val($paidIds);
EDIT2 fixed the missing #
You need to convert string to object.
Change:
$('paidIds').val()
to
$('#paidIds').val()
Try:
var $paidIds = $('#paidIds').val();
if($paidIds != ""){
$paidIds = JSON.parse($paidIds);
}
try to use JSON.parse when you read from the input, and use JSON.stringify when you set the input's value
I would suggest you store array an a data- attribute and use jQuery.data() to read it rather than parsing the value to an array.
HTML
<input id="paidIds" name="paidIds" data-array="[1,2,3]" value="[1,2,3]">
JS
/* Custom event to handle updates*/
$('#paidIds').on('updateArray', function (evt, newVal) {
var arr = $(this).data('array');
arr.push(newVal);
$(this).val(JSON.stringify(arr))
});
/* Useage*/
$('button').click(function () {
var newArrValue=$(this).data('val')
$('#paidIds').trigger('updateArray', [newArrValue]);
});
DEMO

Trouble with getting access to an object's property

I'm having a trouble with getting access to an object's property.
Isn't it possible to get access to an object's property like this?
key["heading"]
key in the code above is a variable.
This code below is the code I'm working on right now.
alertHeading.on('blur', function(){
var inputtedVal = $(this).val();
var key = alertMode.val();
chrome.runtime.getBackgroundPage(function(backgroundPage) {
var background = backgroundPage.background;
//(1)This works fine.
background.setStorage(key, {heading:inputtedVal});
console.log(background.getStorage(key));// Object {heading: "aaa"}
//(2)This doesn't work.
var alertObject = background.getStorage(key["heading"]);
console.log(alertObject);// null. I'm expecting to get "aaa".
});
})
I think I'm making a very simple mistake which comes from my lack of javascript knowledge.
Please help me out to solve this problem.
Your key isn't an object, it's a string. It is the return from background.getStorage(key) that is an object, so you can do this:
var alertObject = background.getStorage(key)["heading"]; // note () and [] placement
// OR, in two steps:
var alertObject = background.getStorage(key);
var heading = alertObject["heading"];
EDIT:
"I haven't understood why it's not an object but a string yet"
Your key variable is set to the return from jQuery's .val() method:
var key = alertMode.val();
...which returns a string that is the value of the form element that it is called on. Add in a console.log(key) and you'll see.

Issue with JSON stringify?

/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
// Get anything in the current field
current_data = $('#changes').val();
if (!current_data) {
var data = new Array();
data[type] = ids;
$('#changes').val(JSON.stringify(data));
} else {
var data = JSON.parse($('#changes').val());
data[type] = ids;
$('#changes').val(JSON.stringify(data));
}
console.log($('#changes').val());
}
I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...
Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?
Thanks :)
These lines may cause problems:
var data = new Array();
data[type] = ids;
... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...
var data = {};
data[type] = ids;
Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.
UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.
I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?
function insertSerializedData(ids, type) {
var changes = jQuery('#changes'), arr, val = changes.val();
if (!val) {
arr = [];
arr[type] = ids;
changes.val(JSON.stringify(arr));
} else {
arr = JSON.parse(val);
arr[type] = ids;
changes.val(JSON.stringify(arr));
}
console.log(changes);
}

How can I print javascript objects?

I have an object
var object= {}
I put some data in the object and then I want to print it like this
document.write(object.term);
the term is a variable that changes depending on different situations. When I try printing this it comes up with undefined.
How would it be done?
Update:
this is the code I am dealing with. I guess it probably isn't the same as what I said above because I am doing it in selenium with browsermob, I just thought it would be similar to document.write(). Here is the code
var numCardsStr = selenium.getText("//div[#id='set-middle']/div[2]/h2");
var numCards = numCardsStr.substr(4,2);
browserMob.log(numCards);
var flash = {}
for(i=0; i<(numCards); i++){
var terms = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[1]");
var defs = selenium.getText("//div[#id='words-normal']/table/tbody/tr[" + (i + 2) + "]/td[2]");
flash[terms] = defs;
browserMob.log(flash.terms);
}
EDIT: You're using two different variable names, flash and flashcards. I don't know if they are meant to be the same thing, but you are setting the value using the [] notation, then getting it using . notation.
Try:
var flash = {};
...
flash[terms] = defs;
browserMob.log(flash[terms]);
If term is a variable to represent the property you are retrieving, then you should use the square bracket notation for getting the property from the object.
Example: http://jsfiddle.net/xbMjc/ (uses alerts instead of document.write)
var object= {};
object.someProperty = 'some value';
var term = "someProperty";
document.write( object[term] ); // will output 'some value'
If you're using document.write(), there's a good chance you are trying to reference the object before it's been instantiated. My advice: don't use document.write() unless you need it in a template. For all other purposes, wait till the page loads and then run your script as an event handler.
There could be other reasons for the failure, but your code sample isn't complete enough for a diagnosis.
To output the whole object as text, use a JSON library:
<script type="text/javascript" src="http://www.JSON.org/json2.js"></script>
.
var o = { "term": "value" };
document.write(JSON.stringify(o, null, 4));
This will output the object as a string and indent 4 spaces to make it easy to read.
What you do is this:
var terms = "abcd";
var defs = "1234";
var flash = {};
flash[terms] = defs;
This creates this object:
{
"abcd": "1234"
}
If you want to go through the properties (i.e. "abce"), do this:
for (var key in flash) {
document.write('Key "' + key + '" has value "' + flash[key] + '"<br/>');
}
This will output:
Key "abcd" has value "1234"
Because I haven't seen this mentioned yet:
var a = {prop1:Math.random(), prop2:'lol'};
a.toString = function() {
output = [];
for(var name in this) if(this.hasOwnProperty(name) && name != 'toString') {
output.push([name, this[name]].join(':'));
}
return "{\n"+output.join(",\n\t")+"\n}";
};
document.write(a);
// should look like:
/*
{
prop1:0.12134432,
prop2:lol
}
*/
In the case that you're defining an object class, like MyObj:
var MyObj = function(id) {
this.someIdentity = id;
};
MyObj.prototype.toString = function() {
return '<MyObject:'+this.someIdentity+'>';
};
And then anytime you write something like
document.write(new MyObject(2));
It'll appear as <MyObject: 2>.
Avoid document.write
If you use Firefox, install firebug and use it's console api
The same console apis should work in chrome too.
For IE, get companion js
In javascript, obj.propertyname is used if the property name is known before hand. If it's not, then:
if pn contains the property name, obj[pn] should give you the value.
Well in firefox and in Chrome/Safari you could simply use...
var myObj = {id: 1, name: 'Some Name'};
window.console.log(myObj);
And the console will output something like "Object"
If you are in Chrome you could inspect the internal values of the object with ease using the built in developer console.
If you use firefox the output should come out of firebug as well...
I'm stating this as an alternative of using document.write as it seems a little bit invasive to me to output content on the document...

Categories

Resources