How can I send a PHP variable on a page to another Javascript page using Ajax?

0
Hello, people, I would like to know how to send a php variable to another javascript document through Ajax.

The PHP variable in question is this:

$json = json_encode(simplexml_load_string($show));

Here it returns the value of a string, but I saw that Json has a Json.parse function, which converts all this to objects, so it's easier to manipulate to make a table, but I want to do things separated, the php page receives these values and the javascript sends to the html where the user will see his registration, if there is an easier and safer method I also generally accept to send this variable to a JS / Json page and there I'll do the table with the information

    
asked by anonymous 29.03.2018 / 20:10

1 answer

1

What you are doing is part of the concepts used in a REST API. See here

Backend is responsible for managing and delivering the data in a practical format such as json, hence the responsibility of displaying this data is from the Frontend application (or other backend in case of microservices).

An example with jQuery:

var objetoJS = jQuery.parseJSON(jsonDoServidor)

jsonDoServidor is what was generated by your json_encode(simplexml_load_string($show));

Note: This should be trafficked to your JS somehow, either via regular http (in the API Routes style) or even rendering (not the best practice anymore).

If it is done via rendering, at the time your PHP generates HTML, you can do something embedding PHP in JS. Example:

index.html

<script> 
var jsonDoServidor = jQuery.parseJSON(
      <?php echo json_encode(simplexml_load_string($show)); ?>
)
console.log(jsonDoServidor)
</script>

Note that your PHP is dynamically creating jsonDoServer for use by JS. This works, though, may not be the best practice.

A better alternative is to create a file / route that returns only JSON and, through an ajax call, take this content and use it.

$.get("/linkproJson").done(function(data){
  console.log(data)
  var jsonDoServidor = jQuery.parseJSON(data)
});

I tried to explain based on what I understood, but your question was not so straightforward.

To help you get ideas, see what I have similarly to your need (I use this with Laravel, so PHP tags are simplified but the concept is the same):

// Recebe o Json para a view
produtos = {!! $analises->produtos or $analisesProdutos !!} 

// Pega a tabela 
var tableRef = document.getElementById('analisesProdutos-table').getElementsByTagName('tbody')[0];

// Cria as linhas na tabela com os dados que vieram do Servidor
produtos.forEach(function (item) {
    var newRow   = tableRef.insertRow(item);
    newRow.innerHTML = '
    <td><a href="/analisesProdutos/${item.id_mlb}">${item.id_mlb}</a></td>
    <td>${item.seller_mlb}</td>
    <td>${item.name}</td>
    <td>${item.price}</td>
    <td>${item.sold_on_register}</td>
    <td id='${item.id_mlb}-sold_last'></td>
    <td></td>
    '
})
    
29.03.2018 / 22:32