How can I pass the value of an input in a href - javascript

I'm trying to pass the LoadNumber into a php file to use in a query and result in a FPDF on a button click. the button works but the value its passing is $(' not the value I wanted. Where am I going wrong. Here is my code.
$(location.href="dispatch.php? LoadNumber=$('#LoadNumber').val()")};

You can do it like:
// Get the LoadNumber value first
var value = $('#LoadNumber').val();
// Set the url with query string properly
var url = "dispatch.php?LoadNumber=" + value ;
// Re-direct to the url now
location.href = url;
Just to make things clear for you.
This can also be done in one line like:
location.href = "dispatch.php?LoadNumber=" + $('#LoadNumber').val();

Use it in this way :
$(location.href="dispatch.php? LoadNumber="+$('#LoadNumber').val())};
Don't put $('#LoadNumber') in quotes.

If you want to set that value to location.href, just write the following:
location.href = "dispatch.php?LoadNumber=" + $('#LoadNumber').val();

window.location = 'dispatch.php?LoadNumber=' + $('#LoadNumber').val();

Related

What is the modern simple way to pass data from one page to another using javascript?

I need to pass data from one HTML(source.html) to another HTML(destination.html) and assign this passed data to value attribute in <input> tag at the destination.html page using modern javascript techniques.
Here is my function # source.html.
function sentData(){
var send = "Send Me"
}
Here is my <input> tag # destination.html.
<input id="sendedData" type="Text" value="send">
What is the best modern simply way to do this? your advice would be really appreciated.
You can use localStorage
In the first page store the item as
localStorage.setItem('keyName','valueInString');
In the second page retrieve the value
if(localStorage.getItem('keyName')){
document.getElementById('sendedData').value = localStorage.getItem('keyName')
}
The best way same as the old on is a form with submit() if you don't want to ask for an input like you post, you can hide the input and a as your trigger.
If you need to use JS for some reason brk answear is the best one.
basicly you name the page and then you tell them to update a label or an input on that specific page.
You can either use localStorage like so:
source.html:
function sentData() {
var data = "Send Me";
localStorage.setItem("data", data);
}
destination.html:
document.getElementById("sendedData").value = localStorage.getItem("data") ? localStorage.getItem("data") : "Default";
Alternatively, use a URL parameter / query string:
source.html:
function sendData() {
var data = "Send Me";
var url = new URL(window.location.href);
url.searchParams.set("data", data);
}
destination.html:
var url = new URL(window.location.href);
document.getElementById("sendedData").value = url.searchParams.get("data") ? url.searchParams.get("data") : "Default";

How to reload a page with javascript sending both GET and POST, and append additional parameter?

I have a page with an select box, which fires an onChange event. In this Java-Script snippet, I would like to reload the current page, including the GET and POST parameters that where sent during request. AFAIK, this can be achieved by using window.location.reload(), or window.location.href = window.location.href when sending POST data is not required.
However, I need to append an additional value (actually, the value of the select element), additionally to the previously sent element. I do not care whether the data is sent using POST or GET. Is there a way to achieve the desired behavior?
To accomplish this you are going to have to rebuild a request from scratch. In the case of get requests, the arguments are easily accessible in the query string but post requests are a little trickier. You will need to stash all that data in hidden input elements or something so that you can access it.
Then you can try something like this:
var queryString = windlow.location.search; //args from a previous get
var postArgs = $("#myPostArgsForm").serialize(); //args from a previous post... these need to be saved and added to the html by the server
//your additional data... this part you probably need to adapt
//to fit your specific needs. this is an example
var myNewArgName = encodeURIComponent("newArg");
var myNewArgVal = encodeURIComponent("Hello!");
var myNewArgString = myNewArgName + "=" + myNewArgVal;
//if there is no queryString, begin with ?
if(!queryString) {
queryString = "?"
}
//if there is, then we need an & before the next args
else {
myNewArgString = "&" + myNewArgString;
}
//add your new data
queryString += myNewArgString;
//add anything from a previous post
if(postArgs) {
queryString += "&" + postArgs;
}
window.location.href = window.location.hostname + window.location.pathname + querystring
<form id="myPostArgsForm">
<input type="hidden" name="prevQuery" value="whats up?" />
</form>
Pretty simple really; have onChange fire a function that uses getElementById to figure out the selector value and then just use window.location to send the browser to the literal: http://yourdomain.com/yourpage.html?selectval=123
then, in the body onload() method, fire another JS function that checks the "get var" like:
function (GetSelector) {
var TheSelectorWas = getUrlVars()["selectval"];
alert(TheSelectorWas);
}
and do whatever you need to do in that function (document.writes, etc). BTW, posting the actual code you're using is always a good idea.
-Arne

