Jump to content

Php variable not been passed to jQuery


Abel1416

Recommended Posts

I am trying to pass a php variable to javascript but it's not working. This is the "sketch" of my code.

<?php
$url="asset/go/";
?>

 

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    </head>
    <body>
        <script>
            var user="mayor";
            var url ='<?php echo json_encode($url); ?>';
       if(user=="mayor"){
           alert(url);
       }
        </script>
    </body>
</html>

As it is now, it comes with the output below:

<?php echo json_encode($url); ?>

If I remove the quotation around the php in d jQuery, it throws an error in syntax.

Also both codes are located in the same file named test.php

Thanks in advance.

Edited by Abel1416
Link to comment
Share on other sites

13 minutes ago, Abel1416 said:

It is a php file. test.php

My PHP test file 

<?php
$url="asset/go/";
?>
<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    </head>
    <body>
        <script>
            var user="mayor";
            var url ='<?php echo json_encode($url); ?>';
       if(user=="mayor"){
           alert(url);
       }
        </script>
    </body>
</html>

Here is mu result

<--  view-source:http://localhost/test/312485.php -->
<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

    </head>
    <body>
        <script>
            var user="mayor";
            var url ='"asset\/go\/"';
       if(user=="mayor"){
           alert(url);
       }
        </script>
    </body>
</html>

 

So except for the extra quotes it seems fine

I can't seem to get the unparsed php code.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.