send parametres as values using JSON syntax - javascript

i want to send an url with parametres, those parametres are values taken by a form with javascript and i want to use JSON to do it, but when i debug i see this error : Uncaught ReferenceError: name is not defined..
function recup()
{
var selectElmt = document.getElementById("name");
var selectcat = document.getElementById("msg");
var name = selectElmt.options[selectElmt.selectedIndex].value;
var msg = selectcat.options[selectcat.selectedIndex].value;
}
function go() { // button send who call the function go
var p_url="http://mysite.com/class?name=" + name + "&message=" + msg +
$.getJSON(p_url, {
}).done(function( data ) {
$.each(data, function (key, field) {
alert(field);
});
});
return false;
}
it's a syntax error when calling the value name and msg but i don"t know how to fix it or in the go function

You two errors, closing curly brace and plus character, the code shoud be:
var msg = "hello"; // i just simplified the value
var name = "test";
function go() { // button send who call the function go
var p_url="http://mysite.com/class?name=" + name + "&message=" + msg;
$.getJSON(p_url, {
}).done(function( data ) {
$.each(data, function (key, field) {
alert(field);
});
});
return false;
}
UPDATE: You need to make name and msg global:
var name, msg;
function recup() {
var selectElmt = document.getElementById("name");
var selectcat = document.getElementById("msg");
name = selectElmt.options[selectElmt.selectedIndex].value;
msg = selectcat.options[selectcat.selectedIndex].value;
}
function go() { // button send who call the function go
var p_url="http://mysite.com/class?name=" + name + "&message=" + msg;
$.getJSON(p_url, {
}).done(function( data ) {
$.each(data, function (key, field) {
alert(field);
});
});
return false;
}
and recup need to be executed before go

the two variables are in another function
Well, that explains it. A variable that is local to a function cannot be accessed by another function.
You have to define the variables in a scope that is shared by both functions. This could be the global scope, but you should avoid creating global variables (you cannot have a global variable with name name anyways, because it exists already).
If you want to assign a value to a variable in a higher scope, use name = ...; instead of var name = ...;.
Example:
(function() {
// create a new scope so that we don't pollute the global scope
// this variable can be accessed by both functions
var answer;
function foo() {
// don't use `var` here, otherwise you create a local variable which
// shadows the variable with the same name in a higher scope
answer = 42;
}
function bar() {
alert(answer);
}
foo();
bar();
}());

Related

JavaScript function local variable being accessed globally

Below is from a textbook that I am working through, but something doesn't make sense. Can someone please explain to me how I'm able to access the local variable "secret" from the global scope? When I run the code the output is '100'. I thought that variables declared inside of a function can't be accessed from outside the function. What is happening here that I can set "secret" to 100?
var set, get;
function val() {
var secret = 0;
set = function (arg) {
if (typeof(arg) === "number") {
secret = arg;
}
};
get = function () {
return secret;
};
}
secret = 100;
document.write(secret);
output > 100
By the way, the textbook originally has the function as an immediate function. I changed to the above hoping that it would lead to a different outcome.
You have a global and a local secret variable.
// Creating a global variable, not affecting the one inside val
secret = 100;
// This is accessing the global variable
document.write(secret);
If you actually run your val function, you'll see that they are different
var set, get;
function val() {
var secret = 0;
set = function(arg) {
if (typeof(arg) === "number") {
secret = arg;
}
};
get = function() {
return secret;
};
}
val();
secret = 100;
document.write("global secret = " + secret + '<br />');
set(5);
document.write("private secret = " + get() + '<br />');
document.write("global secret unaffected = " + secret + '<br />');

"this" in a nested JavaScript function

function TheTable(calculateButtonId)
{
this.errorsBlock = document.getElementById("Some Value");
var addError = function(text) {
this.errorsBlock.innerText += text + "\n";
}
var customHandler = function(desc, page, line, chr) {
addError("[" + line + "] " + desc);
return true;
}
this.init = function() {
window.onerror = customHandler;
......................
}
this.init();
}
var table = new TheTable("BtnId");
as soon as I changed this.addError to var addError it started to thow an error:
Cannot set property 'innerText' of undefined
Could you clarify, what am I referencing by this inside of var-function?
A couple things:
Whenever you invoke a function using the new keyword -- e.g. new TheTable("BtnId") -- you create a new instance of that type. The value of this inside that constructor refers to this new instance.
You can add arbitrary properties to this new instance.
In general, when you invoke a function that has been assigned to this new object, then the value of this inside the function is that same instance.
The var keyword creates a variable scoped to its nearest enclosing function. In general, when you invoke functions of this type (i.e. functions created as global or local variables), the value of this inside them is window.
So when you do this:
this.errorsBlock = document.getElementById("Some Value");
this.addError = function(text) {
this.errorsBlock.innerText += text + "\n";
}
this.addError("whatever");
...then the value of this inside addError refers to the same object that errorsBlock was assigned to and the call succeeds. However, when you change it to this:
var addError = function(text) {
this.errorsBlock.innerText += text + "\n";
}
addError("whatever");
...then the value of this inside addError is window and window probably doesn't have any function property named errorsBlock and the call fails.
function TheTable(calculateButtonId) {
this.errorsBlock = document.getElementById("Some Value");
var self = this;
var addError = function(text) {
self.errorsBlock.innerText += text + "\n";
}
}
this in javascript is always context under which function is running.

