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

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.

Related

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.

Ajax file upload: what happens by default in form.onsubmit()?

I have a Java servlet that receives a file, processes it and then writes the resulting file back through HttpServletResponse's OutputStream.
For upload, I use a simple form:
<form id="upload-form" action="MyServlet" method="POST" enctype="multipart/form-data">
Select file to convert:
<input type="file" id="file-select" name="myfile" />
<button type="submit" id="upload-button">Upload</button>
</form>
After the file has been processed, a download dialog opens automatically.
Since processing may take a while (something like 30 seconds plus upload time), I wanted to provide some progress information through a websocket on the same page. This works if I do this:
var uploadForm = document.getElementById("upload-form");
var fileSelect = document.getElementById("file-select");
var uploadButton = document.getElementById("upload-button");
var httpRequest = new XMLHttpRequest();
uploadForm.onsubmit = function(event) {
event.preventDefault();
event.stopPropagation();
var file = fileSelect.files[0];
var formData = new FormData();
formData.append("myfile", file, file.name);
httpRequest.open("POST", "MyServlet", true);
httpRequest.send(formData);
};
The essential commands here seem to be event.preventDefault and event.stopPropagation.
The thing is: with this code, I get my progress info - but my download window never appears. If I comment out the two commands, it's the other way around. What happens by default when submitting a form, and (how) can I trigger that manually, so that I get both progress info AND the resulting file?
Note: I'm not using jQuery so far.

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.

Naming and posting forms with FormData and XMLHTTPrequest

I'm doing an exercise with JavaScript, and I'm after a couple of hours still stuck. I have this HTML form:
<form method=POST name=transferform
action="/transfer.php">
<input name=user type=text value="">
<input name=credits type=text value="">
<input type=submit name=submission value="Send">
</form>
I want to invoke a JavaScript that posts this form (filled in with some values), using XMLHTTPrequest and FormData. I've come this far, and to me this seems correct but it doesn't seem to work:
var formdata = new FormData();
formdata.append('user', 'bob');
formdata.append('credits', '1');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://someurl.com/transfer.php');
xhr.send(formdata);
Using this script will not work, it doesn't post the form. However, manually pressing 'Send' in the HTML page will post the form, and all is well. My suspicion is that this doesn't work because I haven't set the name of the form in my request(the HTML form is named "transferform"). I can't figure out how to name the FormData-object for the request.
I'm giving you the script of out context (it's a part of a larger exercise involving a web application provided to me to play with), but I hope you can help me anyway :)
I've been using this as my reference.
new FormData() is encoded differently than a form submit.
The default is enctype="application/x-www-form-urlencoded".
Using new FormData() means that you are using enctype="multipart/form-data".

Categories

Resources