I've a JSP page which includes a checkbox, so when i try to submit the form using the conventional javascript way of document.forms[0].submit(); the form gets refreshed and the checkbox values are not getting retained.
Can anybody help me on how to send the form value using only AJAX. I don't need the way to send using JQuery.
This is the code I had used for sending using form submit:
function relatedAER(){
......
document.forms[0].literatureSelected.value = litNO + "&";
document.forms[0].opCode.value = "relatedAER";
document.forms[0].target='_self';
document.forms[0].action="<%=request.getContextPath()%>/litaer.do?selected="+selected;
document.forms[0].submit();
}
I hope next time, you'll put some effort, into creating even a simple code, and showing us instead of asking for a script.
Now, that bieng said: This will submit a username to a php file, called fetch.php
HTML
<input type='text' name='user' id='user' /><br/>
<input type='submit' name='submit' onclick='check()' />
<div id='output'></div>
Ajax:
function check(){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}else{
xmlhttp = ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
document.getElementById('output').innerHTML = xmlhttp.responseText;
}
}
get_user = document.getElementById('user').value;
param = "name="+get_user;
xmlhttp.open('POST','fetch.php', true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
}
</script>
Related
The snippet shows my html and js. In my php controller I just print_r($_POST) but I only see the form data for myName I can't figure out how to access zzz
UPDATE: I added some code to make sure the send request is complete. However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request. I still can't get any js data into php. I could create hidden inputs and fill those in from js and the submit but that seems ugly. can someone help?
function swagSend() {
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
var henry = "henry"
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("zzz=" + henry);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("myForm").submit();
}
}
}
<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>
<input type='text' name='myname'>
<button type='submit' value='submit' onClick=swagSend();>Submit</button>
</form>
If you are making an Ajax call, there is no reason to submit the form. remove it.
If you want the form data to be submitted in the Ajax call, you need to read the form input values and build up the list yourself.
function swagSend(event) {
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
var henry = "henry"
var name = encodeURIComponent(document.getElementById("myname").value)
xhttp.send("zzz=" + henry + '&myname=' + name);
}
<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>
<input type='text' name='myname' id='myname'>
<button type='submit' value='submit' onClick="swagSend(event)">Submit</button>
</form>
you should only send with xhttp.send and not additionally with document.getElementById("myForm").submit();
I have a server running locally which has an in built rest api. To login through this api, we need to send username, password and organization as parameters to url localhost:8090/ehr/api/v1/login via POST method and server returns an auth token as response. when I try to do this directly without user input from form through the following code:
<html>
<body>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("username=admin&password=admin&organization=123456");
</script>
</body>
</html>
It works perfectly fine and auth token is returned as json, but if I try to do the same through user form input via following code:
<html>
<body>
<form method="POST">
<input type="text" name="username" id="username" placeholder="Username">
<input type="password" name="password" id="password" placeholder="Password">
<input type="text" name="organization" id="organization" placeholder="Organization">
<button id="submit" onclick="login()">Let me in!</button>
<br><br>
</form>
<script type="text/javascript">
function login() {
var user=document.getElementById("username").value;
var pass = document.getElementById("password").value;
var org = document.getElementById("organization").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.write(this.responseText);
console.log(this.responseText);
}
};
xhttp.open("POST", "http://localhost:8090/ehr/api/v1/login", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var param = "username="+user+"&password="+pass+"&organization="+org;
xhttp.send(param);
}
</script>
</body>
</html>
this code throws error
login.html:26 XHR failed loading: POST "http://localhost:8090/ehr/api/v1/login"
What is wrong with the second code and how to correct it?
send your params in this way
xhttp.send('username=user&password=pass&organization=org');
I figured it out myself, I just removed form tag from html and used simple input tags instead. This solved the problem maybe because forms on submission try to load a new page instead of staying on the same page, but the parameters were intended to get fetched from the original page. Which was not able to happen as new page got loaded every time submit button was clicked.
I am trying to post form data, an array to php file without page refresh. I am using ajax which doesn't seem to be working. Below is form syntax and ajax. Can somebody please help me? Thanks.
<form name="postcontent" id="postcontent">
function[]; //just for an example of data
<button type="button" id="submitform" onclick="posttophp" >Send</button>
<script>
function posttophp() {
var xhttp = new XMLHttpRequest();
xhttp1.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("submitform").innerHTML = this.responseText;
}
};
xhttp.open("POST", "options.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("
function_Options1[]=function[]")
}
</script>
In php, I store function_Options1[] in another variable and use further.
Two ideas to try:
Maybe the script should be placed before calling the function, but not sure about this.
Try onclick="posttophp();"
this is my first question here (usually I like to find my own ways to solve problems) but I just can't find problem in my file upload code. It's supposed to use AJAX. I simplified everything so it would be easier for you to read. Here is HTML form:
<form id="fileForm" enctype="multipart/form-data" method="POST" action="php/uploadfile.php">
<p>Insert file: <input type="file" id="fileUp" name="fileUp" />
<button type="submit" id="uploadButton" onclick="sendFile();">Upload</button></p>
</form>
Now here goes javascript sendFile() function:
function sendFile()
{
var forma = document.getElementById("fileForm");
var failas = document.getElementById("fileUp");
var uploadButton = document.getElementById("uploadButton");
forma.onsubmit = function(event)
{
event.preventDefault();
}
uploadButton.innerHTML = "Uploading, please wait!";
var newFile = failas.files[0];
var formData = new FormData(forma);
formData.append("fileUp", newFile, newFile.name);
alert(newFile.name);// Here it says filename.jpg it means everything is ok at this stage
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST", "php/uploadfile.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(formData);
}
And php:
<?php
echo var_dump($_FILES);
?>
It should alert contents of $_FILES, but it says array(0){} even if I try $_REQUEST. So, if anyone could suggest what may be wrong, it would be appreciated :]
I am try to have a forum submits more then once when a user clicks the submit button. Why? I am try to add more then one idem to a shopping cart, The shopping cart software I am using doesn't support adding more then one product at a time and I don't want to edit there core code. The hidden forum would have the product ids like '1,2,3' I'd then need the JavaScript to separate the values and post each one using AJAX to the cart. I am not great a JavaScript but I coded what I think should work but its just giving me a alert: 'There was a problem with the request.' twice. I can't see whats wrong with it, any and all help and suggestions are welcomed! Here the code:
JS
<script type="text/javascript">
function testResults (form) {
var product_id = form.product_id.value;
var quantity = form.quantity.value;
var brokenstring=product_id.split(",");
for ( var i in brokenstring )
{
var http_request = false;
function makePOSTRequest(url, parameters) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
// set type accordingly to anticipated content type
//http_request.overrideMimeType('text/xml');
http_request.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = alertContents;
http_request.open('POST', url, true);
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Content-length", parameters.length);
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function alertContents() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
//alert(http_request.responseText);
result = http_request.responseText;
document.getElementById('myspan').innerHTML = result;
} else {
alert('There was a problem with the request.');
}
}
}
var poststr = "product_id=" + encodeURI( brokenstring[i] ) +
"&quantity=" + encodeURI( quantity );
makePOSTRequest('post.php', poststr);
}
}
</script>
HTML
<form action="javascript:testResults(document.getElementById('myform'));" name="myform" id="myform">
<input type="text" name="product_id" id="product_id" />
<input type="hidden" name="quantity" id="quantity" value="1" />
<br />
<input type="submit" name="button" value="Submit" />
</form>
<span name="myspan" id="myspan"></span>
post.php
<?php
print_r($_POST);
?>
If you want to add two items to the cart shouldnt you be doing two posts with the same item? I can just see one post per item there. You are not taking the quantity into account. But this is not the problem. In this case this is only a logic error.
For the javascript side I would recommend you to use jQuery to treat the ajax stuff because it will make your life WAY easier than regular javascript that might event not work with all browsers.
This is the link related to the POST method of jQuery: http://docs.jquery.com/Post
Hope it helps
It is against all the programming logics to post a form several times instead of having a more complex form. From what I can see or understand from your code you are trying to loop through your splitted (brokenstring) string. Your loop is not constructed where and how it should be. Anyway, if I were you, I would consider migraton to another free cart o the possibility to write one myself. From what I see you will be able to do so with a little bit of help from here.