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

1

I have a Json that is returned via ajax, I wanted to be able to manipulate this return throughout my script, out of the scope of Ajax, so I do not have to do a function that does everything within that scope. That way it's working, but it does not feel like a 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';
        }
    });
    
asked by anonymous 05.02.2017 / 02:07

1 answer

2

Good morning, your question is in the sense of code organization , so I'm going to suggest a small refactoring using a code template that I use in my projects. The purpose 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 do not know your level of knowledge in JavaScript, maybe I'll tell you what you already know. But come on.

First, I always suggest encapsulating your code somehow, so you never (or almost never) use the global scope . This is a good JavaScript practice and although this does not seem to be a necessity (especially when the project is small), you will certainly feel the need for it when your application escalates. In addition to helping - and a lot - in maintaining and organizing code.

A very common practice (much used before the modules came about) is the famous < strong> IIFE (Immediately Invoked Function Expression) . I suggest using it here (if you're not already using it, of course).

Another practice I usually take is to have an object that stores all the references of my jQuery objects, so I do not have to select them all the time (we gain in performance as well), nor repeat the selectors every time we call them (often complex / long), and if they change one day, I can change one place. I usually call this object from ui .

And a bind function that does all binds events from that module (click, keyboard, mouse ...). This function is always loaded in ready of document to make sure everything is already loaded (indispensable).

In your code, I've separated the functions of success and error from Ajax.

I also put a variable that stores the received data ( questions ) within the module, and every time 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).

Oh, and I also put the variables in English . This is a lengthy discussion on which language to define the variables in a PT project, but I, personally , I always prefer English. But this is just a detail.

Here 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 in some way.

    
05.02.2017 / 10:23