Reputation: 673
I'm trying to send, the numbers of every cell, and calculate the sum of them in php. Then show the result in text input But it did not work.How Can I do it?
This is my php code:
<?php
if(isset($_POST['keyup'])){
$sum1 = $_POST['sum1'];
$sum2 = $_POST['sum2'];
$sum3 = $_POST['sum3'];
$resultado = $sum1+ $sum2 + $sum3;
echo "Resultado: " .'<input type="text" name="resultado" value="'.$resultado.'">';
}
?>
Thank You in Advance
Upvotes: 0
Views: 113
Reputation: 826
I made a quick look in your full code and it seem the form tags are missing. you need to embody your code in between form tags. which will run a script.
<form action="yourphpfile" method="post"></form>
if you dont want to load a new page you need to use Ajax which is a bit more complicated. more info about form can be found here. http://www.w3schools.com/php/php_forms.asp
edit the action script will run when a submit input button of some sort is clicked.
second edit. I looked into some old project to see how I instead refreshed a page with ajax which goes as follows.
//This function will need to be called on a button click for example
function login(){
var sum1 = document.getElementById("sum1");
var sum2 = document.getElementById("sum2");
var sum3 = document.getElementById("sum3");
//Do some extra refining here if needed. Depends on how the data is obtained.
sum1 = sum1.value;
sum2 = sum2.value;
sum3 = sum3.value;
//Calls the functions below
ajax(sum1, sum2, sum3);
}
//Javascript call this function on a button click
//or create an extra function that calls this and loads the sums from the page.
function Ajax(sum1, sum2, sum3){
var xml;
xml = setXML(xml);
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(DIV THAT WILL NEED TO BE UDATED HERE ).innerHTML=xml.responseText;
}
};
xml.open("POST", URLTOYOURSCRIPT.php ,true);
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("sum1="+sum1+"&sum2="+sum2+"&sum3="+sum3+);
}
function setXML(xml){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xml = new XMLHttpRequest();
return xml;
}
else{// code for IE6, IE5
xml = new ActiveXObject("Microsoft.XMLHTTP");
return xml;
}
}
and then your php script will need the following.
//Obtains the sums from the post data send by ajax.
$sum1 = $_POST["sum1"];
$sum2 = $_POST["sum2"];
$sum3 = $_POST["sum3"];
//Perform some extra checks here like isnumeric() to see if they are actual numbers etc.
if(is_numeric($sum1) && is_numeric($sum2) && is_numeric($sum3){
//Calculates the sum and echoes it on your existing page.
$totalsum = $sum1+$sum2+$sum3;
echo $totalsum;
}else{
echo "you did not insert numbers"
}
Upvotes: 1