0

I'd like to pass a variable from PHP to JavaScript to use it inside my jQuery.ajax-call. I've tried a lot of things now, but without success.

Here is my current code:

$( document ).ready(function() {
    function getLog() {
        ms = Date.now();
        var chatlink = "<?php echo $clink; ?>";

        $.ajax({
            url: chatlink+ms,
            dataType: 'text',
            success: function(text) {
                $("#chat").text(text, "<br />");
                setTimeout(getLog, 500); // refresh every half second
            }
        })
     }
         
         
// some more code here


<?php $clink = 'foo.php'; ?>

5
  • 2
    Move <?php $clink = 'foo.php'; ?> up before you echo it in the javascript. Commented Aug 26, 2017 at 22:40
  • Have you used viewed the source code of the page or checked the browser console for errors? Viewing the source code or inspect element & trace back to the JS it should show you how the php is outputting and the console should display errors if one does occur. Commented Aug 26, 2017 at 22:44
  • is this inside a php file? if not it won't work. Commented Aug 26, 2017 at 22:45
  • it is in a php file and...yeah, the correct placement got the work. Thank you guys :D Commented Aug 26, 2017 at 22:58
  • 2
    Possible duplicate of How can i pass a php variable to ajax Commented Aug 27, 2017 at 0:20

1 Answer 1

4

How to pass PHP variables to JavaScript

Recommendation:

Deploy the content you must generate with PHP as global variables and use them in your scripts to keep your source code clean.



HTML in PHP file

<?php
error_reporting(-1);
$foo     = 'bar';                          #1
$arr_foo = array( 'bar', 'baz', 'blong' ); #2
$arr_js           = array();               #3 | start collection
$arr_js['foo']    = $foo;                  #3 | extend collection ...
$arr_js['arrFoo'] = $arr_foo;              #3
$arr_js['null']   = null;                  #3
$arr_js['bool']   = true;                  #3
$arr_js['int']    = 0;                     #3
$arr_js['float']  = 0.123;                 #3

echo "<script>

/* make sure to declare your name space if you haven't already */
window.yourApp = window.yourApp || {};

/* #1 deploy your PHP variable as markup
don't forget to wrap variables properly if nessecary */
window.yourApp.foo = '$foo';

/* #2 if you are not sure if the PHP variable contains signs that must be escaped 
or have a non primitive type such as arrays then JSON is there to the rescue */
window.yourApp.arrFoo = " . json_encode( $arr_foo ) . ";

/* #3 if you have a lot of vars that you want to transfer to your JS you could
also collect them in an assoziative array and then deploy them all in one
as described above */
window.yourApp = " . json_encode( $arr_js ) . "; /* most convenient way IMHO */

console.log( window.yourApp );

</script>";

JavaScript file

console.log( window.yourApp );



How to get PHP variables via ajax?

JSON encoded PHP array in PHP file

<?php $arr_js = array(
    'foo' => 'bar',
    'arrFoo' => array( 'bar', 'baz', 'blong' ),
    'null' => null,
    'bool' => true,
    'int' => 0,
    'float' => 0.123,
    'two way magic :)' => $_POST['yourApp']['coming from sender']
);
echo json_encode( $arr_js );
// lets assume the name of this file is "ajax-json.php"

JavaScript file

// must be located in the same directory as "ajax-json.php" in this setup
// make sure jQuery is available!
jQuery.ajax({
    method: 'POST',
    url: 'ajax-json.php',
    dataType: 'json',
    data: {yourApp: {'coming from sender': 'pure awesomeness'}},
    success: function( response ) {
        console.log( response )
    }
})



References


The explanations above are actually an edit!

See snippet below which is the original answer that is marked as accepted.

<!-- HTML in a PHP file -->
<?php $clink = 'foo.php'; ?>

<script>
$( document ).ready(function() {
    function getLog() {
        ms = Date.now();
        var chatlink = "<?php echo $clink; ?>";

        $.ajax({
            url: chatlink+ms,
            dataType: 'text',
            success: function(text) {
                $("#chat").text(text, "<br />");
                setTimeout(getLog, 500); // refresh every half second
            }
        })
    }
}
</script>

Sign up to request clarification or add additional context in comments.

2 Comments

This did the trick. I should have watched for this simple mistakes at first :D
@Rhabdomyolyse also consider the edit in my answer... (if you like to)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.