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,

1
  • 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 Commented Apr 10, 2012 at 7:25

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.