I want to build a simple program using XMLHttpRequest to calculate the area of the triangle. I used this code for client-side;
<body>
<form>
<label for="txtLength">Length</label>
<input type="text" id="txtLength" name="txtLength"><br><br>
<label for="txtWidth">Width</label>
<input type="text" id="txtWidth" name="txtWidth"><br><br>
<input type="hidden" name="submitted" value="1">
<input type="button" name="Calculate" value="Calculate" onclick="calArea();">
</form><br><br>
<div id="showArea">Enter Values and click Calculate.</div>
<script type="text/javascript">
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.readyState == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.send(len&wid&sub);
}
</script>
</body>
This code is for the server side.
<?php
print_r($_POST);
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
?>
Even tried so many codes, It doesn't send the data to server side.
I found the mistake. I was sending the parameters as part of the URL, but need to send them as part of the request body.
Client-side code;
function calArea() {
var len = document.getElementById("txtLength").value;
var wid = document.getElementById("txtWidth").value;
var sub = 1;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("showArea").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "calculate_area.php", true);
xhttp.setRequestHeader("Content-Type", "application/json");
xhttp.send(JSON.stringify({len: len, wid: wid, sub: sub}));
}
Server-side code;
if (isset($_POST['sub'])) {
$len = $_POST['len'];
$wid = $_POST['wid'];
$area = (($len*$wid)/2);
echo $area;
}
else{
echo "Not input detected.";
}
len&wid&sub
Taking some variables and putting the Bitwise & between them is not going to give you a useful value to submit to the server.
You need to encode the data in a format that you can transmit over HTTP and which your server-side code can read.
PHP supports URL Encoded and Multipart Form Encoded data natively so pick one of those.
The URLSearchParams API will generate URL Encoded data for you.
e.g.
xhttp.send(new URLSearchParams({ len, wid, sub }));
Passing a URLSearchParams object will also let XHR automatically set the correct Content-Type request header so PHP will know what it needs to do to decode the data and populate $_POST with it.
You need to put all the parameters into a string of the form name=value with each one separated by &. And the values should be encoded in case they contain special characters.
You also need to set the content type so this data will be parsed correctly.
So change
xhttp.send(len&wid&sub);
should be:
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(`len=${encodeURIComponent(len)}&wid=${encodeURIComponent(wid)}&sub=${encodeURIComponent(sub)}`);
Related
I am learning ajax and I have followed a tutorial to post some data to a text file via a php script but I can't get it to work. Is there something I have missed.
the following is the ajax.html page which is a input text with a button to post the data via ajax
<form name="testform">
Off Min:<input name="setOffMin" type="text" id="setOffMin" maxlength="2" size="1"/></br>
<button type="button" onclick="postStuff();">Submit</button>
</form>
<div id="status"></div>
<script type="text/javascript">
function postStuff(){
var hr = new XMLHttpRequest();
var url = "update.php";
var offM = document.getElementById("setOffMin").value;
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(offM);
document.getElementById("status").innerHTML = "processing...";
}
</script>
this is the update.php file
<?php
$setOffMin = $_POST["offM"];
$f = fopen("test.txt", "w");
fwrite($f, $setOffMin);
fclose($f);
?>
I have been looking over this code all last night and cannot work out why it is not writing the data to the text file.
I have run the php script editing out the $_POST and putting in a variable and it does write to the text file. So the php should work and the text file permission is correct. I expect this is the ajax that I have done wrong.
any help will be great
You need to send offM as urlencoded like this:
var offM = 'offM='+document.getElementById("setOffMin").value;
Now when you click on Submit you call update.php?offM=YourText and PHP recieve var $_POST['offM'] with value YourText
I honesty did every possible search, watched lots of tutorials, but still cant make it work. The mistake is somewhere in connetion between javascript and php. The strange point is that connection is successfull and script works if I click the submit button when the page is in a process of reloading.
Please, help.
I call two variables, $l1 and $l2 from the php require-once which do some work on the page, then I use them in Java script to send to PHPfile onclick of submit button;
Button:
<input class ="button vote" type = "submit" onClick= "javascript: somefunction();" value = "do it" />
Function:
function somefunction(){
var hr = new XMLHttpRequest();
var url = "index.php";
var wn = "<?php echo $l1 ?>";
var ls = "<?php echo $l2 ?>";
var vars = "wn="+wn+"&ls="+ls;
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); // execute the request
document.getElementById("status").innerHTML = "processing...";
}
php acceptor on the same page:
<?php if (isset ($_POST ["wn"])){
$wnn = $_POST['wn'];
$lss = $_POST['ls'];...
try this:
var wn = document.getElementById("wn").value;
var ls = document.getElementById("ls").value;
I presume you ar calculating these either diectly, or from a $_SESSION variable perhaps? When you view the source on the completed page check if the variables are present, perhaps just after you assigne the variables within php.
<?PHP
if (isset($l1) && !empty($l1)) {
echo "L1 is $l1";
} else {
echo "L1 wasnt set";
}
?>
then make sure the value up top matches that you're seeing in your javascript
I have two pages. 1st page has two text forms like so:
<form name="NameForm">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
</form>
It pushes the information into page number two using javascript like so (note this is on the same page as the code above):
<script>
function MakeRequest()
{
// get values
var uname = document.NameForm.uname.value;
var ulocation = document.NameForm.ulocation.value;
// validation stuff here that detects browser
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
var url = "location.php?uname=" + uname + "&ulocation=" + ulocation;
xmlhttp.open("POST", url, true);
xmlhttp.send();
}
</script>
So the problem is this, the php scripts on the page that does all server communication is not reading and storing the variables from this post request into my database.(my other get methods that view items in the database works fine)
if (isset($_POST['uname']))
{
$name = $_POST['uname'];
$location = $_POST['ulocation']
}
then the query goes somehting like
//$table and the other undefined variables are the names of my table & columns
$query = "INSERT INTO $table ($tablename, $tablelocation) VALUES ('$name', '$location')";
Basically I'm trying to get that query to work. If i remove the If statement, it stores $name to the database but not $location.
EDIT:
I forgot to add
<div id="result">
</div>
You are sending a GET.
to send a POST try:
[edited] perform the functions that order
function XHR(){
if(typeof XMLHttpRequest !=="undefined"){
try{ return new XMLHttpRequest(); } catch (e){}
}
if(typeof ActiveXObject !=="undefined"){
try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){}
try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
}
return false;
}
function MakeRequest()
{
// get values
var uname = document.NameForm.uname.value;
var ulocation = document.NameForm.ulocation.value;
// validation stuff here that detects browser
var url = "location.php";
xmlhttp = XHR();//Fixed
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//Fixed
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4) {
if(xmlhttp.status==200){
document.getElementById("result").innerHTML = xmlhttp.responseText;
} else {
document.getElementById("result").innerHTML = "ERROR:"+xmlhttp.status;
}
}
};
xmlhttp.send("uname=" + uname + "&ulocation=" + ulocation);
}
<form name="NameForm">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
</form>
Your missing a form method. In your case you wish:
<form name='NameForm" method="POST">
If this does not resolve your issue, then download and use firebug for firefox or chrome console to debug javascript errors.
There will be no output of errors in JS to the text. You will need to use a debug console.
perform an insert via html form
I would modify your HTML to:
<form name="NameForm" method="POST">
Name: <input type = "text" name = "uname">
Location: <input type = "text" name = "ulocation">
<button type="button" onClick="MakeRequest()"">Save</button>
<input type='submit' name='SubmitForm' value='SUBMIT THIS FORM'>
</form>
Then my PHP code:
<?php
if(isset($_POST['SubmitForm'])){
$Name = $_POST['uname'];
$Location = $_POST['ulocation'];
// Perform validation for these inputs, check if empty, set correctly ETC
$query = "INSERT INTO $table ($tablename, $tablelocation) VALUES ('$name', '$location')";
}
then call your Javascript function inside your PHP script; or perform an ajax/jquery call to run the insert without the need of a submit button
Using that javascript ajax function I pass the content of a form, that contain
the dato value, to the PHP login.php than trought the echo pass back the content
(the insert form) that I want to be switched to the cancel form, using
the content respondText (that may take only the echo of the PHP).
BUT INSTEAD the responseText contain ALL the html code, with the old html
plus the cancella_form passed by the echo, that's also out of the div
with id=visibile.
Any ideas why? D:
//ajaxSubmit(dato)
function ajaxSubmit( url , divId , hideId ) {
//in setXmlHttpObject() I just control the user's browser
// and assign the right XmlHttp Object
var ajaxRequest = setXmlHttpObject();
var dato = 'nome='+document.getElementsByName('dato')[0].value;
ajaxRequest.open("POST", url, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dato);
ajaxRequest.onreadystatechange = function() {
//Comunication complete
if (ajaxRequest.readyState == 4 && ajaxRequest.status==200) {
//Comuncation succesfull
if(ajaxRequest.statusText === "OK"){
var str= ajaxRequest.responseText;//<<<HERE///////
$(str).replaceAll("#visibile");
}
//Comuncation failed
else{
var str= "ERROR: Ajax: "+ajaxRequest.responseText;
document.write(str);
}
}
}
}//FINE ajaxRequest();
<?php
include("prova_login_adv.php");
$conn= mysql_connect('localhost','root','');
mysql_select_db('db_prova',$conn ) or die(mysql_error());
//
if(isset($_POST['nome'])){
$dato= $_POST['nome'];
mysql_query(" INSERT INTO test (valore) VALUES ('$dato') ") or die(mysql_error());
/// NOW I declare what I want to be replaced in the div id="visibile"
echo "
<form id='form_cancella' name='form_cancella' action='' methos='POST' onSubmit=' return false;' >
<text name='dato' value='".$dato."' >Benvenuto <b>".$dato."</b></text>
<input type='submit' name='cancella' value='cancella' onClick=\" ajaxSubmit('logout.php','visibile','form_cancella');\" />
</form>
";
}
?>
I have a simple setup to allow a user to change his content on a page.
It calls up a query and populates the area with the results. My goal is to have the user enter in some new information, insert that info into the table, and requery the results.
Here is my Javascript function that is called:
function addLink(){
var ajaxRequest;
if(window.XMLHttpRequest){
ajaxRequest = new XMLHttpRequest();
}
else{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status==200){
var ajaxDisplay = document.getElementById('links');
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
}
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send();
}
}
Those PHP functions merely spit out the HTML, the displayContent() specifically for the actual table data.
Here is my HTML for adding some info to the database:
<center><br /><br />
Image URL: <input type='text' id='links_img' />
Link URL: <input type='text' id='links_link' />
<input type='button' onclick='addLink()' value='add' /></center>
Here is my PHP for adding the information:
<?php
mysql_connect([sensitive information]) or die(mysql_error());
mysql_select_db([sensitive information]) or die(mysql_error());
$result = mysql_query("INSERT INTO linksMod (Image URL, Link URL) VALUES ("$_GET['imgURL']","$_GET['linkURL']") or die(mysql_error());
mysql_close();
?>
Thee page does nothing when I click the 'Add' button.
Thanks for your help!
These lines:
var imgURL = document.getElementById('links_img').value;
var linkURL = document.getElementById('links_link').value;
var queryString = "?imgURL=" + imgURL + "&linkURL=" + linkURL;
ajaxRequest.open("GET", "addLink.php" + queryString, true);
ajaxRequest.send();
need to be outside the "readystatechange" handler function. The way it's written now, they're inside the handler function and, since it isn't called, they'll never happen.
ajaxDisplay.innerHTML = "<?php displayTitle('Links'); ?><?php displayContent('Links', $isLoggedIn); ?>"
I don't think it's possible to embed php in javascript .