Run cURL command in an HTML / JS application

0

I have zero experience in API, JSON, Ajax, cURL, the most I learned in college was basic HTML, CSS, JS and PHP, I already killed myself to search and watch video, but without anyone with experience to help it gets difficult , I'm almost giving up, I need some guidance.

I'm in a project where I have to get data from a site through their API and play in an HTML / JS application, following the steps in the API documentation ( link ), I was able to pull data through cURL, which generates a JSON for me, now I need to know how to make this request directly in this HTML / JS application so that the data appears right in the browser.

Who can help, I thank you.

Edit: I used this cURL command

curl   https://rtm.zopim.com/stream/chats/active_chats \
-H "Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxx"
    
asked by anonymous 24.10.2017 / 19:32

1 answer

1

There are some steps from the frontend to the backend:

First you need the PHP script that makes the request for the API of that third party we will call it chat.php and assume that it is hosted with the https://meuexemplo.com.br/ domain. So your resource will be https://meuexemplo.com.br/chat.php

Chat.php file:

<?php
// Faz alguma coisa (requisições com cURL por exemplo) para conseguir o JSON que deve aparecer no HTML
$resultado = array(); // coloquei um array vazio, mas vamos pensar que ele contêm os dados que devem ser direcionados para o HTML
header('Content-Type: application/json');
echo json_encode($resultado);

Now that you have set up the backend file that will feed your HTML / JS, let's go to Javascript, or rather, let's use the jQuery framework:

$(function(){
  $.ajax({
    url: 'https://meuexemplo.com.br/chat.php',
    dataType: 'json',
    success: function(data) {
      // A variável data contêm o JSON de resposta do seu backend.
      // Eu estou exemplificando que estamos acessando a chave 'teste' de data
      $('#resultado').html(data.test);
    }, error: function(err) {
      $('#resultado').html('Deu erro, porque não temos o backend neste exemplo');
    }
  });
});
<div id="resultado"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

With the data in JSON format inside a variable in success of the $ .ajax function you can use jQuery to insert the information into a table, div, that is, anywhere in your HTML (frontend).

While using examples that are not real if you mind the process, you have a PHP script that retrieves the data you need and it will be accessed through a JavaScript with the $.ajax method of jQuery. And, after AJAX has the data you use JS / jQuery to feed your HTML interface.

    
26.10.2017 / 04:04