EvilZone
Programming and Scripting => Web Oriented Coding => : Code.Illusionist May 25, 2013, 01:13:58 PM
-
I am wondering is it possible to pass variable value from jQuery to PHP file, then same PHP file will for example do something simple as addition. After addition is done, it's stored in some PHP variable. Now, I want to recive back that value from PHP file and show it on web page with jquery. I hope someone understood what I want. I saw some examples how people do it but I am not sure how.
-
This is not using jQuery, but I'm used to do it like this:
doshit.php
<?php
if(isset($_POST['p1']) && isset($_POST['p2'])) {
echo $_POST['p1'] + $_POST['p2'];
}
?>
asd.html
<html>
<head>
<script>
function doit() {
var p1t = document.getElementById('p1');
var p2t = document.getElementById('p2');
var rest = document.getElementById('res');
var p1 = p11.value;
var p2 = p2t.value;
if(window.XMLHttpRequest) http=new XMLHttpRequest();
else http=new ActiveXObject("Microsoft.XMLHTTP");
http.onreadystatechange = function() {
if(http.readyState==4 && http.status==200) {
rest.value = http.responseText;
}
}
http.open("POST", "doshit.php", true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.send("p1=" + p1 + "&p2=" + p2);
}
</script>
</head>
<body>
<input id='p1' type='text' />
<input id='p2' type='text' />
<input id='res' type='text' />
<input type='submit' value='Doit' onclick='doit(); />
</body>
</html>
-
jQuery style: http://api.jquery.com/jQuery.ajax/
-
Thank you both for reply. Will check code and URL ande gived me. If I don't understand it after reading and testing both things, will let you know. :)
-
Do your logic in PHP and then pull it in via jQuery. I like to use JSON personally, so I would do something like:
<?php
$val = 0;
for($x=0;$x<$_GET['num'];$x++){
$val += pow($val, $x);
}
$ret = array('val' => $val);
die(json_encode($ret));
[/size]
[/size]var num = $("#myInput").val();
$.getJSON('/myfile.php?num='+num, function(ret){
alert(ret.val);
// no need for a JSON.parse() as $.getJSON does it for you.
});
[/size]
[/size][size=78%]If you want to be able to fire things off to PHP from jQuery and pull it back when it's finished rather than leave the application you're writing hanging, look into websockets.[/size]