Passing a PHP variable to JavaScript to use in jQuery.ajax

Rhabdomyolyse

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'; ?>

Axel

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>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Passing Variable from javascript(Ajax) to PHP

From Dev

Passing session variable through AJAX to PHP file

From Dev

passing a javascript variable to PHP with xmlhttprequest

From Dev

Passing variable data between jQuery and PHP using AJAX shorthand

From Dev

passing php array to Ajax/jQuery

From Dev

PHP JavaScript passing variable

From Dev

use javascript variable in php in jquery function

From Dev

Passing variable from php to javascript for use as an ID

From Dev

Passing variable from javascript to php with ajax post method

From Dev

Javascript passing a variable to PHP

From Dev

Passing variable from javascript to PHP using ajax in yii

From Dev

Passing a php variable to a modal using AJAX

From Dev

Passing a javascript variable into a php variable

From Dev

Variable in jQuery dialog to be passed for use in php function via ajax

From Dev

Javascript Variable passing to PHP with Ajax

From Dev

Passing javascript Variable value to php variable

From Dev

Passing PHP variable directly to Javascript, bypassing AJAX, how?

From Dev

Ajax Jquery Passing variable to PHP file

From Dev

jQuery Ajax passing response variable to function

From Dev

passing a JavaScript variable to PHP method without using Ajax

From Dev

Passing a javascript variable to PHP to use with Google Charts

From Dev

passing php variable in javascript function

From Dev

Passing a PHP variable into a Javascript funtion

From Dev

passing variable from jQuery ajax to nodejs

From Dev

Passing variable to PHP with AJAX doesn't work

From Dev

Passing Javascript variable to PHP link

From Dev

Passing variable from Ajax to PHP in WordPress plugin

From Dev

Passing Variable Ajax to PHP same page

From Dev

Passing a php value to modal using plain javascript without jquery or ajax

Related Related

  1. 1

    Passing Variable from javascript(Ajax) to PHP

  2. 2

    Passing session variable through AJAX to PHP file

  3. 3

    passing a javascript variable to PHP with xmlhttprequest

  4. 4

    Passing variable data between jQuery and PHP using AJAX shorthand

  5. 5

    passing php array to Ajax/jQuery

  6. 6

    PHP JavaScript passing variable

  7. 7

    use javascript variable in php in jquery function

  8. 8

    Passing variable from php to javascript for use as an ID

  9. 9

    Passing variable from javascript to php with ajax post method

  10. 10

    Javascript passing a variable to PHP

  11. 11

    Passing variable from javascript to PHP using ajax in yii

  12. 12

    Passing a php variable to a modal using AJAX

  13. 13

    Passing a javascript variable into a php variable

  14. 14

    Variable in jQuery dialog to be passed for use in php function via ajax

  15. 15

    Javascript Variable passing to PHP with Ajax

  16. 16

    Passing javascript Variable value to php variable

  17. 17

    Passing PHP variable directly to Javascript, bypassing AJAX, how?

  18. 18

    Ajax Jquery Passing variable to PHP file

  19. 19

    jQuery Ajax passing response variable to function

  20. 20

    passing a JavaScript variable to PHP method without using Ajax

  21. 21

    Passing a javascript variable to PHP to use with Google Charts

  22. 22

    passing php variable in javascript function

  23. 23

    Passing a PHP variable into a Javascript funtion

  24. 24

    passing variable from jQuery ajax to nodejs

  25. 25

    Passing variable to PHP with AJAX doesn't work

  26. 26

    Passing Javascript variable to PHP link

  27. 27

    Passing variable from Ajax to PHP in WordPress plugin

  28. 28

    Passing Variable Ajax to PHP same page

  29. 29

    Passing a php value to modal using plain javascript without jquery or ajax

HotTag

Archive