Ajax Requests - Tips

Asked

Viewed 404 times

2

The thing is, I’d like a suggestion and tip to make a correct system. For example, today I use jquery and many requests $.ajax, this is to popular some data, to send form data and etc. But I realized that I’m making many requests to the server and I don’t know if I’m using right.

To give an example I have a customer registration form for example, when the registration page is opened I call several requests being them:

  • Load the states -- Load cities (when changes status loads cities)
  • Loading the trades
  • Carry the marital status
  • Carrega Place of the dwelling

Among other data I dynamically populate

My question is this, which is the best way to make these requests? or what to do maybe to optimize and not fill my code with $.ajax...

I recently saw a post from wBruno on his personal blog saying that it is not to use jQuery exaggeratedly, and I’m doing exactly this hahah..

How do you work with this? When you need to popular several values in a Dropdown? I appreciate the tips!

3 answers

1

Use compact methods

Ajax is a very extensive method, you can use a more compact method that exists in the list of jQuery Ajax Shorthand Methods.

List:

  • jQuery.get()
  • jQuery.getJSON()
  • jQuery.get()
  • jQuery.post()
  • .load()

Centralize the resources

If you need to reduce the number of requests separate the requests as a CRUD, dummy example in php:

jQuery

$.post( "script.php", {"acao": "select"}).done(function( data ) {
    console.log(data);
});

PHP

switch($_POST['acao']){
   case 'select':
      $output['ESTADOS'] = carregaEstados();
      $output['PROFISSOES'] = carregaProfissoes();
      $output['ESTADOCIVIL'] = carregaEstadoCivil();
      $output['LOCALMORADIA'] = carregaLocalMoradia();
      break;
}

echo json_encode($output);

Popular fields

If you only use jQuery, you don’t use any framework you use data-binding, you can create your own popular functions. according to your need I created one for popular fields just to demonstrate how reusable it can be.

$.fn.populateInput = function(data) {

  this.init = function() {
    if (!!data) {
      this.find('input').each(function(key, val) {
        var input = $(this);
        input.val(data[0][input.attr("name")]);
      });
    }
  };

  this.init();
  return this;
};

var data = {
  0: {
    nome: "Gabriel",
    sobrenome: "Rodrigues"
  }
};
var meuForm = $("#meuForm");
meuForm.populateInput(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id="meuForm">
  <input type="text" name="nome">
  <input type="text" name="sobrenome">
</form>

  • And ai Gabriel, I appreciate your comment and your examples, you commented on framework that uses data-Binding, you refer me some? thanks again.

  • @Crazy da uma lida nesse artigo: http://engineering.paiza.io/entry/2015/03/12/145216

0

Why not search for all the information in a Json variable and then work with it locally with jQuery? Type: var Json = [{ states : {'RJ', 'SP', 'ES', 'MG'}, professions : {'prof 1', 'prof 2', 'prof 3'}, marital status : {'bachelor', 'married'}

}]

Then make a each on each of the variable nodes and populate the html elements.

  • I understand, but wouldn’t it be too heavy? For example, take the cities table in it has about 15 thousand records for more, carry all this would not get too heavy? recently I saw some files in . json format, I already used?

  • You can use the jQuery autocomplete, where you can define from how many characters you search, type, search cities after 3 characters typed in the input, then you only find cities that start with these 3 characters.

  • I get it, only then I would make new requests? I thank you in advance for the answers!

  • Yes, but it is a solution, I do so, because it is better to make 4 requests of 100 records to make one of 15000.

0

One option, if it is not so much data is to bring everything at once, if it is too much data, depending on the user’s connection, it may take ai yes it compensates to make several requests. I had a case of having two Dropdowns in which one depended on the other, what I did was bring everything at once and as the selection of the first dropdown I changed the data of the second. In that case I thought it best to use the v-for of Vue.js to display the data list more easily.

This business of not filling the jQuery code is more with regard to DOM manipulation, however if you use jQuery just to make ajax, there are other smaller and easier solutions.

  • I appreciate the tip, and on the item "other minor and easy solutions" what would be? As I said in case I need to make the requisitions to popular my dropdown and are various, I can’t think of another medium.. I thank you again

  • From what I know, two legal and very easy solutions are the aja.js or the polyfill ES6 window fetch. developed by Github, or trying to do it with pure javascript (it’s no longer easy), like this http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery

Browser other questions tagged

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