alkhader
alkhader

Reputation: 998

Passing javascript variable to PHP function

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,

Upvotes: 2

Views: 17087

Answers (3)

Songo
Songo

Reputation: 5736

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

Upvotes: 6

Gustav
Gustav

Reputation: 1341

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'];

Upvotes: 1

ab_dev86
ab_dev86

Reputation: 1982

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?

Upvotes: 1

Related Questions