Two forms - one submit button? - javascript

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" />

Related

don't get my data with XMLHttpRequest POST across [duplicate]

I am trying to submit a form via ajax using the post method and a FormData object.
Here is a simplified version of the JavaScript:
var form=…; // form element
var url=…; // action
form['update'].onclick=function(event) { // button name="update"
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
};
The form has:
a button (type="button" name="update") to run the script
no action and method="get"
My PHP script has the following:
if(isset($_POST['update'])) {
print_r($_POST);
exit;
}
// more stuff
print 'other stuff';
When I try it, the PHP falls through to the rest of the code, and I get the other output, rather than what I expect from the print_r statement.
I have tried the following variations:
new FormData() (without the form). This does work if I add the update data manually.
new FormData(form). This does not work, whether I add the update manually or not.
changing the form method to post.
Firefox, Safari & Chrome on MacOS; all current versions.
The from itself looks something like this:
<form id="edit" method="post" action="">
<p><label for="edit-summary">Summary</label><input id="edit-summary" name="summary" type="text"></p>
<p><label for="edit-description">Description</label><input id="edit-description" name="description" type="text"></p>
<p><label for="edit-ref">Reference</label><input id="edit-ref" name="ref" type="text"></p>
<p><label for="edit-location">Location</label><input id="edit-location" name="location" type="text"></p>
<p><button type="button" name="update">OK</button></p>
</form>
What should I do to submit the get this to work?
No jQuery, please.
The content type when sending a FormData object is multipart/form-data not url encoded.
Further more the proper boundary must be set for the request, which the user is unable to do. For this XMLHttpRequest sets the correct content type with the required boundary.
So all you have to do is not set the content type and it'll work.
var xhr=new XMLHttpRequest();
xhr.open('post',url,true);
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");<--don't do this
var formData=new FormData(form);
formData.append('update', true); // makes no difference
xhr.send(formData);
xhr.onload=function() {
alert(this.response);
};
Change the name of the button to something other than "update" (and change it in your form['update'].onclick... as well). I think its clashing with the value you are trying to set on the FormData to trigger the PHP code.

Trouble with AJAX within a form

I'm a newbie to JavaScript. I tried to use AJAX from within a form and kept getting "HTTP ERROR 405".
I'd been viewing a video course, so I tested the example code in my environment and it worked perfectly. But the example was not in a form. So I removed the and from my code and the AJAX works. But I need this to work in a form. I want to make several AJAX calls to the server within this one form and need to know what to do to make them work.
Here's the failing HTML code:
<form id="Match_Results" action="#" method="post">
<fieldset>
<legend>Before the Match</legend>
<div id="which_league">
<button id=get_leagues>Get Leagues</button>
<div id="output"></div>
</div>
</fieldset>
</form>
And here's the JS:
document.getElementById('get_leagues').addEventListener('click', loadData);
function loadData() {
const xhr = new XMLHttpRequest();
xhr.open('GET', 'leagues.txt', true);
xhr.onload = function(){
console.log('READYSTATE', xhr.readyState);
if(this.status === 200) {
console.log(this.responseText);
document.getElementById('output').innerHTML = `<h2>${this.responseText}</h2>`;
}
}
xhr.onerror = function() {
console.log('Request error...');
}
xhr.send();
This is just the first step in getting this to work, so I'm just pulling in a local text file and using a button. Actual code later will do this automatically, without the button, pulling from a MySQL db via a PHP page. But I can't even get this working.

Pushing a button programmatically to submit a form on another page in Javascript

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.

How to submit individual input field without form

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.

grabbing text from a text field and updating db with it

I am trying to grab text from a text field and then use that to update my db with it. I have tried using session, get, post and cookie to grab the value using php and this doesn't work. I am new to php so I am thinking this comes out blank because it is server side. I did this with javascript and it grabs the value but I am not sure how to use it with php or to update mysql. any help is appreciated. here is some sample code of mine: I have the update on a seperate php page but the input of my text area is not even being grabbed
<?php
function update_db(){
// echo $_POST["comment"];
$nenabled = $_GET['enabled'];
$comments_new = htmlspecialchars($_GET['comment']);
$nemail = $_GET['email'];
echo ("<script>console.log('$comments_new')</script>");
?>
<form method ="get" action ="update_user.php">
<input type="hidden" name = "enabled" value = "nenabled">
<input type="hidden" name = "comments" value = "comments_new">
<input type="hidden" name = "email" value = "nemail">
<input type="submit" >
<script>
function doFunction() {
var com = document.getElementById("comment");
alert(com.value);
// var comment = '<?php update_db(); ?>';
}
</script>
You have something like :-
<input type="hidden" name = "comments" value = "comments_new">
Then how can you expect
document.getElementById("comment");
will work?
You should add the id in your html, like:-
<input type="hidden" id="comment" name = "comments" value = "comments_new">
You won't be able to call a PHP function from inside the javascript function. Once the page is rendered PHP can no longer modify the page since it is a server side language exclusively. There are two common ways to do this however, the first is to wrap your text input in a form and include a submit button that calls a php file with your code to insert the value into your database. There are plenty of good tutorials out there if you google them but http://html.net/tutorials/php/lesson11.php is a pretty good one.
The other way, and the way that sounds like it would work best for you, is to use AJAX to make a call to a php function. You never navigate away from your page and you can handle success and error conditions. AJAX supports GET and POST data to your php file. Again, not reinventing the wheel here is a great AJAX tutorial that spells out using GET and POST, single data, multiple items, return data, etc. http://hayageek.com/jquery-ajax-post/
Hope that helps!
If you want to update your database on submit of the form, then no need to import yout php code within javascript. You just need to send an AJAX request to your php server on submit your form. For the AJAX request you can also use jQuery.
At first you've to modify your html form like:-
<form onsubmit="return false;">
<input type="hidden" id="name" name = "enabled" value = "nenabled"></input>
<input type="hidden" id="comments" name = "comments" value = "comments_new"></input>
<input type="hidden" id="email" name = "email" value = "nemail"></input>
<input type="button" onclick="update()" value="Submit">
</form>
So, on click of the submit button the update function will be called. The update function will take the input values and call another function to send the AJAX request. So I wrote:-
<script type="text/javascript">
function update(){
var data = {
name : document.getElementById("name").value,
comments : document.getElementById("comments").value,
email : document.getElementById('email').value
};
loadXMLDoc(data);
}
//Ajax request function
function loadXMLDoc(data)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","updateDB.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("name="+data.name+"&comments="+data.comments+"&email="+data.email);
}
</script>
The AJAX request will send a POST request to
your base url + 'updateDB.php'
with data:-
name:nenabled,
comments:comments_new,
email:nemail,
So, now you can do the rest of the thing in the server side php code to update the database.

Categories

Resources