1

let's say i have:

<script>
    var jsString="hello";
</script>

and i want it to pass into php string:

$phpString = jsString;

how do i do that correctly? please tell me the right way. thanks in advance.

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
ssie_28
  • 47
  • 6
  • You need to pass it to the server via a form or via an Ajax call. A basic form submission tute can be found here: http://www.html-form-guide.com/php-form/php-form-tutorial.html and I think the other guy has just posted a link to ajax calls. – Hektor May 21 '14 at 19:02
  • java script is the browser side language while php is the server side.What ever changes you do in javascript cannot be passed to the php.You must have to transfer this value to the server via ajax – Talha Q May 21 '14 at 19:05
  • @lxndr Probably not - the question is how to pass a JavaScript value to PHP. – Hektor May 21 '14 at 19:05

2 Answers2

1

You need a Ajax call to pass the JS value into php variable

JS Code will be (your js file)

var jsString="hello";
$.ajax({
    url: "ajax.php",
    type: "post",
    data: jsString
});

And in ajax.php (your php file) code will be

$phpString = $_POST['data'];     // assign hello to phpString 
biswajitGhosh
  • 147
  • 1
  • 2
  • 17
1

You will need to use an HTTP POST to send the data to PHP. Check out this tutorial: http://www.openjs.com/articles/ajax_xmlhttp_using_post.php to see how to send a post without JQuery. Also see the XMLHTTPRequest docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest. As other answers have noted, JQuery is the makes this much easier with $.post: http://api.jquery.com/jquery.post/.

To get the string in PHP use the $_POST variable.

Mikayla Maki
  • 473
  • 6
  • 18