Putting Javascript variable in html link

I have a dynamic variable that gets updated by users of a webpage in a script and when the user clicks on a hyperlink I need to be able to send that variable to another webpage. So I need something like
Link
to work but I am not sure the exact syntax on how to do this. I already have a getter in my JavaScript I just need to be able to access it when the user clicks on a link.
You could either use an onclick action to send you to a function that navigates the page for you.
Or
You could update the href attribute anytime that value of variable needs to be changed.
The second option is probably preferable, but it largely depends on what else is going on in the page and how variable is set
it looks very familiar with this:
How to redirect on another page and pass parameter in url from table?
link
Native JS:
document.getElementById('redirectwithid').setAttribute('href','yoururl?variable=' + variableGetter());
jQuery:
$("#redirectwithid").click(function() {
var yourVariable = variableGetter();
if (yourVariable != null) {
window.location = 'yoururl?variable=' + yourVariable;
}
});​
Add for Native JS:
I don't know your code so just insert the code where you want to update your variable - at the same time the href will change.
Edit:
If you want to add multiple variable like ?variable=1 and a second variable2=2 you can achieve this by adding a & between the variables, like this:
NativeJS:
document.getElementById('redirectwithid').setAttribute('href','yoururl?variable=' + variableGetter() + '&variable2=' + variable2Getter());
JQuery:
$("#redirectwithid").click(function() {
var yourVariable = variableGetter();
var yourVariableTwo = variableTwoGetter();
if (yourVariable != null) {
window.location = 'yoururl?variable=' + yourVariable + '&' + yourVariableTwo;
}
});​

Can I change the parameter or is the action static/"locked down"?

My code works, I can upload a file.
But how do I set typeNavn to something else runtime, so the value depends on witch tap is selected on the page.?
I want to either set typeNavn as either "billeder" or "dokumenter". Now it's always "billeder" from ViewBag.typeNavn, is that possible and how?
Is the action so static, that I can't change any of it's parameters runtime? I have tryed messing around with a callback, a JavaScript variable and a Razor variable. And it either doesn't work for me, or doesn't change it's first value.
var upload = $('#upload').wijupload(
{
// Note: the next two lines must be on one line for it to work.
// It's only two on SO so we don't have the x-scrollbar.
action: '#CleanHtml.Clean(Html,#Url.Action( "UploadFiles", "Dokument",
new { typeNavn = ViewBag.typeNavn } ))'
});
You need a JavaScript variable that can be changed dynamically, and then used as part of the action url.
var typeNavn = ''; // Declare this somewhere. This is updated by some means.
var cleanHtml = '#CleanHtml.Clean(Html)'; // I don't know what Clean() does.
var upload = $('#upload').wijupload(
{
// Note: the next two lines must be on one line for it to work.
// It's only two on SO so we don't have the x-scrollbar.
action: '/UploadFiles/Dokument?typeNavn=' + typeNavn)'
});
OK the layout of the above code may not be what you need (I don't know what cleanHtml is supposed to be), but the core idea of using a variable typeNavn is key here. You need some means of updating that variable to reflect the type selected i.e. a dropdownlist of something.
It's a bit unclear...do you have a radio/checkbox/etc where you want to change typeNavn or do you want to set that in the controller? Url.Action will render a string which you could certainly change using javascript. However in what context you are using this is a bit unclear.
Just going to guess that you want something like this:
$(".list").change(function(){
var list = $(this);
var url = baseUrl + "?typeNavn=" + list.val(); // How you get baseUrl variable is up to you
var upload = $('#upload').wijupload(
{
action: url
});
});
One thing you can do is pass the TabName in the action of controller as a parameter when loading view. And set the viewbag's value accordingly. So this will not be static and work perfectly.
second way, you can update querystring paramter name by jquery
You can use a placeholder value which can be replace with any desired value using the .replace() method. Here is pseudo-code. In example I have used -1 as placeholder value
Code
var typeNavn = '#ViewBag.typeNavn';
var action = '#CleanHtml.Clean(Html, #Url.Action( "UploadFiles", "Dokument",
new { typeNavn = -1} ))'; //Really have no idean
//Here you can use -1 as place holder which you can replace using JavaScript like
action = action.replace('-1', typeNavn);
var upload = $('#upload').wijupload(
{
action: action
});
Note: I have no idea about CleanHtml.Clean

