'parameterValue' in Javascript - javascript

Is 'parameterValue' a default parameter that is passed on an event in Javascript ?
Can anyone explain where this value comes from.
Load Ajax content
I found it used in the following article - http://www.easywayserver.com/blog/java-how-to-use-ajax-in-jsp/

In the context of that example, parameterValue is not important as it's discarded in the jsp file that is being called. In the javascript the parameters for the call are constructed as:
var url="loadJSP.jsp";
url=url+"?q="+str; /* url looks like loadJSP.jps?q=parameterValue */
In the file you'll see that q is being assigned as the parameter
String q =request.getParameter("q"); /* q = parameterValue */
But in the subsequent lines q is never used:
String str="This is JSP string loading from JSP page in ajax, loading time :";
java.util.Date dt=new java.util.Date();
out.print(str+dt);

"parameterValue" is any string value you want to pass through for the page's query string parameter called "q". The following line of code illustrates where it gets concatenated to the URL:
var url="loadJSP.jsp";
url=url+"?q="+str;
The JSP page on the server will then query the value of the parameter "q" and do something with it. In this instance, though, nothing is done with it. I'm assuming it's only there for illustration purposes.

It is just a plain string that you need to pass as a parameter to the loadContent() function in Javascript.You can replace 'parameterValue' by the actual value that you want to use.

Related

Add parameters to url with onSubmit using a Javascript function

I want to add html parameters to the url with onsubmit. I have 2 forms(1 GET, 1 POST), want to use 1 button to submit them both(Using the POST form button) When the submit button is pressed use onSubmit to call a javascript function, where parameters are "appended" to the url.
I was thinking about doing something like this:
function onSubmitForm() {
url = "localhost:8080/test/index.php?Title=document.getElementsByName('title')[0].value";
//I don't know how to actually call the url.
}
EDIT
I got what I wanted:
Appending form input value to action url as path
First, you have to concatenate the string's static and dynamic parts. Then, you can redirect.
function onSubmitForm() {
window.location = "localhost:8080/test/index.php?Title=" +
document.querySelector('title').textContent;
}
NOTES:
Only form fields have a .value property. If you are trying to get
the text within an element, you can use .textContent.
.getElementsByName() scans the entire document and makes a
collection of all the matching elements. That's wasteful when you
know you want only the first one and, in the case of <title>, there
is only ever going to be one of those in a document anyway. Use
.querySelector() to locate just the first matching element.
ES6
NOTES :
Don't forget to use Babel for converting your code in ES5.
I purpose to you this solution :
function onSubmitForm() {
window.location = `localhost:8080/test/index.php? Title=${document.querySelector('title').textContent}`
}
This way of doing with backtick is even simpler than in ES5, let me explain, before we had to concatenate with the sign + ourVariable + the continuation of our string of character.
Here we have more of that. And we can write on several lines as well.
Then ${} is used to pass a variable inside
Documentation if you want : Literal template string

Convert Razor String Variable to Javascript String Variable in MVC

I am trying to pass my string variable (even boolean) on my cshtml view to my javascript section. I can successfully pass the value from razor section to javascript if its integer. But what I want to accomplish is to pass the string value. Here is my sample code from my .cshtml:
string strAnnouncement = "My announcement";
int intCounterValue = 1200;
To receive the value on Javascript, here is my code:
//Cannot get the value, always error on Developer Tool console
var SessAnnouncement = #strAnnouncement;
//Can get the value successfully
var SessInitTimer = #intCounterValue;
As you can see, I can get the value via javascript on SessInitTimer which is 1200. But on SessAnnouncement, I get a Uncaught ReferenceError: My announcement is not defined.
How can I get the strAnnouncement value on my razor section and pass it on script section?
They are treated as variable and since you have not defined them you get the said error.
You need to wrap in quotes to be treated as string.
var SessAnnouncement = "#strAnnouncement";
A better approach would be to use JSON.Encode() method
var SessAnnouncement = #Html.Raw(Json.Encode(strAnnouncement));

HTML Append Variable to Query String

I have http://localhost/?val=1
When I click on a link, is there a way this link can append a query variable to the current string, for example:
Link
so when I click it the url would be:
http://localhost/?val=1&var2=2
but when I click the link it removes the first query string and looks like
http://localhost/&var2=2
Is such a thing possible with normal HTML?
You can't do that using only html, but you can do it with js or php:
Using JS:
<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>
Using Php:
Link
Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable
Notice 2: this is not a professional way, but it could work if you need something fast.
Basically you want to get your current URL via JavaScript with:
var existingUrl = window.location.href; // http://localhost/?val=1
Then append any Query Strings that are applicable using:
window.location.href = existingUrl + '&var2=2';
or some other similar code. Take a look at this post about Query Parameters.
Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.
Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.
You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

Check if params was passed or not

I have this Javascript function which i use to append elements do my form. When the form is submitted, all elements are passed in as params.
Here's the problem. The elements that my function appends are part of a Hash. This basically works as the rails "nested-attributes".
All seems to be working fine, except when one of the "Hashs" is empty. When i delete all elements from the collection, the hash params is not passed to the controller.
Example (Imagine i appended Honda, Toyota, Hyundai using my JS function)
Cars
[Honda]
[Toyota]
[Hyundai]
This is how the hash is set up in the JS function (every time i click the "add"):
CarsHash.name= "cars_hash"+"["+"tmp_cars"+"]"+"["+i+"]"+"car_name"
If i were to submit the form, the values would be passed as Hash to the controller like this:
cars_hash=>{tmp_cars=>"{"1"=>{car_brand=> "honda"},"2"=>{car_brand=> "toyoda"},"3"=>{car_brand=> "hyundai"}"}
However, if i decide to delete all those values from the hash (using the delete button which also has functionality stated on the JS function) and submit the form, the Hash is not even present as a param. Then, when i get to my controller and i try to populate the variable i use for iterating/inserting into my DB:
Controller
cars_hash = params[:cars_hash][tmp_cars]
It gives me this error:
undefined method `[]' for nil:NilClass
I understand, the param is not even present so its essentially nil. I tried with all this possibly options:
if not params[:cars]["tmp_cars"].blank?
if not params[:cars]["tmp_cars"].empty?
if params[:cars]["tmp_cars"].present?
if params[:cars]["tmp_cars"] != nil
But no luck. Can anyone suggest me a way to get this to work? Again, the param will only be not nil IF the hash as a value. For it to have a value, an element must be appended to the document through the JS function.
Try doing:
cars_hash = params[:cars_hash] && params[:cars_hash][tmp_cars]
I would strongly recommend installling andand gem which is perfect for situations like this. With this gem you can wirte the code above like:
cars_hash = params[:cars_hash].andand[tmp_cars]
UPDATE:
Your code was not working because params[:cars_hash] returned nil, on which you were trying to call [] method, and such a method is not defined for nil object. Hence you need to check whether params[:cars_hash] is nil or not before you call anything on it.
&& operator have this nice property that it is not even executing the right argument whan the left argument is falsy - there is no point of doing this. Since every expression in ruby returns value of the last executed command, && returns whatever left expression returns if it is falsy (false or nil) and otherwise it runs the expression on its right side and returns its value. This is pretty common to use this && in this context in Ruby.

JSON/AJAX and local variables in JavaScript functions

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]);
});
}

Categories

Resources