JSON/AJAX and local variables in JavaScript functions - javascript

Working with JSON for the first time, I'm trying to call strings stored in a JSON file like this:
var getText = function(pat,id){
$.getJSON('assets/brospeak.json',function(js){
$('#pim1').append(js.pat.id);
});
}
So my intent is that pat and id get passed to getText when it's called to find the string. The problem is, the local variables in the line $('#pim1').append(js.pat.id); aren't getting called properly, so basically every time I call getText it looks for myfile.pat.id instead of, say, myfile.pattern.a. It works fine when I do just the getJSON part and explicitly tell it where the strings are.
The heck am I doing wrong?

Use js[pat][id] instead if the property name is dynamic:
var getText = function(pat,id){
$.getJSON('assets/brospeak.json',function(js){
$('#pim1').append(js[pat][id]);
});
}

Related

Passing a Django Object to Javascript

Below is the simplified version of my code
view.py:
context['colorObj'] = Colors.objects.all()
Now on template, I can just loop through {{colorObj}} to get the individual values inside the object.
However on JavaScript, this is not the case.
If I want to assign to a variable my colorObj, it just does not work(or maybe I am wrong).
Here is I first thought I should do:
JavaScript:
var colorObj = {{colorObj}};
the value of colorObj is still empty, and there are warning marks on the {{}}. Others suggested to use "" on the Javascript like var colorObj = "{{colorObj}}"; but JavaScript just treat this as a simple String.
Other suggestion is this:
from json import dumps
...
colorObj = Colors.objects.all()
context['colorObj'] = dumps(colorObj)
Then on JS:
var colorObj = {{colorObj| safe}};
But I got an error Object of type QuerySet is not JSON serializable pointing the error to the dumps line.
Note, I am using Django3.1.5
Though I asked about how to get the data from db to Javascript with this method, I proceeded to a different method since it matches my use case. I used #Mahdi Firouzjah's answer for this.
you could use ajax in templates and __ serialize in backend side.
then using javascript you're able to work with that object.

Use dynamic element ID in #{rich:clientId()} function

We can get element by static ID using rich:clientId() function as follows
document.getElementById('#{rich:clientId(JSF_ID)}').click();
However, I need to use a dynamic ID which takes the form of var + "_ID" where var can be employee, student, etc and thus resulting in employee_ID, student_ID as actual ID.
I tried as follows:
dynamicID = var + '_ID';
document.getElementById('#{rich:clientId(dynamicID)}').click();
However, it didn't work. How can I achieve this?
It looks like you are setting dynamicID via JavaScript, am I right?
If yes, the EL-expression #{rich:clientId(dynamicID)} cannot be evaluated as EL on the server during the rendering of the page since the dynamicID is only available on the client (=browser) when the page has already been built up on the server and sent to the browser.
Where does var come from? How is it applied to the component with the dynamicID? Can't you use the same approach for the getElementById?
For concatenating a variable with a constant in JSF on server-side, see the following already answered post Concatenate strings in JSF/JSP EL and Javascript. Basically it gives you a how-to in creation of an own concatenation function for jsp/jsf. Works pretty need.
As a hint: you can use #{rich:element(JSF_ID)} instead of document.getElementById('#{rich:clientId(JSF_ID)}') to keep the source readeable - it will render identical results.
Good luck...

Converting javascript function to global variable

I've been struggling to convert a JavaScript function to a global variable.
I've got 2 files in total that are basically part of the entire function, here is the JavaScript function.
<script type="text/javascript">
$.get("banner1.php", function(getbannerlink1) {
$("#banner1").load(getbannerlink1+ " #productImage");
// var window.bannerlink1=getbannerlink1; (this doesn't want to work)
});
<script>
Basically banner1.php selects ONE random URL out of an array, and echoes the URL. This JavaScript then gets the URL, and then does a .load() function of that URL and gets the #productImage class from that URL, basically it gets the product image from the random URL. That works all good. Now I need to convert the getbannerlink1 variable to a global variable, because I would like to use the link outside of this function as well.
I've tried using the following just before closing the function:
var window.bannerlink1=getbannerlink1;
but this is just destroying the function altogether :/
What am I doing wrong?
var window.bannerlink1 is a syntax error. var should only be used with variable identifiers, which may not contain a period.
You want to set a property of window, not declare a new variable name, so just drop the var.
Drop the var
window.bannerlink1 = getbannerlink1;
Ideally you would avoid using a lot of globals and use a global namespace to hold the values.

Is it possible to concatenate a function input to text of another function call?

Firstly appologies for the poor title, not sure how to explain this in one line.
I have this Javascript function (stripped down for the purpose of the question)...
function change_col(zone){
var objects= zone1227.getObjects();
}
I am passing in an integer into the function. Where I have "zone1227", I want that 1227 to be the integer I pass in.
I've tried this;
var zonename = "zone" + zone;
var objects= zonename.getObjects();
but that doesn't work.
Is this possible? The functions do exist for every possible integer passed in, but I was hoping to keep the code compact rather than a long list of if statements with hardcoded function names.
Since zone1227 is apparently a global variable, it can also be written as window.zone1227 or as window['zone1227']. This means that you can achieve what you describe, by writing this:
function change_col(zone){
var objects= window['zone' + zone].getObjects();
}
Nonetheless, I agree with Interrobang's comment above. This is not a good way to accomplish whatever it is that you really want to accomplish. You should not be referring to global variables via strings containing their names.
No, you cannot refer to a variable with the value of a string, nor can you concatenate anything onto a variable name. EDIT: turns out you can. You still shouldn't.
Yes, you can avoid using a long hard-coded if/elseif sequence: use an array.
Then you can say this:
function change_col(arr, i)
{
var objects= arr[i].getObjects();
}
And the call would be something like:
change_col(zone, 1227);

Javascript jQuery post()/get() JSON object as closure function before document ready

I'm trying to figure out what the best way to handle a JSON object that I need to post/get when the document is ready so I can then run over another function that builds out the DOM based on said JSON object. This object is also something that updates every 30 seconds to a minute.
My initial thought was to build it out as a closure. i.e.:
var myJSONobject = $.post(uri, function(data){return data;});
however the function I run when the for document ready, and functions I base on click events don't recognize the object as being valid. It returns a JSON object, and I've used jsonlint.com to confirm that the object format is valid. So I am thinking its in how I am handling the string of events. Where the object though it may be legit is being rendered after the document ready thus breaking the functionality in a sense. Cause if I take the same object it spits out and hard code it in as a variable. the code I've been working on works fine. So now I am trying to figure out whats my best approach to handling this so one, my script doesn't break prematurely. and two find out if trying to adapt this as a closure the way I am is the right way? Whats a good practice logic in this type of scenario? Should I load the JSON object into a hidden div somewhere or text area and pass it through that or what?
$.post function does not actually return the return value of the success function, so you cannot just assign myJSONobject to it.
What you really want to do is
var myJSONobject;
$.post(uri, function(data){
myJSONobject = data;
// OR work with data here
});
// You cannot use myJSONobject right away
But be careful, you can't access myJSONobject right after calling $.post, you need to wait until the ajax call succeded.
If you need the Object right away before document.ready, use the jsonp technology, and load that script inside documents <head>. Or better load it at the end of the <body>, and the scripts that need it right after it.

Categories

Resources