How can I print PHP POST data using AJAX? (no jQuery) - javascript

So basically I've got this HTML.
<form method="post" id="myform" onsubmit="getData()">
<fieldset>
<legend>Form</legend>
<label>Color: <input type='text' id="color" name='color'></label>
<label><input type="submit"></label>
</fieldset>
</form>
<div id="showoutput">
</div>
This PHP:
<?php
$color = $_POST['color'];
if($color != "")
{
$color = htmlentities($color, ENT_QUOTES);
print "<p>The color is $color</p>";
}
else
{
print "<p>Fill out form!</p>";
}
?>
And this JS:
window.onload = getData;
var req = new XMLHttpRequest();
function getData()
{
var poststr = "color=" + encodeURI( document.getElementById("color").value );
req.open("POST", "lab11-1.php", true);
req.onreadystatechange = useResponse;
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(poststr);
}
function useResponse()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
document.getElementById('showoutput').innerHTML = req.responseText;
}
}
}
I'm trying to be able to input a color in the form, hit submit, and use AJAX to print the PHP to the "showoutput" div in my HTML. I've tried everything I can think of and haven't been able to figure it out.

I think this is not correct.
Ajax don't need form submit function,
I did do like this, I think you want it.
<form method="post" id="myform">
<fieldset>
<legend>Form</legend>
<label>Color: <input type='text' id="color" name='color'></label>
<label><input type="button" onclick="getData()" value="submit"></label>
</fieldset>
</form>
<div id="showoutput">
</div>
<script>
window.onload = getData;
var req = new XMLHttpRequest();
function getData()
{
var poststr = "color=" + encodeURI( document.getElementById("color").value );
req.open("POST", "test.php", true);
req.onreadystatechange = useResponse;
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(poststr);
}
function useResponse()
{
if(req.readyState == 4)
{
if(req.status == 200)
{
document.getElementById('showoutput').innerHTML = req.responseText;
}
}
}
</script>

Related

The HTML Form and the corresponding xmlhttprequest script doesn't work as expected

I am trying to set up a simple HTML form, and want the response to be added to the HTML form with xmlhttprequest.
Im new in scripting and does not fully understand the handling of objects
The HTML form:
<form id="frm1" action="./cgi-bin/input.cgi">
WPT: <input type="text" name="wpt1"><br>
Time: <input type="text" name="time1"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "./cgi-bin/input.cgi", true);
xhttp.send();
}
</script>
The cgi code:
#!/usr/bin/python
import cgi, cgitb
cgitb.enable()
data = cgi.FieldStorage()
print("Content-Type: text/html\n")
print("Data: ")
print(data["wpt1"].value)
print(data["time1"].value)
I expect that the string "Data: [wpt1] [time1]" to be located at RESULT HERE, where [wpt1] and [time1] has the values from input data.
The error message is:
=> 12 print(data["wpt1"].value)
data = FieldStorage(None, None, []), ].value = []
My understanding of the error message is that no data is submitted.
When using this code for the script part the input is submitted and printed, but not as a content of the HTML Form.
<script>
function myFunction() {
document.getElementById("frm1").submit();
}
</script>
I think you either use POST or send values as query params. method 1:
<form id="frm1" action="./cgi-bin/input.cgi">
WPT: <input type="text" id="wpt1" name="wpt1"><br>
Time: <input type="text" id="time1" name="time1"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "./cgi-bin/input.cgi?wpt1="+document.getElementById("wpt1").value+"&time1="+document.getElementById("time1").value, true);
xhttp.send();
}
</script>
or method 2:
<form id="frm1" action="./cgi-bin/input.cgi">
WPT: <input type="text" id="wpt1" name="wpt1"><br>
Time: <input type="text" id="time1" name="time1"><br><br>
<input type="button" onclick="myFunction()" value="Submit">
</form>
<p id="demo">RESULT HERE</p>
<script>
function myFunction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", "./cgi-bin/input.cgi", true);
xhttp.send(JSON.stringify({"wpt1":document.getElementById("wpt1").value,"time1":document.getElementById("time1").value}));
}
</script>

Why does this simple JavaScript+Ajax+php code not working?

