How to get multiple data from a page and display separately with AJAX

0

I have a program where he creates cookies with the data that the user typed in the <input> fields. This all through AJAX. So far no problems, but in this file I make the request, it returns me the data of the cookies created. What I want is to get this data and put it in two other <input> fields.

An example to clarify further:

  • Two fields <input> name and email;

  • I am sending this data to another file that creates cookies with this data;

  • And two other fields that I want to auto-populate with this returned cookies;

Only when returned, they come together, is there any array to get this information one at a time?

One detail, I use pure JavaScript, no jQuery.

    
asked by anonymous 29.08.2014 / 20:33

1 answer

2

One of the solutions, and what I consider more reliable (in terms of possible entries that can create confusion in the logic of the script), is to preformat the response still on the server side, so that the client side does not need to decode it, la.

If you can get PHP to reply to Ajax with something like this:

'<script>
    var resposta = {
        "nome": "' . $_COOKIE['nome'] . '",
        "email": "' . $_COOKIE['email'] . '"
    };
    fcPreencheCampos(resposta);
</script>'

In this way, in your responseText , you will have the source code that should be set to <div> (for example) to be executed promptly.

function ajax(){
    // ...

    // Ao receber a resposta, e após verificar se o status é 200, etc etc:
    document.getElementById("divExecuta").innerHTML = xhr.responseText;

    // ...
}

At this point, just have a function, declared in a script of <head> , for example, that sends the data to the fields as soon as they arrive:

function fcPreencheCampos(dados){
    document.getElementById("inputNome").value = dados.nome;
    document.getElementById("inputEmail").value = dados.email;
}

JSFiddle will not help much, in this case; I hope the explanation is enough for you to understand! Hugs!

    
29.08.2014 / 21:31