简体   繁体   中英

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,

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM