JSON Search for data from specific pages

Asked

Viewed 185 times

2

Hello! I am trying to pull data from an API I made in PHP to send in JSON to another site. I managed to pull the result of a whole table of employees, but now I want when click on the employees appear the other data related to it as Phone, address... pulling for his ID.

The API that connects index.html

<?php

require_once 'bd2.php';
header('Access-Control-Allow-Origin:*');
$pdo = conectar();
$listar = $pdo->query("select * from funcionarios");
echo json_encode($listar->fetchAll(PDO::FETCH_OBJ));

 ?>

The javascript that makes the JSON of index.html

$(document).ready(function(){
  var container = $("#teste2");
  var lista = container.find("#lista");
  var html = '';

  $.getJSON('http://teste.com/api-home.php', function(data){
    $.each(data, function(k, v){
      html += '<p>Nome: '+v.nome+'</p>';
      html += '<p>E-mail: '+v.email+'</p>';
      html += '<a href="perfil.html?id='+v.id+'">Perfil</a>'
    });
    lista.html(html);
  });
});

The profile API that connects to the profile.html

<?php
require_once 'bd2.php';
header('Access-Control-Allow-Origin:*');
$pdo = conectar();
$id = $_GET['id'];
$listar = $pdo->query("select * from funcionarios where id='$id'");
echo json_encode($listar->fetchAll(PDO::FETCH_OBJ));

 ?>

The javascript that makes the JSON of the.html profile

$(document).ready(function(){
  var container = $("#teste5");
  var lista = container.find("#lista2");
  var html = '';

  $.getJSON('http://teste.com/api-perfil.php', function(data){
    $.each(data, function(k, v){
      html += '<p>Telefone: '+v.telefone+'</p>';
      html += '<p>Endereço: '+v.endereco+'</p>';
    });
    lista.html(html);
  });
});

  • If you wear it like that: $listar->fetchAll(3)? What happens?

1 answer

0


I think we need to pass the ID as parameter in the javascript of the profile page.html.

In this part of the profile API you are making a GET to catch the id and get the staff with this id.

...
   $id = $_GET['id'];
   $listar = $pdo->query("select * from funcionarios where id='$id'");
...


But in the javascript of the profile page.html you nay this passing this id, as a parameter so your API will not be able to make the query in the database.

...
   $.getJSON('http://teste.com/api-perfil.php', function(data){
...


So when you click on an employee you need to pick up the ID and pass along the profile API url:

...
   $.getJSON('http://teste.com/api-perfil.php?id='+ID, function(data){
...

this way when the API code will do the $GET['id'] he’s gonna get the id that you passed by url and will have to pick up the employee for his id.

  • Thanks Mt, that’s right.

Browser other questions tagged

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