Recently, I've been writing some Javascript that interacts with a page. As a part of this, I need to be able to submit an HTML input field.
From what I've seen, most of the time input fields are a part of their own form. For example, StackOverflow's search bar has the form "search" and input field "q".
However, on the particular page that I'm working with the input field does NOT have its own form. It is only a part of a greater form that encompasses many sections of the page.
I'm aware that you can submit forms by calling the .submit( ) method on the form. However, this does not appear to work for individual input fields.
I know that this input field can be submitted individually, because when you manually type text and press Enter it works. I have no issues with the input field, and I can easily change its value.
Basically, what my question boils down to is:
How can I submit an individual input field without calling form.submit( )?
if you're sending only this input you can use XMLHttpRequest():
var input = document.getElementById('inpputId');
var parameters=input.name+"="+input.value;
var http=new XMLHttpRequest();
http.open('POST','yourfile.php',true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onload=function(){
//write code after receiving the content
}
http.send(parameters);
You can submit the field by using javascript:
Then the java function can submit the value:
function someJSFunction(var event) {
var url='/saveValue.php';
var value="savethis="+this.value;
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(params);
}
Code untested so needs some work :)
You can make a post pretty easily with jquery.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#btnSubmit').click(function() {
var inputVal = $('#inputField').val();
$.ajax
({
type: "POST",
url: 'your_url_for_handling_post',
contentType: "application/json",
data: JSON.stringify({"Username":inputVal})
})
.done(function(data) {
console.log(data);
});
});
});
</script>
</head>
<body>
<input type='text' id='inputField' name='username' />
<input type='submit' id='btnSubmit' value='Submit' />
<!-- you can use any element to trigger the submit
<div id='btnSubmit'>Submit</div>
-->
</body>
</html>
EDIT: json is not a requirement. I just put that in there because that's how I normally do it. You can definitely just send the value by itself.
Related
I have a form with an <input type=number> field.
The form is not submitted via <button type=submit>, but the input field values are collected with a Javascript function and passed to an AJAX call. In a classical submit, Firefox would prevent me from submitting the form when one of the input fields is invalid. But in this case it doesn't happen. Instead, Firefox sets the invalid field value as empty. As my parameter isn't required, I can't distinguish on the server side whether it was invalid or just intentionally left out. A small working sketch of what my program does:
<html><head><meta charset="utf-8">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(
function() {
let data = {somefield: $("#field").val()};
console.log("data to transfer:", data);
$.ajax({
type: "POST",
dataType: "json",
url: "http://httpbin.org/post",
data: data,
success: function(e) {
console.log("server response:", e.form);
}
});
}
);
});
</script></head><body><form>
<input id="field" type="number" />
<button type="button" id="button">Submit</button>
</form></body></html>
Chrome handles this situation better -- it doesn't allow me typing non-number characters in number fields. Trying to emulate this behaviour with jQuery bears other problems that would probably be worth another question.
What would be the best way to handle this in Firefox?
Please forgive the basic question, I'm very new to Javascript and web development in general. I want to use a script on one page of my site to programmaticaly press a button to submit a form on another part of the site, making a POST request. The html I have to access is the following:
html
<form action="thing.jsp" method="post"> // Beginning of form
...
<input type="submit" id="submit" value="Do something"> // Button code
...
</form>
And I think the Javascript should look something like this:
JS
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', "/stuff.jsp", true);
var params = "???????"; // What do I need to put here?
xhr.send(params);
</script>
From reading around online, my suspicion is that I may just need to get the right value for params? Though if there's another way of achieving the same result (e.g. by just sending a POST request without doing anything to the button), I'd be perfectly happy to go with that.
Thanks in advance for your time and wisdom.
You don't need to use ajax, just use this:
<input type="button" value="GO" id="buttonId" />
<script>
function go() {
document.location.href = 'http://google.com';
}
document.getElementById('buttonId').onclick = go;
</script>
please notice the button type should be 'button', not 'submit'
Using jQuery - a JS library - you can simply send a HTTP GET Request. This can then be picked up in PHP using $_GET['key'] which will hold the value.
$(function() {
$('#unique-id-btn').click(function() {
$.get('file.php', { key: $('unique-id-input').val() }).done(function(response) {
alert(response);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="unique-id-input" placeholder="enter something...">
<button type="button" id="unique-id-btn">Click me</button>
Note, you will need to create the file.php. Inside, it will control what happens with that data being sent across, ie:
$data = $_GET['key'];
echo $data == "foo" ? "bar" : "tell me foo!";
Also note you can only run PHP in a .php file extension, not JSP.
I don't know if it is possible or not. I referred some site, but I didn't get exact answer.
I am using
click
When I send this request to server in the response page easily I can see "id=4" in address bar, obviously which is not secure, But in post request we cant see this.
So can we convert a get request to post or ant other way is there to hide this from address bar.
Thanks in advance.
Firstly, to convert GET to POST, simply change the link to a form:
<form id="myForm" action="xyz" method="post">
<input type"hidden" name="id" value="4"/>
</form>
This form will not be visible and you can easily auto-submit it using JavaScript in your link:
click
Secondly and more importantly, both GET and POST are equally not secure over HTTP. To secure them, use HTTPS and they will be both equally secure, so no need to change if GET is working for you.
click
Dynamically create a from and post it.
function postForm() {
var form = $('<form method="POST" action="xyz"></form>');
$(document.body).append(form);
form.append('<input type="hidden" name="id" value="4"/>');
form.submit();
}
As Racil suggested in comments, you can also do the following
click
and then
$('#postLink').click(function(e){
e.preventDefault();
//create form and post
});
Call a java script function on onclick which will make the form submission using post method or you can use ajax call to post the data and get your desired results.Use id as a parameter in function.
<a href="#" onclick="postData(4)">
/// Javascript function for ajax call
function postData(id){
var param = { "Id": id};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "xyz.aspx",
data: JSON.stringify(param),
success: function (data) {
/// Recive data here or do your stuff here
}
}
Make a form having single input type hidden and onclick set value of that input type hidden element and submit form using jquery.
<form id="target" action="destination.html">
<input type="hidden" id="hiddenValue">
</form>
/// Javascript function for setting value of hidden element and form submission using jquery
function postData(id){
$("#hiddenValue").val(id);
$("#target").submit();
}
Hopefully this will solve your problem.
I need to post some data to a webservice using a single button click.
I don't want to show the reply received from the server, which a simple HTML form does. So I came up with the following code:
<!DOCTYPE html>
<html>
<head>
<script>
function sendData() {
var form = document.createElement('form');
form.action = "https://posttestserver.com/post.php";
form.method = 'POST';
var input = document.createElement('input');
input.type = 'hidden';
input.name = "args";
input.value = "on";
form.appendChild(input);
form.submit();
alert("Submited!");
}
</script>
</head>
<body>
<button onclick="sendData();">Click Me!</button>
</body>
</html>
Please enlighten me what exactly is going wrong, because its not posting any data.
Any reason you have to use JavaScript to create the form? Is it simply not posting the input or is the form failing to submit? You can always use your Web Inspect tool to see the request.
Try opening your web inspector and look at the console for any JavaScript errors.
your posted data found at
http://www.posttestserver.com/data/2015/12/16/21.17.23451563624
plz, see the image.
you can use ajax to post data instead of form submit.
params = {
'input':'on'
}
$.ajax(url,post,params,succ,err)
Solutions as per my understanding :
If you are placing script in head tag, refer 'Where should I put <script> tags in HTML markup?'. The conclusion is to put scripts in the head tag and use the async or defer attributes.
Append form to your body before submitting the form.
document.body.appendChild(form);
Place script before body tag.
Not sure why you want to create a form using JS just to post some data to server when you could have used ajax. As already mentioned in previous answers you can use jQuery. If you are reluctant to use jQuery, you could have used XML HTTP Request (XHR) object
A simple solution using jQuery would be
$.ajax({
type: 'POST',
url: 'https://posttestserver.com/post.php',
data: {'args': 'on'}
});
Since you want the data to send on clicking a button, you could trigger the event on button click
$('button').on('click', function() {
$.ajax({
type: 'POST',
url: 'https://posttestserver.com/post.php',
data: {'args': 'on'}
});
});
My main aim was
I don't want to show the reply received from the server
So I added an IFRAME in the page and then added it as the form's target
<form action="MYLINK" method="POST" target="hidden-form">
...
</form>
<IFRAME style="display:none" name="hidden-form"></IFRAME>
Now the reply from server is not visible
I have TWO forms on my website.
Is it possible when I submit one of these, it will take form data from a particular field in the other form?
I am using the Recurly system with PHP.
You can write your own function.
function submit (){
document.getElementById("firstform").submit();
document.getElementById("secondform").submit();
}
You can then make a button that calls this function.
If this doesn't work, try again using ajax.
Example
You can do it with javascript.
For example:
var request =false;
function submit()
{
var yourobject = document.getElementById("yourobject").value;
data = "yourobject" + "=" + encodeURIComponent(yourobject);
request.open("POST", "yourpage.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(data);
}
And the input:
<input type="button" onclick="submit()" value="Submit" />