0

I have an array came from php file.

"[{\"username\":\"a.villar026\",\"fullname\":\"Alexis Abulencia Villar\"}]"

This is the array setting in the php file retrieved in the MYSQL table. then I want to get the value of username and fullname of the array but when i return it as a javascript variable, the result is undefined.

I tried the codes below:

var user = JSON.stringify(msg.username);
var name = JSON.stringify(msg.fullname);

var user = JSON.stringify(msg[0]['username']);
var name = JSON.stringify(msg[0]['fullname']);

var user = JSON.stringify(msg[0]); //this returns only an character ({) or {[}
var name = JSON.stringify(msg[1]); //this returns only an character ({) or {[}

my question is, how can i possibly set the value of a variable in javascript using php array.

ADDITIONAL INFO:

JAVASCRIPT CODE:

$(document).ready(function(){
        $("#logout").click(function(){

        });
    getUser();
 });

    function getUser(){
    var user ='';
    var session ='';
        $.ajax({
                type:'POST',
                url:'../bench/php/session.php',
                data:'',
                success:function(msg){
                    alert(JSON.stringify(msg));
                     user = JSON.stringify(msg.username);

                    console.log(JSON.stringify(user));
                }, error: function(e){
                    console.log(e);
                }
            });
    }

PHP CODE:

<?php
   include('config.php');
   session_start();

   $user_check = $_SESSION['login_user'];
   $temparray = array();

      $ses_sql = mysqli_query($db,"select username,fullname from user where username = '$user_check'");

      $row = mysqli_fetch_array($ses_sql,MYSQLI_ASSOC);

        if ($row > 0 ){         
                array_push($temparray, $row); //save your data into array
        }

       echo json_encode($temparray);

       if(!isset($_SESSION['login_user'])){
          header("location:index.html");
       }

?>

1 Answer 1

2

how can i possibly set the value of a variable in javascript using php array.

let response = "[{\"username\":\"a.villar026\",\"fullname\":\"Alexis Abulencia Villar\"}]"
let data = JSON.parse(response)
console.log(data)
data[0].username = "something"
console.log(data)

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

Comments

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.