How to perform a simple state and city search with jquery and json

Asked

Viewed 947 times

0

This is my json test and precise, through the keys "ce" and "fortress", perform a search of their respective data. In this case, the search is done by AJAX which has been subjected to a POST through a form with two select:

{
  "ce": {
    "fortaleza": [
      {
        "nome": "Teste",
        "email": "[email protected]",
        "cel": "(xx) xx-xx"
      },
      {
        "nome": "Teste",
        "email": "[email protected]",
        "cel": "(xx) xx-xx"
      }
    ],

    "sobral": [
      {
        "nome": "Teste",
        "email": "[email protected]",
        "cel": "(xx) xx-xx"
      },
      {
        "nome": "Teste",
        "email": "[email protected]",
        "cel": "(xx) xx-xx"
      }
    ]
  },
    "rn": {
    "carnaiba": [
      {
        "nome": "Teste",
        "email": "[email protected]",
        "cel": "(xx) xx-xx"
      },
      {
        "nome": "Teste",
        "email": "[email protected]",
        "cel": "(xx) xx-xx"
      }
    ],

    "sorisal": [
      {
        "nome": "Teste",
        "email": "[email protected]",
        "cel": "(xx) xx-xx"
      },
      {
        "nome": "Teste",
        "email": "[email protected]",
        "cel": "(xx) xx-xx"
      }
    ]
  }
}

Form with example result:

inserir a descrição da imagem aqui

I have no idea how to do this with jquery, because I am completely layman.

2 answers

1


You can use the method $.getJSON() from jQuery to recover data from your JSON page and there just select the data based on what the user typed.

Take the example

index.html

// captura o evento de submit do formulário
$('#form').submit(function(event) {
	// previne que o formulário seja enviado para a página default
	event.preventDefault();

	// salva os dados do formulário em um array
	var form = $(this).serializeArray();

	// pega o estado dos dados recuperados
	var estado = form[0];

	// pega a cidade dos dados recuperados
	var cidade = form[1];

	// faz uma requisição para a página em json
	$.getJSON('data.json', function(data) {
		// seleciona o estado e cidade baseado no que o usuário seleciononou
		var match = data[estado.value][cidade.value];

		// faz um loop no objeto retornado
		$.each(match, function(index, element) {
			// faz algo com os dados
			console.info(element);
		});
	});
});
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<form id="form">
		<div>
			<label for="estado">Estado</label>
			<select id="estado" name="estado">
				<option value="ce">Ceará</option>
				<option value="outro">Outras opções</option>
			</select>
		</div>
		<div>
			<label for="cidade">Cidade</label>
			<select id="cidade" name="cidade">
				<option value="fortaleza">Fortaleza</option>
				<option value="outro">Outras opções</option>
			</select>
		</div>
		<input type="submit">
	</form>
	<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
	<script src="scripts.js"></script>
</body>
</html>

The data.json has the same content you provided in the post..

  • Perfect! How do I, when there is a new search, clear the previous one? Thank you.

  • What would be "clean" in the case? Return selects to initial state?

  • Exactly. It cleans the previous one and queries a new one. That’s all after clicking on Ubmit. Another problem that keeps repeating. I wish I didn’t hear a second consultation in the same estado+cidade, but only estado+outra cidade.

  • To reset a select to set its index to -1 (or any other index you want), like this: $('select').prop('selectedIndex', -1); if you prefer you can also insert an input type reset and simulate a click on it. And to disable select will depend on the situation, do you want that after refreshing the page it can select all again? Just use this $('select option').attr('disabled','disabled'); Otherwise you can work with localStorage, sessionStorage, etc.

1

You can get the JSON file through the method $.getJSON(path), that returns you a Promise. Based on this Promise, you can check the data contained in the file if it has been recovered successfully.

As the file is already converted to a JS object, you can access the properties of it, which contains the data you want. Follow code below.

$(document).ready(function () {
    'use strict';

    var promiseDados = $.getJSON('dados.json'),
        chaveEstado = 'ce',
        chaveCidade = 'fortaleza';

    promiseDados.done(function (dados) {
        var pessoas = dados[chaveEstado][chaveCidade];

        pessoas.forEach(function (pessoa, index) {
            var div = $('<div></div>');

            div.append('<span>PESSOA ' + (index + 1) + '</span>');

            Object.keys(pessoa).forEach(function (key) {
                div.append('<div>' + pessoa[key] + '</div>');
            });

            $('body').append(div);
        });
    });

    promiseDados.fail(function (error) {
        console.log('Falha ao obter JSON', error);
    });
});

Browser other questions tagged

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