How to step a database variable that is in php for javascript?

Asked

Viewed 145 times

-2

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

  • 1

    There is no way to pass a variable itself from one application to another. And it helps us if you provide some source, we are not a code writing service.

  • @Lucascosta He did not mean exactly "variable", I believe. In this case AJAX Javascript makes an asynchronous request for a URL and receives the content of the request response. The same content can be interpreted, for example, as JSON, anything.

  • Yes @Someone, an edition with the most suggestive title so that others can find the easiest question and some code is welcome.

  • Just to clarify, AJAX works with JSON, string and XML.

1 answer

0

That’s not how it works: passing a "variable" from one code running to another (and that still works totally different from each other, even more by a request). An AJAX (asynchronous) request is made for a specific URL, and receives a string as response (which by default can be interpreted by the presence of a header in the request) of the contents of that URL.

To begin, 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, coding what stores these coordinates as JSON may be useful. If these coordinates are visible in an (array) (PHP, unlike JS), the result JSON could be something like this:

"[coordenada1, coordenada2, ...]"

Using json_encode in PHP. To answer the client-side just use echo (I think you can use it, too print and printf, although I don’t know much of PHP to say that).

echo json_encode(suasCoordenadas);

To interpret JSON can be used JSON.parse in Javascript. eval or Function# (that is, the Javascript itself! ) can also be used, and there is no uncertainty 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 that: this is not all; if you want to know more than XMLHttpRequest see other subjects.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.