开发者

how to pass the JavaScript variable to the php function [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How to get javascript function data into Php variable

I am writing a code in javaScript. in that I need to call the php function.

But the problem is again I have to pass the Javascript variable to the php function.

My javascrpt is as follows,(is this correct)

<script>
obj.value="0254"
if (obj2.value != -1) 
{
       var PLOptions= "<?php PLOptions(?>"+ obj.value +"<?php)?>"
}
</script>

Here PLOptions() is the php method and obj.value is the javascript variable.

please let me know, how 开发者_运维百科can I achive this.


You can't do that. PHP is executed server-side, Javascript client-side. What that means is, the PHP code is executed before the Javascript.

However, you could use AJAX to call a PHP function from Javascript.


  1. PHP runs on the server and sends HTML to the server.
  2. Server sends HTML to client.
  3. Client renders webpage and executes JavaScript

At this point it is too late to pass data to a PHP function.

You have to issue a new HTTP request…

  • Submit a form
  • Set location.href
  • Use Ajax
  • Add an image

… and include the data in the POST body or the GET query string.

PHP can then read from $_POST or $_GET and return some more data.


Note that they execute disjointly, when your PHP executes it's running server side, your JavaScript runs client side.

What you would have to do is post back/AJAX to the page and pass in the variable as part of the call.


It's not possible you must use Ajax request to send data to php scripts.


Think you will have to use AJAX(HTTPRequest) to achive this and pass your parameters as POST or GET to php..

php code example:

if(isset($_POST['parameter1']) && isset($_POST['parameter2'])){

    //some function code

    echo return_value; //and here use echo as return to get the result to javascript

}

the AJAX part can be done in alot of ways, if you want me to extend with an example tell me if you are using a framework and if(which)


JS is executed clientside while PHP is executed serverside, so you'll have to send the JS values to the server. This could possibly be tucked in $_POST or through AJAX

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