How do I pass a database variable that is in php to javascript?

-2

I have a program that has coordinates in the database, is taking these coordinates I would pass to another page (javascript) that would calculate the route and show a map in the screen of the users (by ip) to an establishment (coordinates) . But to pass I will need to use ajax, as I do not know anyone could give me a light ??

    
asked by anonymous 01.11.2016 / 17:24

1 answer

0

This is not how it works: pass a "variable" from one running code to another (and still works totally different from one another, even more so by a request). An AJAX (asynchronous) request is made to a specific URL, and receives a response string (which by default can be interpreted by the presence of a header in the request) of the content of that URL.

To begin with, PHP must respond to the client-side with the coordinates. Since there will be more than one value and the server-side response is a string you will need to use a separation logic. In this case, encoding what stores these coordinates as JSON may be useful. If these coordinates are visible in an array (PHP, other than JS), the result JSON might look something like this:

"[coordenada1, coordenada2, ...]"

Using json_encode in PHP. To answer the client-side just use echo (I think you can also use print and printf , although I do not know much of PHP to say it).

echo json_encode(suasCoordenadas);

To interpret JSON, JSON.parse can be used in JavaScript. eval or Function# (that is, JavaScript itself!) can also be used, and there is no insecurity regarding the server, it is only bad to depend on the language itself.

Example to make an asynchronous request in JavaScript, using XMLHttpRequest

var handleRequestError,
    handleRequestResponse,
    request;

handleRequestError = status =>
    alert(status);

handleRequestResponse = data =>
    alert(JSON.parse(data)[0]);

request = new XMLHttpRequest;

// Primeiro parâmetro de XHR#open:
// --- é o método utilizado na requisição.

// Terceiro parâmetro:
// --- diz se a requisição é síncrona;
// --- padrão: true, ou false em outros navegadores

// Últimos parâmetros:
// --- Nome de usuário e senha (restrição)

request.open('get', 'file.php', true);

// O evento "readystatechange" do XHR
// ocorre quando o estado da requisição
// muda.
request.onreadystatechange = () => {
    // XHR#readyState, o estado.
    // Se o estado for 4, a requisição
    // está feita.
    // Outra equivalência é utilizar o evento "load",
    // https://developer.mozilla.org/en-US/docs/Web/Events/load
    if (request.readyState === 4) {
        // XHR#status: estática

        // Sucesso?
        request.status === 200 ?
          // XHR#responseText: resposta em texto
          // XHR#response retorna a resposta com um valor
          // dependente de #responseType
          // E XHR#responseType funciona antes de a
          // requisição iniciar (ou terminar)
          handleRequestResponse(request.responseText)
                               :
          handleRequestError(request.status);
    }
};

request.send();

Remembering: this is not all; if you want to know more about XMLHttpRequest see other subjects.

    
01.11.2016 / 18:42