I have this javascript code
<Script>
function getGroupId(){
var group=document.getElementById("selectedOptions").value;
var groupFirstLetter=group.substring(2);
}
</Script>
I need to pass the groupFirstLetter to a PHP function which will count how many users in this group and return the value to the javascript function.
Any ideas please?
Thanks,
-
1there are only 2 ways to archieve that. 1. Ajax 2. reload page. JS runs in your client, PHP on the server. as soon as you requested a page and got your answer there is nothing happening on the server anymore (except for sockets or ajax). Without those 2 options you cant let js communicate with phpMohammer– Mohammer2012年04月10日 07:25:18 +00:00Commented Apr 10, 2012 at 7:25
3 Answers 3
You can use jQuery for that to post an AJAX request. See this example taken out of jQuery documentation:
$.ajax({
type: "POST",
url: "some.php",
data: {groupFirstLetter:groupFirstLetter},
complete: function(data){
//data contains the response from the php file.
//u can pass it here to the javascript function
}
});
The variable will be available in your PHP code as $_POST['groupFirstLetter'].
You can manipulate it as you wish then echo a response to the browser again and it will be available in the data variable.
references:
Comments
As javascript runs on user's browser you have to do an http request to a php page. POST or GET can be used to send parameters.
To make a http call with javascript refer to this: HTTP GET request in JavaScript?
Comments
Use jQuery (jquery.com).
Dynamically load the php-file sending the variable using ajax like so:
$.post("file.php", {variable_name: value}, function(returned_data){
console.log(returned_data); //or do whatever you like with the variable
});
and your php-file will access the variable as:
$_POST['variable_name'];