2

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,

alkhader
  • 960
  • 6
  • 16
  • 33
  • 1
    there 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 php – Mohammer Apr 10 '12 at 07:25

3 Answers3

6

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:

jQuery AJAX

Songo
  • 5,618
  • 8
  • 58
  • 96
1

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?

Community
  • 1
  • 1
ab_dev86
  • 1,952
  • 16
  • 21
1

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'];
Gustav
  • 1,361
  • 1
  • 12
  • 24