Change HTML element using XHttpRequest from HTML form - javascript

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>

Related

Take input from textbox and redirect with that text to perform a google search

Hey everyone i am trying to solve the following question
Using form, make a page in HTML where the user can enter a keyword and click on the “Search” button and then that keyword is searched on google.
But till now have no luck in figuring out how to redirect with the i/p from my textbox in form
here is the code
<html>
<head>
<title>What is PHP</title>
</head>
<body>
<script type="text/javascript">
function showDetails()
{
var a = document.getElementById('sea');
window.location = 'https://www.google.com/search?q='+ a;
}
</script>
<img src="https://www.google.com/url?sa=i&source=images&cd=&cad=rja&uact=8&ved=2ahUKEwjN2I-drPLfAhVBrY8KHUBlCwMQjRx6BAgBEAQ&url=https%3A%2F%2Fwww.froala.com%2Fwysiwyg-editor%2Fdocs%2Fserver%2Fphp%2Fimage-upload&psig=AOvVaw2Rv-5CgPx3gJo5_dzi6XFo&ust=1547729604931087" width="25%" height="25%">
</img>
<p>Php is amazing<br>Php is not cool</p>
<button onmouseover="alert('I Love HTML too!')">I Love HTML</button>
<br>
<br>
<form method="POST">
Search: <input type="text" name="fname" id="sea">
<input type="button" name="btn" onclick="showDetails()">
</form>
</body>
</html>
By selecting getElementById() method you select the element as a whole. You can get the value of an input-element with the value attribute.
var a = document.getElementById('sea').value;

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

Getting error while submit form with ajax

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 ...
})

How do I manually test JavaScript?

I'm trying to learn javascript by making a simple price checking website using the Best Buy products API.
How do I "run" the javascript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. The function processData(data) searches for the product using the SKU.
Nothing is happening when I test the site, and any help would be great; thanks!
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
<input id="SKU" name="SKU" required="" type="text">
<label for="SKU">SKU</label>
<input id="email" name="email" type="email">
<label for="email">Email</label>
<input class="button" id="submit" name="submit" type="submit">
</form>
<script>
function validateSKU() {
var SKU = document.forms["bestBuyForm"]["SKU"].value;
var bby = require('bestbuy')('process.env.BBY_API_KEY');
var search = bby.products('sku=' + SKU);
search.then(processData);
}
function processData(data) {
if (!data.total) {
console.log('No products found');
} else {
var product = data.products[0];
console.log('Name:', product.name);
console.log('Price:', product.salePrice);
}
}
</script>
</body>
</html>
Use web console to see what does happen and read about the console API.
Try to bind validateSKU with HTML element addEventListener method. Also you should prevent default form behaviour which cause page reloading on submit. Call event.preventDefault().
Working example code:
<html>
<form id="someForm">
...
<button type="submit">Submit</submit>
</form>
<script>
function validateSKU(event) {
console.log('IT works');
event.preventDefault();
// ...here your code
}
var form = document.getElementById('someForm');
form.addEventListener('submit', validateSKU, false);
</script>
</html>

POST FormData to php using javascript and XMLHTTPRequest

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";
}

Categories

Resources