botiapa
botiapa

Reputation: 403

I'm trying to echo javascript with php

I'm a beginner, so i hope you can understand me.

I want it to echo a javascript code when the cookie named usr is not false. The first echo works perfectly but the jquery won't work at all.

<?php 
require('checker.php');
$result = checker::isExpired($_COOKIE["hash"]);
$_COOKIE["usr"] = $result;
if ($result != false) {
    echo '<span style"color:red;">szeretlek java</span>';
    echo '<script src="js/jquery.js">';
    echo 'var result = $.cookie("usr");';
    echo 'var added = "Hello, " + result;';
    echo '$(function {
    $("#brand_div").html("alma");
    });';
    echo '</script>';
}
else {
echo "";
}
?>

Upvotes: 1

Views: 101

Answers (3)

VISHNU
VISHNU

Reputation: 966

Hi there are few error in your code. in Js you must give "()" for functions. In the below code instead for reading from COOKIE i give variable please change that and also include require('checker.php'); The below code is a working example for your query , you need to add your pages and variables.

<?php 
$result = "Sdfsf";
if ($result != false) {
    echo '<span style"color:red;">szeretlek java</span>';
    echo '<script src="https://code.jquery.com/jquery-1.10.2.js"></script>';
    echo '<script type="text/javascript">';
    echo "var result = '$result';";
    echo 'var added = "Hello, " + result;';
    echo '$(function() {
    $("#brand_div").html("alma");
   });';
    echo '</script>';
}
else {
echo "";
}
?>
 <div id="brand_div" class="brand_div">  </div>

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94662

You are trying to echo 2 scripts in one <script></script> tag set.

So amend your code like this adding the script tag for your hand coded script after you include jQuery

<?php 
require('checker.php');
$result = checker::isExpired($_COOKIE["hash"]);
$_COOKIE["usr"] = $result;
if ($result != false) {
    echo '<span style"color:red;">szeretlek java</span>';
    echo '<script src="js/jquery.js"></script>';
    echo '<script type="text/javascript">';
        echo 'var result = $.cookie("usr");';
        echo 'var added = "Hello, " + result;';
        echo '$(function() {
                $("#brand_div").html("alma");
            });';
    echo '</script>';
}
else {
    echo "";
}

Upvotes: 1

Ganesh Jagtap
Ganesh Jagtap

Reputation: 43

Close the script tag for first echo and use separate script tag for your custom function.also add parenthesis for function().

<?php 
require('checker.php');
$result = checker::isExpired($_COOKIE["hash"]);
$_COOKIE["usr"] = $result;
if ($result != false) {
    echo '<span style"color:red;">szeretlek java</span>';
    echo '<script src="js/jquery.js"></script>';
    echo '<script type="text/javascript">';
    echo 'var result = $.cookie("usr");';
    echo 'var added = "Hello, " + result;';
    echo '$(function() {
    $("#brand_div").html("alma");
   });';
    echo '</script>';
}
else {
echo "";
}

Upvotes: 3

Related Questions