POST FormData to php using javascript and XMLHTTPRequest - javascript

At the moment I have two files, index.htm and accessdata.php.
This is what I have in index.htm:
<html>
<head>
<script>
function postData() {
var xmlhttp=new XMLHttpRequest();
var url = "accessdata.php";
var checkBoxes_formData = new FormData(document.getElementById("checkBoxes"));
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(checkBoxes_formData);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<button type="button" onclick="postData()">POST</button>
<form id=checkBoxes>
<table>
<tr><input type="checkbox" name="opt1" value="blue" checked> Blue</td>
<tr><input type="checkbox" name="opt2" value="yellow"> Yellow</td>
</table>
</form>
<p id="result"></p>
</body>
</html>
and this is what I have in accessdata.php:
<?php
$opt1=$_POST['opt1'];
echo $opt1;
echo "bla";
?>
Now, on
<p id="result"></p>
"bla" shows up, but not "blue", or "yellow".
What am I doing wrong?
THE CORRECT HTML CODE BELOW!!
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>POST PHP XMLHTTPRequest</title>
<script>
function postData() {
var xmlhttp=new XMLHttpRequest();
var url = "accessdata.php";
var checkBoxes_formData = new FormData(document.getElementById("checkBoxes"));
xmlhttp.open("POST",url,true);
xmlhttp.send(checkBoxes_formData);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
}
</script>
</head>
<body>
<button type="button" onclick="postData()">POST</button>
<form id="checkBoxes">
<input type="checkbox" name="opt1" value="blue"> Blue
<input type="checkbox" name="opt2" value="yellow" checked> Yellow
</form>
<p id="result"></p>
</body>
</html>

blue doesn't show up because you are claiming:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
But FormData objects encode data as multipart/form-data.
Remove the code that explicitly sets the content-type and let the browser generate it for you. (Don't try to explicitly set it to multipart/form-data, you have to specify what the boundary marker is going to be in the header too).
yellow doesn't show up for the same reason, but also because:
You are only looking at opt1 and it is associated with the name opt2 and
Checkbox controls are only successful (i.e. will be in the data that gets submitted) if they are checked (which the yellow one is not by default).
Complicating matters further, your HTML is invalid. Use a validator. You can't have an input as a child of a table row, you need to create a table data cell between them. (Note that it looks like you are trying to use a table for layout, you should probably get rid of the table entirely).

Tap to create a note
You should try this…
<form method=post action=accessdata.php>
<input type=checkbox value=blue name=opt1>blue
<input type=submit value=submit name=send>
</form>
In accessdata. PHP
if❨isset❨$_POST[`send']❩❩ {
$color=$_POST[`opt1'];
echo $color."bala";
}

Related

Change HTML element using XHttpRequest from HTML form

I want to be able to enter a name into a form and have a message sent back underneath saying "Your name is" [name] ", right?" I built this little test program that I plan on incorporating back into the main code but haven't had much luck with it. I am using the POST method.
<HTML XMLns="http://www.w3.org/1999/xHTML">
<head>
<title>A Simple Ajax Example</title>
<script type="text/javascript" src="xhr.js"></script>
<script type="text/javascript" src="simpleajax.js"> </script>
</head>
<body>
<h1>Fetching data with Ajax</h1>
<iframe name="iFrame" style="display: none;"></iframe>
<form method="post" action="data.php" target="iFrame">
<label>User Name:</label>
<input id="namefield" type="text" name="namefield">
<input type="submit" name="submit" value="Fetch" onclick="loadDoc(namefield.value);">
</form>
<div>
<p id="targetDiv">The fetched data will go here.</p>
</div>
</body>
</HTML>
And the javascript...
function loadDoc(name) {
var xhttp = new XMLHttpRequest();
var firstName = name;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("targetDiv").innerHTML = this.responseText;
}
};
xhttp.open("POST", "data.php?namefield=" + firstName, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
Here is what input type submit does from MDN :
<input> elements of type "submit" are rendered as buttons.
When the click event occurs (typically because the user clicked the button),
the user agent attempts to submit the form to the server.
So to change that, one of the ways is to return false in the onclick handler ex:
<input type="submit" name="submit" value="Fetch" onclick="loadDoc(namefield.value);return false;">
Or you can use Button Element instead of submit which will give more meaning for what you need to do:
<button type="button" onclick="loadDoc(namefield.value);">Fetch</button>

how to get the value of a checkbox with php and xml

I'm just learning PHP, XML, AJAX, etc., and I have a form that works fine in general. But I'm having trouble passing the value/state of a checkbox to my PHP script.
Note that my server doesn't appear to work with POST methods (I'm looking into that separately). So I'm using GET. Hopefully that isn't related, but just wanted to note that in case it is relevant.
Here is my simplified HTML file:
<html>
<head>
<script>
function showUser(u) {
alert(u.value);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","checkbox_test.php?u=" + u.value,true);
xmlhttp.send();
return false;
}
</script>
</head>
<body>
<form method="get" onsubmit="return showUser(this.checkboxID)">
<input id="checkboxID" name="checkboxName" value="checkboxValue" type="checkbox">
<input type="submit" value="Submit">
</form>
<div id="txtHint"></div>
</body>
</html>
And here is my simplified PHP file:
<!DOCTYPE html>
<html>
<body>
<?php
$check = $_GET['u'];
if(isset($check)){
echo 'True';
}else{
echo 'False';
}
?>
</body>
</html>
Use u.checked as it's the attribute used by the input to determine the state of the checkbox, u.value will return checkboxValue
<input id="checkboxID" name="checkboxName" value="checkboxValue" type="checkbox">

How to open a URL in the same window in JavaScript?

I am using this code currently and it works great. I am now wanting it to open the url in the same window instead of in a new window. I've read up on this and tried "_self" and I must be doing something wrong.
This is a sample of the code.
<HTML>
<HEAD>
<TITLE> Radio Window </TITLE>
<script>
function OpenWindow(){
for(i=0;i<document.FormName["RB1"].length;i++){
if(document.FormName["RB1"][i].checked){
window.open(document.FormName["RB1"][i].value);
break;
}
}
}
</script>
</HEAD>
<BODY>
<form name="FormName">
<input type="radio" name="RB1" value="http://www10.brinkster.com/A1ien51" checked>Eric's Webpage<BR>
<input type="radio" name="RB1" value="http://www.javaranch.com">JavaRanch<BR>
<input type="radio" name="RB1" value="http://www.google.com">Google<BR>
<input type="button" value="Open New Window" name="butt" onclick="OpenWindow()">
</form>
</BODY>
</HTML>
Add attribute action='url of page you want to open' in your form tag and it would work.
like change this <form name="FormName"> to <form name="FormName" action='url'>
Also replace your last input with this in the form <input type="submit" value="Submit">
What you want to do is to change the current page location, so you can do so by changing your function like this :
function OpenWindow() {
var inputs = document.forms.FormName["RB1"];
for (var i = 0; i <inputs.length; i++) {
if (inputs[i].checked) {
document.location.assign(inputs[i].value);
return;
}
}
}
See the documentation on MDN: https://developer.mozilla.org/en/docs/Web/API/Location/assign

Pass text value to another php file using ajax

I have written a code that contain a text box and submit button. When I hit the enter with text box value it should go to another page(q.php) using ajax, and it should return values from there to here(home.php)
here is my code. (home.php)
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","q.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form onsubmit="return myFunction(document.getElementById('fname'))">
Enter name: <input type="text"id="fname" name="fname">
<input type="submit" value="Submit">
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
My next page(q.php)
<?php
$q = $_GET['q'];
echo $q."Some Content from this page";
?>
My answer is using html+jquery+php:-
<html>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script><!-- add jquery library -->
<form method="post">
Enter name: <input type="text"id="fname" name="fname">
<input type="submit" value="Submit" class= "abc">
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
<script type = "text/javascript">
$(document).ready(function(){ //when your page is rendered completly
$('.abc').click(function(e){ //when you click on submit button this function will run
e.preventDefault();//to prevent normal submission of form
if($('#fname').val() !== ''){ //check name field have some value
$.post('q.php',{'q':$('#fname').val()},function( data ){ //send value to post request in ajax to the php page
$('#txtHint').html(data); //print the response coming from php page to the result div inside your html code
});
}
});
});
</script>
And in php file:-
<?php
$q = $_POST['q'];
echo $q."Some Content from this page";
?>

How to post textbox array name value using xmlhttp

I am a newbie programmer. Is their a way I can post the array name in php file using xmlhttp.I have seen same question like this but it was totally advance with my basic information.
Here's my sample code problem:
HTML
<body>
<input type="text" id="department" name="department[]" />
<br />
<input type="text" id="department1" name="department[]" />
<br />
<input type="text" id="output" name="output" style="width:100%; height:200px;" />
<br />
<input type="button" id="btn" name="btn" value="submit" onClick="showvalue()" />
</body>
JS
function showvalue() {
var dept=document.getElementsByName("department[]").value;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("output").value=xmlhttp.responseText;
}
}
xmlhttp.open("POST","processbranch.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("&dept1="+dept);
}
PHP
$dept = $_POST['dept1'];
foreach($dept as $key => $deptval)
{
echo $deptval;
}
Please give me some sample like my code. Please sir/mam. Thanks in advance :D
hey #shiro Jacinto just change the name of your input department[dept] & department[dept1] in both the input. But I tell you its not a proper way. you can follow the steps
1) create a simple form with different name.
2) call js function on submit.
3) create json object and add your fields into it.
4) post your data to desired php file using jQuery post or ajax post.
Try using this link. Hope this will help you

Categories

Resources