views:

92

answers:

6

I'm developing a pet project with jQuery. Now the application requires some variable value is transferred to client javascript when the page is loaded. I'm wondering what's the best practice to do it.

I can image to do it in two ways. First, render it to be a javascript variable in the page.

<script> <?php echo "var maxid = $maxid;"?> </script>

Which means the client will see

<script> var maxid = <somevar>; </script>

Second, assign it to be an attribute of one element.

<div maxid="<php echo $maxid >" />

Which approach is better? Is there any other way to do it?

A: 

-- Edit:

Just so it's clear, your "question" is asking something totally different than your "code". You'll need to clarify, my post below talks about the "question".

-- Old:

I generally return the complete HTML to be rendered, in the pages that the ajax calls to.

The reason for this is that I don't have to duplicate layout logic in JavaScript, and it ends up being generally useful for just keeping the JavaScript trivial, and of the form of setting HTML/text content of relevant placeholders.

It comes at the cost of transferring more data, but for me, I'm happy to make this trade-off.

Noon Silk
+6  A: 

For the sake of valid html I'd go with the first method, though it really doesn't matter as long as it gets the job done.

<script>
$(function() {
    var max_id = <?php echo $max_id;?>;
});
</script>
meder
A: 

I would render it to be a javascript variable (your first alternative). This seems to be a common approach.

Peter
+3  A: 

I use JSON string to pass values to client Take a look at this example http://blog.reindel.com/2007/10/02/parse-json-with-jquery-and-javascript/

Sorantis
JSON is an option, but that would cost at least one more HTTP round trip.
Morgan Cheng
A: 

First method is better because you will consume less memory and CPU with a simple variable. Going the DIV way, you will consume a DOM element and a DOM node search to read the value.

Everton
+1  A: 

I rarely have to pass just one variable ... I tend to have a whole set of information, in which case I use:

var myAwesomeStuff = <?php echo json_encode($myArrayOfAwesomeInformation); ?>

No round trip to the server, as mentioned earlier with JSON.

rpflo