-2

I want to add some PHP into JavaScript, however, the one I have at the moment does not work and was wondering if you could help.

This is what I have so far:

$(document).ready( function() {
 setTimeout( function() {
  $("body").addClass("ready");
 }, 1700);
 setTimeout( function() {
  $(".splash h1").html("Hi <?php echo '$first_name'?>");
  setTimeout( function() {
   $(".splash h1").html("Welcome to your Profile");
  }, 1500);
 }, 900);
});

The variable first_name is already defined and fully working on the PHP page it will display on.

Here is the PHP code

    <?php
/* Displays user information and some useful messages */
session_start();

// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
  $_SESSION['message'] ='<br>You must be logged in before accessing that page!';
  header("location: login.php");
}
else {
  $title = $_SESSION['title'];
  $first_name = $_SESSION['first_name'];
  $last_name = $_SESSION['last_name'];
  $email = $_SESSION['email'];
  $school_name = $_SESSION['school_name'];
  $class = $_SESSION['class'];
  $school_admin = $_SESSION['school_admin'];
  $position = $_SESSION['position'];
  $active = $_SESSION['active'];
  $staff = $_SESSION['staff'];
  $grav_hash = md5("$email");
}
?>
Tom
  • 1
  • 4

3 Answers3

0

Remove the semi colons around the variable, and make sure it is defined.

<?php

$first_name = "Tom";

?> 

$(document).ready( function() {
     setTimeout( function() {
      $("body").addClass("ready");
     }, 1700);
     setTimeout( function() {
      $(".splash h1").html("Hi <?php echo $first_name; ?>");
      setTimeout( function() {
       $(".splash h1").html("Welcome to your Profile");
      }, 1500);
     }, 900);
    });
Jesse Schokker
  • 896
  • 7
  • 19
0

if you're using an external .js file it's not possible unless you change something in .htacess file. There's another easier way. Use a .php file and add at the beginning header("Content-type: text/javascript"); and with a simple echo'your js code'; write your script and you'll be able to mix php and javascript in a single file.

If you're using a .php file and using <script></script> just use <?php $yourphpcode; ?> and add your code.

I hope I've helped you with this :-)

-1
$(document).ready( function() {
  setTimeout( function() {
  $("body").addClass("ready");
  }, 1700);
  setTimeout( function() {
  $(".splash h1").html("Hi <?php echo '{$first_name}'; ?>");
  setTimeout( function() {
  $(".splash h1").html("Welcome to your Profile");
  }, 1500);
}, 900);
});

You have not ended the echo with semi-colon. This is the error.