SideFX
SideFX

Reputation: 839

Mixing javascript and inline server code

I am trying to do the following:

   <script>
      var documentId = %(this).attr('id');

      <% int docId = %>documentId<%;%>

   </script>

As you can see, I'm trying to create a new server variable but assign the value of the javascript variable. Or at least have the javascript variable evaluated. (This is a simplied example of the real world problem I'm trying to solve) Is there any way that I can do this?

Upvotes: 1

Views: 1313

Answers (5)

Andrey M.
Andrey M.

Reputation: 3806

To send data from browser to server you should use form controls (text field, hidden field, textarea, checkbox, etc.) or ajax. In your case, you can serialize javascript object to a string and pass it to the server via hidden field or XmlHttpRequest.

Upvotes: 0

Jordan
Jordan

Reputation: 32542

You can't do this because the server variable will have already been calculated and the HTML has been generated by the time the client script runs.

Server Side Code Runs => Generated HTML File Served To Browser => Javascript Code Runs

This process is one-way, so there's not a way to give that variable back without using an Ajax request.

However, if all you need is the id, and the control is a .NET control, you can simply use the myControl.ClientID value.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1063338

Since it is your server code that gives the object an @id, the server should already know it at the point of creation. But no, you can't interleave client and server like that - they run disjoint in time and geography

Upvotes: 0

Stephen
Stephen

Reputation: 18964

The problem:

  1. Server-side code is evaluated on the server, before anything is transmitted to the client.
  2. Client side code (JavaScript) is evaluated in the browser, after the server has finished transmitting the document.

After understanding the above statements, you'll see that your current example is technically impossible.

What you will need to do (if your goal is to prevent a page refresh) is send the new data to a script on the server using AJAX. The script will process the data and respond to the browser.

Upvotes: 4

ggutenberg
ggutenberg

Reputation: 7370

The server code will get processed first, before the page is ever rendered. So you'd have to use something like AJAX to pass a JavaScript value back to the server.

Upvotes: 0

Related Questions