views:

266

answers:

6

How do I go about passing data from JavaScript code to PHP and back. Right now, I do this is a round about way:
PHP to JavaScript: I would simply use the inline echo to send the data:

<script type="text/javascript">
    var data = <? echo $target_variable ?>
</script>

OR

<script type="text/javascript">
    var data = <?= $target_variable ?>
</script>

JavaScript to PHP: I would create a form element in the JavaScript that would sumbit the data for me to the php file:

<script type="text/javascript">
    var data = targetData;
    document.write("
        <form method=\"post\">
            <input type=\"hidden\" value=\""+target_value+\""></input>
        </form>
    ");
</script>
</script>

Are there any better ways to do this? Best practices sort of thing.

+2  A: 

If you wish to submit this data via a form, you don't need to create the form with Javascript. Simply create an invisible form with HTML, populate the hidden field with Javascript, and automatically submit whenever you're ready.

  <form method="post" action="process.php">
    <input type="hidden" name="data" id="data" />
  </form>

  document.getElementById("data").value = "foo";

If you want to send this in an ajax-style fashion, I would suggest implementing jQuery, which makes this extremely easy. Note the previous case converted to a jQuery solution:

$.post("process.php", {data:"foo"}, function(results){
  // the output of the response is now handled via a variable call 'results'
  alert(results);
});
Jonathan Sampson
How would you submit a form with JavaScript? Is it something like:document.forms.form_name.submit(); ?
chustar
@chustar you can do it that way but remember the whole page will refresh which may be fine but it may be better to use Ajax to make the call in the background.
Jeff Beck
A: 

Well, if you want asynchronous interaction, you can use XMLHTTPRequest to perform an async POST request to the server, to send data.

Mike
A: 

you can use GET or POST to pass the data from one to another.

nks14
A: 

The best thing you can do with the pair of PHP and JavaScript is to start using the json_encode() and json_decode() functions in PHP.

This will get the data into JSON which is the JavaScript Object Notation allowing you to pass objects between the two languages. You can do an eval once you get it in JS to get the object.

Actually moving the data should depend on what you are doing exactly but many times I use Ajax and it would be a good place to start looking at.

Jeff Beck
+2  A: 

Following code shows a ajax request which submits a form from your page in background using jquery ajax. I hope it makes sense.

<html>
<head><title>Sample</title></head>
<script language="javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"&gt;&lt;/script&gt;
<script language="javascript">
    function submitMe()
    {
       variableString = 'name='+$("#name").val()+'&location='+$("#location").val();
       jQuery.ajax({
       type: "POST",
       url: "http://google.com/some.php",
       data: variableString,
       success: function(msg){
      alert( "Data Saved: " + msg );
       }
     });
    }
</script>
<body>
    <form id="xyzForm">
       <input type="text" id="name" name="name"/>
       <input type="text" id="location" name="location"/>
       <input type="button" value="submit" onClick="submitMe();"/>
    </form>
</body>
</html>
Priyank
The key in this answer is USE JQUERY, don't try to do this by hand.
Alex
A: 

First, you need to understand that php and javascript are running on different computers.

Php runs on the server whereas javascript runs on the client computer. That makes things a little bit nondirect. I mean, php and javascript cannot change variables directly, because they dont run at the same time. First php runs at the server, prepares the htmk and js and gives it to the client, then at clients computer javascript runs, if javascript needs something from server, it calls the server again (either post, get or ajax doesnt matter, it is still a http request).

So from php to javascript,you can pass the variable while preparing the javascript, at which pont only php runs and javascript not, and from javascript to php, you can pass the variable by making a request from clients computer to your php server with some variables.

marvin