-1

I am trying to figure out the best way I retrieve php variables with AJAX and then make those variables into javascript variables.

Let's say I have the following within my php file:

echo $total;
echo $actual;

Edit: JSON

echo json_encode($comments);

How can I turn these php variables into javascript variables within the AJAX call success: function (data) { or is there a better way to do this?

Paul
  • 3,348
  • 5
  • 32
  • 76

4 Answers4

1

Create a result array to contain all of the variables you want to return. Encode the result instead of $comments.

$result = array('total' => $total, 'actual' => $actual);
echo json_encode($result);

In the JavaScript, set the dataType to json and jQuery will automatically parse it, then you can access the variables as properties of the success argument.

$.ajax({
    url : '...',
    type : 'post',
    dataType : 'json',
    success : function(result) {
        console.log( result.total );
        console.log( result.actual );
    }
});
MrCode
  • 63,975
  • 10
  • 90
  • 112
0

You have to do is json_encode, by doing it manually or by making array of these variables and retrieve it by ajax. By this you can make it java script variable.

Waleed Ahmed Haris
  • 1,229
  • 11
  • 17
0

As soon as the page loads you will have to declare them as a global variables. This can either be done independently or using the window scope.

    <script>
    // On page load

    total = <?php echo $total; ?>;
    actual = <?php echo $actual; ?>;
    // OR
    window.total = <?php echo $total; ?>;
    window.actual = <?php echo $actual; ?>;
    </script>

Now you can use these variables in the success callbacks.

AkshayS
  • 34
  • 1
0

Someone already used json so I'm going to use a simple string separator. Copy-paste next two codes in two files with the given names, then open ajax1.php in your browser :

ajax1.php

<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script type = "text/javascript">
var total;   // JAVASCRIPT VARIABLE.
var actual;  // JAVASCRIPT VARIABLE.
function myAjax ()
{ $.ajax( { url     : "ajax2.php",
            success : function ( data )
                      { var arr = data.split("^^"); // ◄■■ SEPARATE DATA RETURNED.
                        total = arr[0]; // FIRST VALUE.
                        actual = arr[1]; // SECOND VALUE.
                        alert( total );
                        alert( actual );
                      },
            error   : function ( xhr )
                      { alert( "error" );
                      }
        } );
}
    </script>
  </head>
  <body>
    <button onclick="myAjax()">Click here</button>
  </body>
</html>

ajax2.php

<?php
$total = 450;
$actual = 10;
echo $total . "^^" . $actual; // "^^" IS THE SEPARATOR. ANYTHING CAN BE USED.
?>