Display calculating result in the same page
I have a table in my php code. In the second c开发者_JAVA百科olumn of the table, normally it displays "---", and after i click the submit button, it will display the calculating result in the same page.
For example,
<table>
<tr><td>1</td><td>---</td></tr>
<tr><td>2</td><td>---</td></tr>
<tr><td>3</td><td>---</td></tr>
</table>
And in the same page, it should receive the variables
$var1 = $_POST['variable1'];
I'm not sure which way to use, ajax or javascript or just css?
Do you have any ideas?
Thanks
You can use Javascript if you want to use the calculation on the client side, PHP if you want it on the server side. From your question I guess you want it on the server side.
Just submit the form to the same page: action = "your_page.php"
.
Test if the page is submitted via your form, then display the results (a table with the results), after you calculate them, of course. Else display the page like it is now.
With JavaScript you can use DOM to select that exact td where you want your results and display them there, after you calculate them via JavaScript.
A third option.. ajax, has the advantage that can calculate the results in real time (without pressing the submit button).
You must decide what you want before using one of the methods, each one of them has some advantages and some disadvantages.
you could achieve this with just php and css but ajax would make it slick. i'd use JSON to parse data from a .js to a .php and back. jQuery makes this really easy (using $.post
)
$(document).ready(function() {
$.post('calculate.php', { value: $('td') }, //posts value to php
function(data) {
if(data.success) {
alert(data.result); //gets the value $result from php
}
else {
alert('error');
}
}, 'json');
});
this would post the value of td to calculate.php, which could calculate and echo out JSON data
$value = $_POST['value'];//assign value from js to $value
.....
$data['success'] = true; //there was no error
$data['result'] = $result; //where $result is calculated within php
echo json_encode($data);
you could pass as many variables between the js and php files. you could even animate your results.
these links might help
http://davidwalsh.name/animated-ajax-jquery
http://www.9lessons.info/2009/08/jquery-and-ajax-best-demos-part-3.html
http://www.noupe.com/ajax/30-fresh-ajax-tutorials-and-techniques.html
精彩评论