swathi
swathi

Reputation: 107

accessing database values in javascript

Well

The situation is we are using mysql.We have written the queries and extracted the result from the assoc array.Now how do we access the result from javascript.

  $query = "SELECT firstname FROM employees;
  $result = mysql_query( $query , $resource );
  $value= mysql_fetch_assoc( $result);
  extract( $value );

Now does the javascript code be like

 <script type="text/javascript">
 function somefunction(){
 var databasefield = document.getElementsByName("firstname").value;
  }
 </script>

Upvotes: 0

Views: 804

Answers (3)

rosejn
rosejn

Reputation: 859

It depends on what you want to do with the data from the query. If you want programmatic access to lots of data from Javascript then one good way is to use JSON notation. Basically, your PHP script will generate a snippet of javascript source code that represents a collection of values or basic javascript objects. You could do this with typical PHP templating style, or you can use a JSON library for PHP that is used to respond to a request coming from javascript running in the browser.

Upvotes: 0

Mic
Mic

Reputation: 25154

You can write your PHP page to deliver a JSON string like:

callBack({employee:{firstName:'Jim', lastName:'Black'}});

Where callBack is a function that exist in your page before the script tag pointing to your PHP.

<script>
  function callBack(json){
    ...
  }
</script>
<script src="/request.php?some_param=234"></script>

This technique is called JSONP.

Upvotes: 0

Kaleb Brasee
Kaleb Brasee

Reputation: 51915

You need to add the firstname value into your PHP-generated HTML somehow. You could output it as a Javascript variable, or you could output it as a hidden INPUT field.

Upvotes: 1

Related Questions