0

I am learning single page application, I have the following php code which gives me the max(id) according to create_user from the database. and i have a separate js file i want to use the id in this js file.(.php file exist in php folder , .js file in js folder and htlm in views), please do my question is clear how to use a value or variable from php file int spearate js file not in html file , mysqli issue i will learn later, thanks in advance for your help how do I do this ?

<?php
$json["status"] = "running";
$details[] = "started get_tables ";
include_once('confi.php');
$request_body = file_get_contents('php://input');
// first store the given set of data to keep it for future analysis
$statement = "INSERT INTO tbl_archive (content) VALUES ('$request_body' );";
mysql_query($statement);
$input = json_decode($request_body, true);
// now check if valid user
$user = $input["user"];

$username = $user["username"];
$password = $user["password"];

if($password and $username){


    $mySQLstring = "SELECT username, password, id FROM tbl_user where username = '$username' ;";
    $json["statement"][] = $mySQLstring;
    $qur = mysql_query($mySQLstring);
    //var_dump ( $qur );
    if ($qur){
        $max = mysql_fetch_assoc($qur);
    }
    if ($max){
        $json["max"] = $max;
        if ($max["password"] == $password){
            $json["username"] = $username;
            $json["id"] = $max["id"];
            $json["status"] = "ok";
            $tables = array("class", "class_user", "module", "module_class", "module_user", "rating", "student", "student_class");
            //$tables = array("class");
            foreach($tables as $table){
                if ( $table == 'module' ){
                $statement ='SELECT create_user, MAX(id) FROM tbl_'.$table;                 

                $statement .= ' WHERE create_user = 19 ' ;

                $qur = mysql_query($statement);
                if ($qur){
                    while($r = mysql_fetch_array($qur, MYSQL_ASSOC)){
                        //var_dump($r);
                        //echo (json_encode($r));
                        $result[$table][] = $r;
                    }
                }
                }
            }
            $json = array("status" => "ok", "data" => $result);
        }
    }
}



@mysql_close($conn);

/* Output header */
header('Content-type: application/json');
echo json_encode($json);
?>
george
  • 97
  • 1
  • 12
  • 2
    Probable duplicates: http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript http://stackoverflow.com/questions/7141860/passing-variables-from-php-to-javascript http://stackoverflow.com/questions/11474684/is-it-possible-to-insert-php-variables-into-your-js-code – 3ocene Dec 22 '15 at 17:46
  • Welcome to Stack Overflow. I have fixed English issues with your question and I have rephrased the last portion to clarify what you are asking. – Rohit Gupta Dec 22 '15 at 18:43
  • May I point out that using `max(id)` to get the newly created user is bad practice in production. Consider the scenario where two transactions occur at the same time, the user you just created may not be the max id in the database and you would then get an incorrect reference back. The best way to do this would be to use mysql's last insert id function found [here](http://php.net/manual/en/function.mysql-insert-id.php), you should also consider using `mysqli` or `PDO` as your database transaction layer, `mysql` is deprecated and opens up a tonne of vulnerabilities. – Halfpint Dec 24 '15 at 22:34
  • suppose i am using mysqli or whatever else my question is how to use returned value from php in js – george Dec 24 '15 at 23:14

2 Answers2

1

If I'm understanding your question correctly, you just want your php json encoded result as a javascript variable. If so, it's simply a matter of injecting php code into your javascript.

 <script type="text/javascript">
    var jsonArray = <?php echo json_encode($json) ?>;
 </script>
1

There are two ways you can do this. If the JavaScript is running on that page, you can just echo out the PHP variable into a JavaScript variable.

<script type="text/javascript">
var phpVar = <?php echo json_encode($json) ?>;
console.log(phpVar); // Your JSON as a JavaScript object
</script>

Or from within your PHP:

<?php 
    echo '<script type="text/javascript">var id='.json_encode($json).'</script>";
?>

If it's a different file, you can load the JSON through an AJAX call:

var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var phpVar = JSON.parse(xmlhttp.responseText);
    console.log(phpVar); // Your JSON as a JavascriptObject
  }
}
xmlhttp.open("GET", "phpfile.php", true);
xmlhttp.send()

More on AJAX: http://www.w3schools.com/ajax/

3ocene
  • 2,102
  • 1
  • 15
  • 30
  • actually i am learning single page application, i have some php, HTML and js file, and i want use the the id obtained from the php inside the js, i tried what u had wrote but it did not work – george Dec 22 '15 at 20:51
  • Make sure you put it outside the php tag – 3ocene Dec 22 '15 at 21:07