How to pass only a number in a form URL - javascript

I have the code below:
<form action="/files/" method="get">
<h3>GET /files/{fileId}</h3>
<label>File ID: </label><input type="text" name="fileID" />
<input type="submit">
<br><br>
</form>
this responds with a URL: /files/?fileID=88
However, I want the URL to look like: /files/88
Does anyone know if this is possible and if so could you point me in the right direction to do so?

It can be done from the browser, although it's not clean as you would have to use Javascript to change the form's action attribute.
// get hold of the form element (it needs an id)
var form = document.getElementById('form-id'),
// get hold of the input tag (it also needs an id)
fileIdInput = document.getElementById('file-id'),
// get the action attribute, e.g. '/files/'
baseAction = form.getAttribute('action');
// add an even listener to listen for the form being submitted
form.addEventListener('submit', function() {
// get the value from the file id input
var fileId = fileIdInput.value;
// when it submits, change the action e.g. '/files/' + 88
form.setAttribute('action', baseAction + fileId);
// return true so that the form submits
return true;
});
It's not really maintainable code and server side solutions to this sort of problem have been around for a while.
If you're using Express and you already have a handler for the /files/:id endpoint, then I would suggest using AJAX to make the request instead of a standard GET form.
For example using the fetch api. Fetch is a new interface for doing AJAX requests, however it's not yet implemented in all browsers. So you might want to include a polyfill script.
// the first argument for fetch is the URL
fetch('/files/' + id)
// fetch returns a promise that we can call `.then()` on.
// our function will be called when the ajax request is done
.then(function(data) {
console.log(data);
})

Related

How send string parameter using Post Method from the view to the controller ASP.NET [duplicate]

Here is a line of code in my Controller class:
return JavaScript(String.Format("window.top.location.href='{0}';", Url.Action("MyAction", "MyController")))
Is there a way to make it use the verb=post version of MyAction?
You can't use POST by simply navigating to a different URL. (Which is what you'd do by changing location.href.)
Using POST only makes sense when submitting some data. It's not clear from your code what data would actually be POSTed.
If you really want to initiate a POST via javascript try using it to submit a form.
I came across the same problem myself and solved it using a data- attribute and some jQuery. The benefit of doing it this way is that you still get the correct URL when you hover over the link, even though it does a POST. Note that the Html.BeginForm contains the default action in case the user hits the enter key.
HTML (ASP.NET MVC3 Razor)
#using (Html.BeginForm("Quick", "Search"))
{
<input type="text" name="SearchText" />
Search
Advanced
}
jQuery
$("a[data-form-method='post']").click(function (event) {
event.preventDefault();
var element = $(this);
var action = element.attr("href");
element.closest("form").each(function () {
var form = $(this);
form.attr("action", action);
form.submit();
});
});
Continuing off of Matt Lacey's answer, your action could return a bit of Javascript that does this:
Use jquery to add a new form to the DOM
Use jquery to submit the newly added form
Something like this: (untested code)
var urlHelper = new UrlHelper(...);
var redirectUrl = urlHelper.Action("MyAction", "MyController");
var redirectScript = String.Format(#"
var formTag = $('<form action=""{0}"" method=""post"" id=""redirectForm""></form>');
$(body).append(formTag);
formTag.submit();"
, redirectUrl
);
return JavaScript(redirectScript);

JavaScript to PHP form, based on user input