Injecting json object property into an anchor's href attribute using the Play! Framework

I have a jQuery ajax call that looks like this:
$.ajax({
type : 'GET',
dataType : 'json',
url : '/Zoo/animals',
success : function(data){
var count = data.length;
for(var i = 0; i < count; i++) {
${'#tableBody').append('<tr><td>');
${'#tableBody').append('' + data[i].name + '');
${'#tableBody').append('</td></tr>');
}
}
})
Now all of this works fine except for the href attribute. Play! gives me the following error:
Exception raised was NullPointerException : Cannot get property 'name' on null object.
The json string that gets returned from the ajax call is fine as the text of the link shows up as the name of the animal as expected. I would like to pass the name of the animal to the Animal.index action however have been unable to do so.
Update:
As others have mentioned, I have also tried this:
${'#tableBody').append('' + data[i].name + '');
which just results in the link of:
localhost:9000/animal/index?name=+%2B+data[i].name+%2B+
The problem is that Play! generates the url when the file is served, well before any javascript is executed. No change to the string or quotes here or there is going to help you.
A workaround:
var url = "#{Animal.index(XXX)}".replace('XXX', data[i].name);
${'#tableBody').append('' + data[i].name + '');
This allows Play! to generate its url at "compile" time, and then javascript simply executes a replace at "run" time. Not sure if Play! will look for a variable named XXX, if so, add a dumby variable named XXX with value "XXX" on the server side.
UPDATE
I don't have a Play! instance in front of me to fiddle with, but instead of a variable, you could probably also insert the string directly as a value by quoting the XXX:
var url = '#{Animal.index("XXX")}'.replace('XXX', data[i].name);
And then you wouldn't need a variable named XXX. The details require a bit of playing around, although the idea is the same.
This sounds like a job for the jsAction tag. It generates a javascript function which works along the same lines as davin's answer.
You would put var animalAction = #{jsAction #Animals.index(':name') /}; somewhere before your ajax call, then change your link generation code to:
${'#tableBody').append('<tr><td>');
${'#tableBody').append('' + data[i].name + '');
${'#tableBody').append('</td></tr>');
You'll notice the generated function takes an object as it's argument, so it can support as many parameters as you want.
What isn't explicitly clear in the docs is that the label (:name) must be the same as the name of the parameter in the corresponding controller action (public static void index(String name)), which of course must be the same as how it's specified in the routes file (GET /animals/{name} Animals.index).
data is a javascript object, you need to specify that similar to how you are printing the text of the link. Can you try this?
${'#tableBody').append('' + data.name + '');
You are looping over data array but you need to reference each data object by the index i so like data[i]. I would try this:
$.each(data, function(k, item) {
$('#tableBody').append('<tr><td>' + item.name + '</td></tr>');
});
This will replace everything inside your success callback
you should change this line-
${'#tableBody').append('' + data[i].name + '');
to this-
${'#tableBody').append('' + data[i].name + '');

Categories

Resources