Pass values from json_encode to variable in javascript

1

I have a problem when trying to pass the values from one PHP variable to another in javascript. The variable in PHP is an array formulated from a query, I pass that array by a json_encode () and assign it to an array in javascript:

var array_en_js = <?php echo json_encode($var_php) ?>;

However, when I do it, I receive an alert "Uncaught SyntaxError: Unexpected token;" and when analyzing the code it appears to me in the following way:

var array_en_js = ;

Already validate that the PHP variable has some value through print_r (), which showed the values of the query effectively.

The accesses to the BD are correct

    
asked by JOSE ALAN LUNA CARREON 20.03.2018 в 20:51
source

2 answers

0

Warning I do not know if it will have to do with what you want to solve but here you have to be clear that the php only has php code, and that at the end of executing that php it should show all the data that you want to show in the client (js). Example to see if you are returning the data well you have to put it in the xampp that I guess all that you will have done but you will put in the url: localhost: 8080 / folder Where is the PHP file / myArchive.php

In which you can see if you are returning the data well your php and then collect them with js, jquery or angularjs.

These would be get methods that would be to collect the data you send from the php

This method is an http. For example, in js if I'm not mistaken, that's the way I've looked.

         function httpGetAsync(theUrl, callback)
          {
              var xmlHttp = new XMLHttpRequest();
              xmlHttp.onreadystatechange = function() { 
              if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
              callback(xmlHttp.responseText);
          }
              xmlHttp.open("GET", theUrl, true); // true for asynchronous 
              xmlHttp.send(null);
          }

In jquery it would be like this:

      $.get("rutaDelArchivo/miArchivo.php", function(data, status){
                  alert("Data: " + data + "\nStatus: " + status);
      });

In angularjs it would be like this:

       var app = angular.module('myApp', []);
       app.controller('myCtrl', function($scope, $http) {
       $http.get("rutaDelArchivo/miArchivo.php")
           .then(function(response) {
           $scope.contenidoDeTodoElJson = response.data;
           });
        });
    
answered by 20.03.2018 / 21:10
source
0

in fact already validated and it was because the table had a column with all its null parameters, in the query select all the fields except that and it worked. But your answer worked for another project of angle 5: D!

thanks

    
answered by 20.03.2018 в 21:46