I have a simple form on my homepage (index.php), that takes one user input.
<form action="/run.php" method="POST" target="_blank"
<input type="text" name="userinput">
<button type="submit">Run!</button>
</form>
That input is then passed to run.php where the content is displayed and inserted into a MySQL database.
However, I need to run JavaScript functions on that user input, and then input the results (from the JavaScript function) into the database (so passing the value from JavaScript to PHP).
I originally had the JavaScript in the run.php, which worked for calculating and displaying the value, but I was unable to pass the value to PHP to insert into the database.
From what I've read, you can't pass JavaScript values to PHP on the same page, as it requires some sort of POST or GET, so I'm attempting to run the JavaScript functions on the homepage index.php and then use a hidden input field to POST the value to the run.php file.
<input id='hidden_input' type='hidden' name='final-calc' value='random(userinput)' />
Where the function is a JavaScript Promise:
function random(userinput) {
....
.then(function(userinput) { // Function needs to use the userinput from the form
// calculations
return X //(X being any random value)
}
}
The two problems I'm running into is that:
I can only get the userinput value after the user enters a value and submits the form, so I don't believe I can pass that userinput value into the JavaScript function and still POST the returned value?
The JavaScript function is an asynchronous Promise, but apparently, this might not have an effect - so it may not be a problem.
The key here is AJAX. You have to retrieve the userinput using plain JS, make any calculations needed and then send the results to your PHP script. I left a fiddle: https://jsfiddle.net/k5xd54eu/1/
<input type="text" id="userinput" name="userinput"/>
<button onclick="inputhandler();">TEST</button>
<script>
function inputhandler() {
var text = document.getElementById('userinput').value;
alert(text);
/*DRAGONS BE HERE*/
/*THEN*/
/*USE AJAX HERE TO PASS THE RESULTS TO PHP SCRIPT*/
}
</script>
I'm not explaining how to implement the AJAX call to send the results, mainly because it's a matter of taste too. For example you can use plain JS or a library such as jQuery (which is my personal preference, since it's very clean and easy). Take a look here:
http://api.jquery.com/jquery.ajax/
and here:
https://www.w3schools.com/jquery/jquery_ajax_intro.asp
for more information.
EDIT: Since I've mentioned AJAX, it would be more correct to include some code. So this is what I generally use for simple POSTs (it's based on the jQuery library so be careful to include it):
var url = 'ajaxhandler.php';
var stuff = '1234abcd';
$.ajax({
type: "POST",
url: url,
data: {stuff: stuff},
success: function (data) {
/*Do things on successful POST*/
}
});

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

Send a value from a cookie to a script

A user input form on my site sends values to a script located on a different server:
<form action="https://mycompany.formprocessor.com/script/" method="post" name="MyForm" onsubmit="return myFunction();"> etc.
I am recreating that form with a modified functionality. Instead of sending the form values directly, I save them in a cookie, and only then, when a certain event happens, I want to send input values from that cookie to the script located at the url provided as the value for action attribute.
Something like this:
on event {
// send cookie value to https://mycompany.formprocessor.com/script/ using "post" method;
}
How can this be done?
First of all, you will need to use some cookie functions to store the values in cookie(s) and then access the input values you have saved in those cookie(s). Some cookie functions with explanation how to use them are here: http://www.codelib.net/javascript/cookies.html
Then you will need to have a way of sending the data across domains. To do that I suggest that you use a form containing a hidden field and then submit that form to the other server.
Like this:
<form method="post" action="https://mycompany.formprocessor.com/script/">
<input type="hidden" id="hiddendata" name="data" />
</form>
<script>
function onEvent() { /* call this function when your desired event happens */
var cookiedata = readCookie('cookiename');
var datafield = document.getElementById('hiddendata');
datafield.value = cookiedata;
datafield.form.submit();
}
</script>
Note that I suggest you have the program at formprocessor return 204 No Content as its HTTP status code so that the document itself is not reset. Otherwise the browser will replace the current page with the contents of https://mycompany.formprocessor.com/script/ after the data is submitted. This is the a way of doing AJAX that does not block cross-domain requests.
The following method will only work if you are content with using GET requests to send the data to the server.
You can set the src attribute of included elements on the page, like an img element, to a URL like this (initial image is from http://commons.wikimedia.org/wiki/File:1x1.png)
<img id="hiddenimage" width="1" height="1" src="1x1.png" />
<script>
function onEvent() { /* call this function when your desired event happens */
var cookiedata = readCookie('cookiename');
var dataimage = document.getElementById('hiddenimage');
dataimage.src = 'https://mycompany.formprocessor.com/script/?data=' + encodeURIComponent(cookiedata);
}
</script>
First of all, you will need to use some cookie functions to store the values in cookie(s) and then access the input values you have saved in those cookie(s). Some cookie functions with explanation how to use them are here: http://www.codelib.net/javascript/cookies.html
Then you will need to have a way of sending the data across domains. To do that I suggest that you use a form containing a hidden field and then submit that form to the other server.
Like this:
<script>
function onEvent() { /* call this function when your desired event happens */
var cookiedata = readCookie('cookiename');
var datafield = document.getElementById('hiddendata');
datafield.value = cookiedata;
datafield.form.submit();
}
</script>
Note that I suggest you have the program return 204 No Content as its HTTP status code so that the document itself is not reset. Otherwise the browser will replace the current page with the contents of https://mycompany.formprocessor.com/script/ after the data is submitted. This is the a way of doing AJAX that does not block cross-domain requests.
I am about to describe another way of sending cross-domain requests without submitting a form... please wait.
The following method will only work if you are content with using GET requests to send the data to the server.
You can set the src attribute of included elements on the page, like an img element, to a URL like this (initial image is from http://commons.wikimedia.org/wiki/File:1x1.png)
<img id="hiddenimage" width="1" height="1" src="1x1.png" />
<script>
function onEvent() { /* call this function when your desired event happens */
var cookiedata = readCookie('cookiename');
var dataimage = document.getElementById('hiddenimage');
dataimage.src = 'https://mycompany.formprocessor.com/script/?data=' + encodeURIComponent(cookiedata);
}
</script>
You can get the values set in the cookie by using "document.cookie".
Update:
var cookievalue= document.cookie;
var xmlhttp= new XMLHttpRequest();
var url="https://example.com/path?value="+cookievalue;
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send();
The answer kind of depends on how the script that's accepting the values is set up. For storing and retrieving the values, balaji's suggestion is good enough. The plugin located here makes storing and retrieving values to/from cookies very easy.
So, for e.g. if the function you are sending the values to is something like this:
public void myFunction(firstValue, secondValue){
// logic here
}
then the way you'd send the values is something like this:
https://mycompany.formprocessor.com/script/firstValue="value_from_cookie"?secondValue="value_from_cookie"

How to get a specific value from JavaScript to C# coding?

After creating everything by the JavaScript dynamically I want to move a single specific value into my C# code; I don't want everything, I have written in the code that which variable I want to be moved into my C# code:
<script>
var test="i want this variable into my c#";
var only for javascript="i don't want this to be travel when i click on submit button";
var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type', "submit");
s.setAttribute('value', "submit");
</script>
To get a client variable "into c#", you need to make it part of a request to the server where c# is running. This can be as simple as appending it to a URL, or you may create a new field, or you may populate an existing field and send it.
// a variable
var test = "a value to be sent to the server";
// put the value into a hidden field
document.getElementById("hdnValue").value = test;
// submit the form containing the hidden field
document.getElementById("form1").submit();
Since we are talking about c#, I assume the server is ASP.Net, either web forms or MVC. For MVC, ensure that there is a controller method that takes a corresponding parameter. For web forms, you may include <input type="hidden" runat="server" clientidmode="static" id="hdnValue" />. The page will then have access to this value in the code behind.
i want to travel a single specific value into my c# code ... i don't
want everything
An alternate (and possibly more elegant) way of sending a single value to the server is to POST the value asynchronously using AJAX. I would suggest using jQuery to make this easier, but it can also be done in plain JavaScript.
Here's a jQuery example of an AJAX post:
$.ajax({
url: "http://yourserverurl/",
type: "POST",
data: { test: "a value to be sent to the server" },
success: function(data){
// an optional javascript function to call when the operation completes successfully
}
});

Categories

Resources