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">
Related
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>
When I was submitting post method form, given input fields values, not getting while submitting. If i using Ajax call in Jquery the form values serialize and submit it correctly, but in a javascript, Ajax call using FormData I'm getting error.
Can anyone resolve my problem.
Error:
Error: Can't set headers after they are sent. at
ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11)
apollo.model.save.unsetkey: Primary Key Field: name must have a value
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form id="myForm" method="post" action="">
<div>
<label for="name">Enter name:</label>
<input type="text" id="name" name="name">
</div>
<div>
<label for="surname">SurName:</label>
<input type="text" id="surname" name="surname">
</div>
<div>
<label for="age">Age:</label>
<input type="text" id="age" name="age">
</div>
<input type="submit" value="Submit!" onclick="loadForm()">
</form>
<p id="demo"></p>
<script>
function loadForm() {
var xhttp = new XMLHttpRequest();
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "http://127.0.0.1:8080/user", true);
xhttp.setRequestHeader('Accept', 'application/json');
xhttp.setRequestHeader('Content-Type', 'application/json');
var data = JSON.stringify(formData);
console.log('data = ', data);
xhttp.send(data);
}
</script>
</body>
</html>
You don't stop the default submission of the form, so when someone clicks the submit button the form will submit normally as well as through using Ajax. The solution is to bind a listener to the form submission and prevent the default behaviour.
Try this:
document.querySelector("#myForm").addEventListener("submit", function (event) {
event.preventDefault();
// ... Ajax call here ...
})
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";
?>
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";
}
my search form on my page is
<form id="headbar-search" action="search.php" method="GET" x-webkit-speech="x-webkit-speech">
<input type="text" name="search" id="jsid-search-input" value="<?php echo$_GET['search']; ?>" class="ui-autocomplete-input search search_input" placeholder="Search…" tabindex="1"/>
<div class="ui-widget"></div>
</form>
i dont want users to be able to search certain words....
if they search "f***" i want it to redirect to the home page or a simple javascript notification that says not allowed.... thanks!
Either trap for bad words in your php script, or put your php request behind some javascript and trap there. example....
html...
<html>
<head>
<link rel="stylesheet" href="style.css"></link>
<script src="functions.js"></script>
</head>
<body>
<form id="headbar-search">
<input type="text" id="search-box"/>
<input type="submit" onclick="search();"></input>
</form>
</body>
</html>
js...
var badWords = ["gosh","darn"];
function search() {
var searchStr = document.getElementById("search-box").value;
var badWordHit = false;
for (key in badWords) {
if (badWords[key] == searchStr) {
badWordHit = true;
}
}
if (badWordHit) {
alert("Oh no you didn't!");
} else {
// ajax request here
}
}