OOP JavaScript - public variable undefined

I'm having a problem with the scope of a public variable in javascript. The variable is declared in the main function (function Level) of my javascript class. The loadXML function is called from outside the class, but knows the this.layers variable. When my xml is loaded and redirected to another function the this.layers variable suddenly is undefined. Anyone having experience with this kind of problem.
var Level = (function()
{
function Level()
{
this.layers = 3;
}
Level.prototype.loadXML = function()
{
console.log(this.layers); //variable is defined!
$.get("xml/level_" + this.currentLevel + ".xml", Level.buildGrid);
};
Level.buildGrid = function(xml)
{
console.log(this.layers); //variable is undefined!
};
return Level;
})();
Thanks in advance.
Return a new function from buildGrid that will be passed as jQuery's callback and pass to the wrapped function the current level so that you can get informations from the argument passed. The buildGrid function is so private to the Level's closure and can be accessed only inside it.
var Level = (function () {
var buildGrid = function (level) {
return function(xml) {
console.log(xml);
console.log(level.layers);
};
};
function Level() {
this.layers = 3;
}
Level.prototype.loadXML = function () {
console.log(this.layers); //variable is defined!
$.get("xml/level_" + this.currentLevel + ".xml", buildGrid(this));
};
return Level;
})();
this.layers only exists within the scope of level which is a constructur.
try the following:
var t = new Level.Level()
t.layers

Access to other variables inside of jeditable

I'm really new to javascript, so sorry for my ignorance. In jeditables, you can specify a callback function. I'm using all this code in a separate script. Is there a way to pass variables into this callback function? for example:
var info = "foo";
$('#bar').editable("/foo/bar",
callback : function(value, settings) {
var foobar = value + info;
});
var info = "foo";
$('#bar').editable("/foo/bar",
function(value, settings) {
var foobar = value + info;
});
You should read up on javascript scoping.
What I did above is not usually the way to go since info is now in the global scope.
Side point:
You can even move you callback to a completely different location:
var info = "foo",
callBackFn = function(v, s){
var foobar = v + info;
};
$('#bar').editable("/foo/bar", callBackFn);
You can also assign attributes to the "settings" object as follows:
$(".myClass").editable( "/foo/bar",
{
indicator: "Saving...",
tooltip: "Click to edit",
onblur: "submit",
bax: bax
},
function(value, settings) {
var foobar = value + settings.bax;
});
Inside your handler, you can see the use of the reference to the object by simply stating settings.bax

Is it possible to set a variable equal to a function without using an enclosure?

In JavaScript, you can set a variable equal to a method like this:
variable = function () { alert("My name is bob"); };
Or like this:
function SayMyName() {
alert("My name is bob");
}
variable = SayMyName;
You can also enclose a function with arguments like so:
function SayMyName(name) {
alert("My name is "+ name);
}
variable = function () { SayMyName("bob"); };
But trying to store a variable the following way will call the function, not store it as a variable:
function SayMyName(name) {
alert("My name is "+ name);
}
variable = SayMyName("bob");
There was a clever way you used to be able to work around this by using [callee][1], but callee is depreciated and won't work on most modern browsers.
Is there any way to set a variable equal to a function with arguments without using an enclosure?
Can't you use a nested anonymous function for this?
var variable = function(name) {
return function() {
alert('My name is ' + name);
};
};
Calling it yields your desired result:
var test = variable('bob');
test(); // Alerts "My name is bob"
You can use the bind method to fix some parameters
var variable = SayMyName.bind(null, "bob");
However, this does not work in IE <= 8 so you would have to use a similar replacement or polyfil in tha case.
You can return a function, like:
function SayMyName(x) { return function() { alert("My name is Bob.");}};
var x = SayMyName('bob');
x();
var name = (function sayMyName(name) {
return alert('My name is: ' + name);
});
name('Mike');​​​​​
public class ToyProgram{
public static void main(String[] args){
String funcCallVar = aFunc();
System.out.println(funcCallVar);
}
public static String aFunc(){
String aVariable = "yes you can set a variale equal to a function";
return aVariable;
}
}

Categories