How to use an ajax return in any part of the script?

Asked

Viewed 575 times

1

I have a Json that is returned via ajax, I wish I could manipulate this return throughout my script, outside the scope of Ajax, so I don’t have to do a function that does everything within this scope. That way it’s working, but it doesn’t seem like good practice.

Cod:

  jQuery.ajax({
        url: 'consulta.php' + location.search,
        type: "GET",
        dataType: 'json',
        success: function(returnjson) {

          //Exibe os dados de primeira
          $('#id_pergunta').html(returnjson[i].id_pergunta);
          $('#pergunta_jogo').html(returnjson[i].pergunta);
          $('#desafio_jogo').html(returnjson[i].desafio);
          $('#resposta_jogo').html(returnjson[i].resposta);
          $('#equipeum').html(returnjson.equipeum);
          $('#equipedois').html(returnjson.equipedois);
          if (vez === 1){
            alert("A Equipe " + returnjson.equipeum + " iniciará o jogo");
          } else{
            alert("A Equipe " + returnjson.equipedois + " iniciará o jogo");
          }
          //troca a pergunta
          $('#proxima').click(function proxima(){
            i++;
            $('#id_pergunta').html(returnjson[i].id_pergunta);
            $('#pergunta_jogo').html(returnjson[i].pergunta);
            $('#desafio_jogo').html(returnjson[i].desafio);
            $('#resposta_jogo').html(returnjson[i].resposta);
          });
        },
        error: function(returnjson) {
            alert("Erro interno do servidor");
            window.location = 'Index.php';
        }
    });
  • 1

    The logic is correct, it really has to be started from within the success. You can better organize the code. That '#proxima' is loaded with ajax or already exists on the page?

  • Already exists in the paagina.

1 answer

2

Good morning, your question is in the sense of code organization, then I’ll suggest a small refactoring, using a code template that I use in my projects. The intention is only to demonstrate some possibilities that you would have, and it is totally hypothetical, since I do not know its application. Also as I don’t know your degree of Javascript knowledge, maybe I’ll tell you what you already know. But come on.

First, I always suggest encapsulate somehow your code, so that you never (or almost never) use the global scope. This is good Javascript practice and as much as it doesn’t seem like a necessity (especially when the project is small), you will definitely feel the need for this when your application scales. In addition to helping - and a lot - in the maintenance and organization of code.

A very common practice (much used mainly before the emergence of modules) is the famous IIFE (Immediately Invoked Function Expression). I suggest using it here (if not already using, of course).

Another practice I usually adopt is to have an object that stores all the references of my jQuery objects, so I don’t need to keep selecting them every time (we win in performance too), nor repeating the selectors every time I call them (often complex/long), and if one day they change, I can change one place. I often call this object ui.

And a function bind that makes all the Binds of events of that module (click, Keyboard, mouse...). This function is always loaded in the ready of document to be sure that everything has already been loaded (indispensable).

In your code, I’ve separated the functions of success and error ajax.

I also put a variable that stores the received data (questions) inside the module, and every time the ajax receives, it the arrow (remembering that this was a kick of its structure).

Finally, I encapsulated in a function only the instructions to show the question on the screen (I saw that it was being done twice, when I clicked to go next, and when I received the data).

Ah, and I also put the variables in english. This is a long discussion about which language to define variables in a PT project, but I, personally, I always prefer it in English. But this is just a detail.

This is my complete suggestion:

var QuestionsManager = (function() {

    var ui = {};
    var activeQuestion = 0;
    var playerTurn = 1;
    var questions = []

    $(document).ready(function() {
        bind();
    });

    function bind() {

        ui['id_pergunta'] = $('#id_pergunta');
        ui['pergunta_jogo'] = $('#pergunta_jogo');
        ui['desafio_jogo'] = $('#desafio_jogo');
        ui['resposta_jogo'] = $('#resposta_jogo');
        ui['equipeum'] = $('#equipeum');
        ui['equipedois'] = $('#equipedois');
        ui.btn = {
            'proxima': $("#proxima")
        } 

        ui.btn['proxima'].on("click", function() {
            activeQuestion++;
            showActiveQuestion();
        });

    }

    function ajaxGetQuestions() {

        $.ajax({
            url: 'consulta.php' + location.search,
            type: "GET",
            dataType: 'json',
            success: successGetQuestions,
            error: errorGetQuestions
        });

    }


    function successGetQuestions(questionsjson) {

        questions = questionsjson;
        activeQuestion = 0;

        showActiveQuestion();

        ui['equipeum'].html(json.equipeum);
        ui['equipedois'].html(json.equipedois);
        if (playerTurn === 1){
            alert("A Equipe " + json.equipeum + " iniciará o jogo");
        } else{
            alert("A Equipe " + json.equipedois + " iniciará o jogo");
        }       
    }

    function errorGetQuestions() {
        alert("Erro interno do servidor");
        window.location = 'Index.php';      
    }

    function showActiveQuestion() {
        ui['id_pergunta'].html(questions[activeQuestion].id_pergunta);
        ui['pergunta_jogo'].html(questions[activeQuestion].pergunta);
        ui['desafio_jogo'].html(questions[activeQuestion].desafio);
        ui['resposta_jogo'].html(questions[activeQuestion].resposta);
    }

    //escolhemos o que vamos expor
    return {
        ajaxGetQuestions: getQuestions
    }

})();

/* somente uma função está disponível
  "pelo lado de fora", que é a getQuestions(), o resto
  é "privado" do "módulo" que criamos */

QuestionsManager.getQuestions(); //invoca o ajax

Anyway, it’s just a suggestion to illustrate some techniques that exist. The code has not been tested.

I hope it helps somehow.

Browser other questions tagged

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