I'm new to ajax, I am trying to send the html page data to php without reloading the current page. When I click on submit button it just blink "processing..."
html file
<!DOCTYPE html>
<head>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "simple.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
First Name: <input id="first_name" name="first_name" type="text"> <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>`
Php file
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
Edit 1
I added alert message in onreadystatechange. It showing three alert messages 2,3,4 respectively.
alert(hr.readyState);
There are multiple things i can see:
</script> a closing of the script which doesn't have any opening tag in the head.
The variable vars doesn't create a query string as it is missing a ?.
So, the complete changes would be:
<head>
<script type="text/javascript">
function ajax_post(){
var hr = new XMLHttpRequest();
var url = "simple.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "?firstname="+fn+"&lastname="+ln;
//----------^---put this at start.
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
Or you can send it as:
hr.send({ firstname:fn, lastname:ln });

image upload using javascript?

This is my HTML and javascript.
I'm trying to upload an image using javascript.
I did find some examples using jquery, but was hoping if this function below can be modified to do the same.
The image upload script is a PHP script, which works when the form is posted normally, but when using this function below, it doesn't send the image to the PHP script. $_FILES is empty.
How can I modify this function to send the image as well?
<html><head>
<script type="text/javascript">
function jax( ){
pd = document.getElementById("pd").innerHTML;
i = document.getElementById("i").value;
url= "ajax.php"; //?act=uploadPic&title=" + pd + "&i=" + i;
q="act=uploadPic&title=" + pd + "&i=" + i;
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}
catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support ajax. Allow Active scriptting in internet settings."); return false;
}
}
}
ajaxRequest.onreadystatechange= function(){
if(ajaxRequest.readyState == 4){
r =ajaxRequest.responseText;
alert(r);
}
}
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(q);
}//func
</script>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<p> Title: <input type="text" name="pd" id="pd" value=" Title here " />
<p> Image: <input type="file" name="i" id="i" />
<p> <button onclick=" jax( ) "> Upload </button>
</form>
</body>
</html>
The PHP script to verify if image is send:
ajax.php
<?php print_r($_FILES); ?>
this is my function,but can't working lower than ie8:
function jax(){
url= "ajax.php?act=uploadPic";
var formData = new FormData(document.forms[0]);
var xhr = new XMLHttpRequest();
xhr.open('post',url,true);
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
}
}
}
xhr.addEventListener('progress',function(e){
if (e.lengthComputable) {
console.log(e.loaded+'/'+e.total);
}
},false);
xhr.send(formData);
}

Submit multiple values of a form using AJAX (but no jQuery) - XMLHttpRequest

Normally I'd use jQuery for this, but to cut a long story short, on this I can't.
I've successfully submitted a form via AJAX which has only one element of a form, like this:
<div id="response"></div>
<form onsubmit="submitStuff(this.datatosend.value);this.reset();return false;">
<input id="datatosend" type="text" />
<input type="submit" />
</form>
<script>
function submitStuff(e) {
if (e == "") {
document.getElementById("response").innerHTML = "";
return
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("response").innerHTML = xmlhttp.responseText
}
};
xmlhttp.open("GET", "sumbitData.php?data=" + e, true);
xmlhttp.send()
}
</script>
Now say I have this form:
<form onsubmit="????????????????????;this.reset();return false;">
<input id="datatosend1" type="text" />
<input id="datatosend2" type="text" />
<input type="submit" />
</form>
How do I do the same, submitting both values?
I'm a bit new to Javascript, especially 'pure' Javascript so please be a bit patient!
Build up the string
var data1 = encodeURIComponent(document.getElementById("datatosend1").value);
var data2 = encodeURIComponent(document.getElementById("datatosend2").value);
var url = "sumbitData.php?data1=" + data1 + "&data2=" + data2;
Read the form values and make a string to attach to the url:
var child=document.getElementById(form_id).getElementsByTagName('input');
var data=new Array();
for(var i=0;i<child.length;i++){
data.push(child[i].id + '='+ encodeURIComponent(child[i].value));
}
data='?' + data.join('&');

Get result displayed in form / textfield

I have an ajax script which fetches results from a web-service and displays them in a div, however I would like them to be displayed in an input area / text field.
My main script:
<script type="text/javascript">
function get_CODES_Results() {
document.getElementById("results").innerHTML = "<img src=\'loading.gif\' />";
var url = document.location;
if (window.XMLHttpRequest) req = new XMLHttpRequest();
else if (window.ActiveXObject) req = new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange = processRequest;
//req.open("GET", url, true);
//req.send(null);
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send("codes="+document.getElementById("codes").value);
function processRequest() {
if (req.readyState == 4) {
document.getElementById("results").innerHTML = req.responseText;
}
}
}
</script>
And here the area where it is being displayed:
<p>
<h3>Results:</h3>
<div id="results"></div>
</p>
My question:
How can I achieve that my result is displayed in an input/text-field?
Some advice would be highly appreciated - thank you, Patrick
Try with this:
document.getElementById("results").value = req.responseText;
And then you results should be an input:
<input type="text" id="results" />
this?
document.getElementById("results").value = req.responseText;
<input id="results" type="text" />
Suppose this is your text field:
<input type="text" id="whatever" value="" />
Simply set the response to its value:
document.getElementById('whatever').value = req.responseText;

Categories