Bwyss
Bwyss

Reputation: 1834

javascript inside php wordpress

Sorry for the basic question, just a bit confused as to what is going on here. I have some PHP running in Wordpress, I am able to run html, php and javascript all from within one file. For example:

<?php
//query WP for the tag

$wp_getTag = $wpdb->get_results( 
    "
    SELECT name 
    FROM $wpdb->mydb_wor1.ukj_terms 
    INNER JOIN ukj_term_taxonomy
    ON (
        ukj_terms.term_id = ukj_term_taxonomy.term_id
        )
    WHERE ukj_term_taxonomy.taxonomy LIKE 'post_tag'
    " 
);

$json = json_encode($wp_getTag);

?>

<script type="text/javascript"> 
// pass the value to js

var JsonTags = <?php echo $json ?>;

</script>

So all the above works. I am grabbing some info from wp and then assigning it's value to a JS variable using echo. But it is not clear what is going on here? is the Javascript running on the server instead of the client?

Upvotes: 0

Views: 103

Answers (2)

JohnnyFaldo
JohnnyFaldo

Reputation: 4161

The server is outputting information into the client side, hence the function name 'echo' (it echo's from the server onto the client side).

You're able to mix server side code into client side code as a result as it's processed by the server first, this is why you can't (without the use of Ajax) effect server side code with Javascript.

Upvotes: 0

David
David

Reputation: 218808

No, the JavaScript is running on the client. The PHP is running on the server. That is, this code runs on the server:

<?php echo $json ?>

The evaluation of that code results in a string being emitted to the client in that location of the output. So, if the variable $json contains the string "{ 'value' : 'hello world' }" then this code would then run on the client:

var JsonTags = { 'value' : 'hello world' };

First all the server-side code runs, which ultimately results in a response to the client. Once that response is received by the client, all the client-side code runs.

Upvotes: 3

Related Questions