TEORIA - PRACTICA FETCH JS API JSON PHP MYSQL (GET-POST-PUT-DELETE)

 const url = 'https://jsonplaceholder.typicode.com/users';


let data = {

  name: 'Sammy'

}


let fetchData = {

  method: 'POST',

  body: JSON.stringify(data),

  headers: new Headers({

    'Content-Type': 'application/json; charset=UTF-8'

  })

}


fetch(url, fetchData)

  .then(function() {

    // Handle response you get from the API

console.log(response);

  });




fetch('https://example.com/delete-item/' + id, {

  method: 'DELETE',

})

.then(res => res.text()) // or res.json()

.then(res => console.log(res))




const putMethod = {

 method: 'PUT', // Method itself

 headers: {

  'Content-type': 'application/json; charset=UTF-8' // Indicates the content 

 },

 body: JSON.stringify(someData) // We send data in JSON format

}


// make the HTTP put request using fetch api

fetch(url, putMethod)



.then(response => response.json())

.then(data => console.log(data)) // Manipulate the data retrieved back, if we want to do something with it

.catch(err => console.log(err)) // Do something with the error


const someData = {

 title: document.querySelector(TitleInput).value,

 body: document.querySelector(BodyInput).value

}



function update(id, data){

  fetch(apiUrl + "/" + id, {

    method: 'PATCH',

    body: JSON.stringify({

     data

    })

  }).then((response) => {

    response.json().then((response) => {

      console.log(response);

    })

  }).catch(err => {

    console.error(err)

  })


async function loadItems() {

        try {

            let response = await fetch(`https://url/${AppID}`);

            let result = await response.json();

            return result;

        } catch (err) {

        }

    }


    async function addItem(item) {

        try {

            let response = await fetch("https://url", {

                method: "POST",

                body: JSON.stringify({

                    AppId: appId,

                    Key: item,

                    Value: item,

                    someBoolean: false,

                }),

                headers: {

                    "Content-Type": "application/json",

                },

            });

            let result = await response.json();

            return result;

        } catch (err) {

        }

    }


    async function removeItem(id) {

        try {

            let response = await fetch(`https://url/${id}`, {

                method: "DELETE",

            });

        } catch (err) {

        }

    }


    async function updateItem(item) {

        try {

            let response = await fetch(`https://url/${item.id}`, {

                method: "PUT",

                body: JSON.stringify(todo),

                headers: {

                    "Content-Type": "application/json",

                },

            });

        } catch (err) {

        }

    }




fetch('https://reqres.in/api/users', + id {

  method: 'PUT',

  headers: {

    'Content-Type': 'application/json'

  },

  body: JSON.stringify({

    name: 'user'

  })

})

.then(res => {

  return res.json()

})

.then(data => console.log(data))



fetch('https://reqres.in/api/users' + id, {

  method: 'DELETE',

})

.then(res => {

  return res.json()

}) 

.then(data => console.log(data))



fetch('https://reqres.in/api/users', {

  method: 'PUT',

  headers: {

    'Content-Type': 'application/json'

  },

  body: JSON.stringify({

    id: 1,

    first_name: 'Anthony'

  })

})

.then(res => {

  return res.json()

})

.then(data => console.log(data))


JSON.stringify


/////////////

Petición POST

La utilizaremos para insertar nuevos registros.

fetch('http://localhost:3009/users', {

    method: 'POST',

    headers: {

        "Content-Type": "application/json",

    },

    body: JSON.stringify({ mail: 'pp@pp.com', password: '123' })

})

.then(res => res.json())

.then(res=> {

      console.log(res);

});

Petición PUT

La utilizaremos para actualizar información existente.

Enviaremos la información que queremos actualizar en el cuerpo de la petición y la id del elemento que queremos actualizar en la url de la petición.

fetch('http://localhost:3005/users/1', {

        method: 'PUT',

        headers: {

            "Content-Type": "application/json",

        },

        body: JSON.stringify({ mail: 'ññññ', password: 'ññññ' })

 })

.then(res => res.json())

.then(res=> {

      console.log(res);

});

Petición Delete

La utilizaremos para eliminar información existente.

fetch('http://localhost:3005/users/2', {

      method: 'DELETE',

})

.then(res => res.json())

.then(res=> {

      console.log(res);

});



3. POST JSON data

POST-ing JSON data to the server is slightly trickier.


First, indicate the HTTP method as 'POST'.


Second, set the body parameter with the object's JSON (as a string).


async function postName() {

  const object = { name: 'James Gordon' };

  const response = await fetch('/api/names', {

    method: 'POST',

    body: JSON.stringify(object)

  });

  const responseText = await response.text();

  console.log(responseText); // logs 'OK'

}

postName();

Take a look at body option value. JSON.stringify(object) utility function stringifies the JavaScript object into a JSON string.


body option requires a string, but not an object.


This approach works when performing POST, but as well PUT and PATCH requests.


3.1 Explicitly posting JSON

Again, some servers might require you to indicate explicitly that you POST (or PATCH, or PUT) data in JSON format.


In such a case indicate the content type of data you're pushing, particularly setting the Content-Type header to application/json.


// ...

const object = { name: 'James Gordon' };

const response = await fetch('/api/names', {

  method: 'POST',

  body: JSON.stringify(object),

  headers: {

    'Content-Type': 'application/json'

  }

});

// ...

4. Using a request object

In the examples above options argument of fetch(URL, option) was used to set the method, headers, and body options.


But sometimes you might want to encapsulate the request data into an object, thus Request becomes handy.


For example, let's post JSON data by creating a request object:


// ...

const object = { name: 'James Gordon' };

const request = new Request('/api/names', {

  method: 'POST',

  body: JSON.stringify(object),

  headers: {

    'Content-Type': 'application/json'

  }

});

const response = await fetch(request);


 


fetch('https://reqbin.com/echo/get/json', {

    method: 'GET',

    headers: {

        'Accept': 'application/json',

    },

})

   .then(response => response.json())

   .then(response => console.log(JSON.stringify(response)))









Updated: Feb 21, 2023 Viewed: 7829 times  Author: ReqBin 

What is JSON?

JavaScript Object Notation (JSON) is a language-independent text format for storing and exchanging data. Web applications use JSON to exchange data between a web browser and a server and exchange data between servers via REST API. For many programming languages, including JavaScript, Java, C ++, C #, Go, PHP, and Python, there are ready-made code libraries for creating and manipulating JSON data. JSON file names use the .json file extension.


JSON Example

{

  "Id": 78912,

  "Customer": "Jason Sweet",

  "Quantity": 1,

  "Price": 18.00

}


What is Fetch API?

The Fetch API presents a new global fetch() method, which allows network requests to be made similarly to the XMLHttpRequest (XHR) method but more powerfully and flexibly. Fetch API is a better alternative to XMLHttpRequest and can be easily integrated with other technologies, such as Service Workers. The main difference between the Fetch API and XMLHttpRequest is that Fetch uses promises, which allows you to have a more straightforward and cleaner API without nested callbacks.



JavaScript Fetch JSON Example

Below are example of getting JSON from the ReqBin echo URL using Fetch API.


JavaScript Fetch JSON Example

Execute

fetch('https://reqbin.com/echo/get/json')

   .then(response => response.text())

   .then(text => console.log(text))

  

// output: {"success":"true"}


The response.text() method does not automatically parse the response body and resolves to a string. To automatically parse a JSON response into a JavaScript object, you need to use the response.json() method.


How to fetch JSON data in JavaScript?

To get JSON data from an API endpoint, you must first call the fetch() method and then response.json(). The fetch() method returns a Promise representing the server's response, and the response.json() resolves to the result of parsing the JSON response into a JavaScript object.


JavaScript Fetch JSON Data with Fetch API Example

Execute

fetch('https://reqbin.com/echo/get/json')

   .then(response => response.json())

   .then(json => console.log(JSON.stringify(json)))

  

// output: {"success":"true"}


How to POST JSON data using Fetch API?

To post JSON data to the server using the Fetch API, you need to tell fetch() to use the POST method and pass the JSON data in the "body" parameter. The Content-Type: 'application/json' HTTP header is necessary for the server to correctly receive and interpret the JSON data in the body of the HTTP message.


JavaScript POST JSON with Fetch API Example

Execute

fetch('https://reqbin.com/echo/post/json', {

    method: 'POST',

    headers: {

        'Content-Type': 'application/json'

    },

    body: JSON.stringify({"id": 1})

})

   .then(response => console.log(response.status))

  

// output: 200


How to fetch JSON data using HTTP POST method?

To fetch JSON data from the server using the HTTP POST method, you need to tell fetch() to make a POST request by passing the "method: 'POST'".


JavaScript Fetch JSON with HTTP POST Example

Execute

fetch('https://reqbin.com/echo/post/json', {

    method: 'POST'

})

   .then(response => response.json())

   .then(json => console.log(JSON.stringify(json)))

  

// output: {"success":"true"}


How to fetch JSON using JavaScript async and await operators?

To fetch JSON data using JavaScript's async and await operators, you must first call await fetch() to resolve it to a Response object and then call await response.json() to resolve it to a parsed JSON object.


JavaScript Fetch JSON using async and await

Execute

const response = await fetch('https://reqbin.com/echo/get/json');


const json = await response.json();


console.log(JSON.stringify(json));

  

// output: {"success":"true"}



//////////////



const myDataObject = { name: `SilvenLEAF`, age: 19, isTeen: true};


fetch(YOUR_URL, {

    method: 'POST',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(myDataObject)

})

.then(response => {

    return response.json( )

})

.then(data => 

    // this is the data we get after posting our data, do whatever you want with this data

    console.log(data) 

);



const mySecondDataObject = {

    "userId": 1,

    "id": 1,

    "title": "The post of SilvenLEAF",

    "completed": false

};




fetch('https://jsonplaceholder.typicode.com/posts/', {

    method: 'POST',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(mySecondDataObject)

})

.then(response => {

    return response.json( )

})

.then(data => 

    // this is the data we get after posting our data, do whatever you want with this data

    console.log(data) 

);


COMPLETE GUIDE FOR USING FETCH (PUT)

PROMISE VERSION

const myDataObject = { name: `SilvenLEAF`, age: 19, isTeen: true};


fetch(YOUR_URL, {

    method: 'PUT',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(myDataObject)

})

.then(response => {

    return response.json( )

})

.then(data => 

    // this is the data we get after putting our data, do whatever you want with this data

    console.log(data) 

);



//your data to send

const mySecondDataObject = {

    "userId": 1,

    "id": 1,

    "title": "The blog of SilvenLEAF",

    "completed": false

};




fetch('https://jsonplaceholder.typicode.com/posts/1', {

    method: 'PUT',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(mySecondDataObject)

})

.then(response => {

    return response.json( )

})

.then(data => 

    // this is the data we get after putting our data, do whatever you want with this data

    console.log(data) 

);




COMPLETE GUIDE FOR USING FETCH (DELETE)

PROMISE VERSION

const myDataObject ={ userId: 1}

fetch(YOUR_URL, {

    method: 'DELETE',

    headers: {

      'Content-Type': 'application/json'

    },

    body: JSON.stringify(myDataObject)

})

.then(response => {

    return response.json( )

})

.then(data => 

    // this is the data we get after doing the delete request, do whatever you want with this data

    console.log(data) 

);

<body>

   <form id="form" method="post">

       <input type="text", id="name" placeholder="Name"/></br>

       <input type="text", id="body" placeholder="Body"/></br>

       <input type="submit" value="Add"/>

    </form> 

    <div>

    <h3>The Following data is successfuly posted</h3>

    <h4 id="title"></h4>

    <h5 id="bd"></h5>

    </div>

</body>


<script>

var form=document.getElementById('form')


form.addEventListener('submit', function(e){

 e.preventDefault()


 var name=document.getElementById('name').value

 var body=document.getElementById('body').value


 fetch('https://jsonplaceholder.typicode.com/posts', {

  method: 'POST',

  body: JSON.stringify({

    title:name,

    body:body,


  }),

  headers: {

    'Content-type': 'application/json; charset=UTF-8',

  }

  })

  .then(function(response){ 

  return response.json()})

  .then(function(data)

  {console.log(data)

  title=document.getElementById("title")

  body=document.getElementById("bd")

  title.innerHTML = data.title

  body.innerHTML = data.body  

}).catch(error => console.error('Error:', error)); 

});

</script>




Specifying the HTTP method with fetch() #

The fetch() method accepts an optional second argument: an object of options and settings.


To use an HTTP method other than GET, pass in an object with the method key, and use your desired HTTP method as the value.


// Make a POST request

fetch('https://jsonplaceholder.typicode.com/posts', {

method: 'POST'

}).then(function (response) {

if (response.ok) {

return response.json();

}

return Promise.reject(response);

}).then(function (data) {

console.log(data);

}).catch(function (error) {

console.warn('Something went wrong.', error);

});

Sending data with fetch() #

Another optional property you can include with a fetch() request is body. The body property holds any data you want to send as part of your HTTP (or API) request.


Depending on the endpoint, this data may be sent as a JSON object or a query string. Some APIs allow both types, while some require just one or the other.


API requests are sent with headers that include information about the request.


When sending data with fetch(), you will need to specify the Content-type, which tells the API if the data you sent is JSON or a query string. This is another property you can pass into the options with your fetch() method.


fetch('https://jsonplaceholder.typicode.com/posts', {

method: 'POST',

body: '', // The data

headers: {

'Content-type': '' // The type of data you're sending

}

});

Sending data as a JSON object #

To send data as a JSON object, use the JSON.stringify() method to convert your data into a string. For your headers['Content-type'], use application/json as the value.


Note: the JSON Placeholder API request that you also specify the charset as UTF-8. This is not usually required.


fetch('https://jsonplaceholder.typicode.com/posts', {

method: 'POST',

body: JSON.stringify({

title: 'New Pirate Captain',

body: 'Arrrrrr-ent you excited?',

userId: 3

}),

headers: {

'Content-type': 'application/json; charset=UTF-8'

}

}).then(function (response) {

if (response.ok) {

return response.json();

}

return Promise.reject(response);

}).then(function (data) {

console.log(data);

}).catch(function (error) {

console.warn('Something went wrong.', error);

});

Here’s a demo.


Sending data as a query string #

To send data as a query string, include the query string as the value of the body property. Any query string properties that may have spaces or special characters in them should be passed into the encodeURIComponent() to encode it.


For your headers['Content-type'], use application/x-www-form-urlencoded as the value.


fetch('https://jsonplaceholder.typicode.com/posts', {

method: 'POST',

body: 'title=' + encodeURIComponent('New Pirate Captain') + '&body=' + encodeURIComponent('Arrrrrr-ent you excited?') + '&userID=3',

headers: {

'Content-type': 'application/x-www-form-urlencoded'

}

}).then(function (response) {

if (response.ok) {

return response.json();

}

return Promise.reject(response);

}).then(function (data) {

console.log(data);

}).catch(function (error) {

console.warn('Something went wrong.', error);

});


Fetching data

AJAX, acrónimo de Asynchronous JavaScript And XML o JavaScript asíncrono y XML, es una técnica que nos permite comunicarnos con otros servicios para obtener/añadir/modificar/borrar información de manera asíncrona (a continuación de ser cargada la web). Hoy en día seguimos utilizando la misma estrategia salvo que disponemos de APIs más modernas como Fetch. También lo puedes considerar: realizar petición HTTP asíncrona.

Obtener datos de un servidor nos abre la puerta a una cantidad ilimitada de información por parte de otros servicios (estadísticas, bases de datos, cálculos…) que bien tratada enriquecerán la navegación con estructuras nuevas de HTML o elementos que mejoran la experiencia.

Por ejemplo si estoy haciendo un buscador de viajes, sería agradable indicar que tiempo hará en el destino cuando se indique la fecha de salida. En este caso preguntaría a un servidor externo (API) dicha información para después crear un apartado dentro de la web con la temperatura. ¿Esas predicciones están en mi código? No, para nada. Pregunto, me responden y muestro.

API significa: interfaz de programación de aplicaciones o application programming interface. Puede ser interna del lenguaje, como el propio fetch o externa, como un servicio que nos permite hacerle peticiones HTTP.

 

Cuando gestionamos información, independientemente del lenguaje o base de datos, disponemos 4 acciones básicas elementales.

Crear (Create).

Leer (Read).

Actualizar (Update).

Borrar (Delete).

Para simplificar se le denomina CRUD.

Cuando realizamos peticiones HTTP, o hacemos peticiones, disponemos del mismo sistema aunque usamos verbos para comunicarnos con el servidor.

GET: Leer.

POST: Crear.

PUT: Actualizar.

DELETE: Borrar.

O también llamados métodos (Methods).

Si quisiera conectarme con un API externo usaremos la función fetch.

fetch('https://dominio.com/')

  .then(function(response) {

    // Transforma la respuesta. En este caso lo convierte a JSON

    return response.json();

  })

  .then(function(json) {

    // Imprimo por consola

    console.log(json)

  });

Con versión ES6 de JavaScript se modernizó las herramientas para realizar peticiones en AJAX, llamada fetch. El 27 de Marzo del 2017 Safari lo implementó aunque Chrome y Firefox ya lo tenían habilitado desde 2015. Fue en ese momento cuando se convirtió en una posibilidad para usarlo, aunque encontrarás por la red muchos ejemplos antiguos usando XMLHttpRequest.

Su ejecución es asíncrona, por lo que siempre nos devolverá una Promise (una promesa). Para esperar a que termine tenemos 2 posibilidades, o usar la función then() o ejecutarlo en una función asíncrona y esperar con await.

async function hacerPeticion() {

  // Realiza la petición

  const miFetch = await fetch('https://dominio.com/');

  // Transforma la respuesta. En este caso lo convierte a JSON

  const json = await miFetch.json();

  // Imprimo por consola

  console.log(json);

}


hacerPeticion();

Mi recomendación es que realices las llamadas con este último ejemplo ya que será más fácil de estructurar y además es más rápida en devolver resultados (hablamos de milésimas de segundo, tampoco hay que perderla cabeza con el tema). Igualmente ten cuidado cuando realices un return ya que devolverá una promesa.

GET

 

Usando .then()

fetch('https://jsonplaceholder.typicode.com/users')

  .then(function(response) {

    // Transforma la respuesta. En este caso lo convierte a JSON

    return response.json();

  })

  .then(function(json) {

    // Usamos la información recibida como necesitemos

    console.log(json)

  });

Otra versión con función arrow.

fetch('https://jsonplaceholder.typicode.com/users')

  .then((response) => response.json())

  .then((json) => console.log(json));

Usando await

async function obtenerUsuarios() {

  // Realiza la petición

  const miFetch = await fetch('https://jsonplaceholder.typicode.com/users');

  // Transforma la respuesta. En este caso lo convierte a JSON

  const json = await miFetch.json();

  // Imprimo por consola

  console.log(json);

}


obtenerUsuarios();

Parámetros en la URL

En ciertas ocasiones necesitamos incluir parámetros en la URL. Es un caso particular del verbo GET, ya que es la única manera de transmitir configuraciones al servidor. Las rutas tendrán la siguiente forma:

https://dominio.com?query=barcos&page=4

El símbolo del interrogante (?) separa el nombre del dominio de los parámetros, cuyo formato es siempre “nombre parámetro” + “=” + “valor”. En el caso anterior podemos observar el parámetro query con el valor barco, y el parámetro page con el valor 4. Entre los parámetros se utiliza un & como separador, y no existen los espacios o carácteres especiales (como los acentos o eñes).

¿Cuando debemos utilizarlo? Cuando la documentación de la API nos pida transmitirle parámetros en este formato, usando el verbo GET. La forma más moderna, y práctica, es utilizar el objeto URLSearchParams.

const URL_API = "https://dominio.com";

const misParametros = new URLSearchParams();

misParametros.set("query", "barcos");

misParametros.set("page", 4);

const URLConParametros = `${URL_API}?${misParametros.toString()}`;


console.log(URLConParametros);

// https://dominio.com?query=barcos&page=4

¡No hagas la URL a mano! Hay carácteres, como los espacios o los acentos, que no podrás concadenar correctamente sin previamente parsearlo a URI. Usa URLSearchParams aunque solo sea un solo parámetro.

POST

 

Usando .then()

fetch('https://jsonplaceholder.typicode.com/users', {

  headers: {

    'Content-type': 'application/json'

  },

  method: 'POST',

  body: JSON.stringify({ id: 11, name: 'Rodrigo Díaz de Vivar', username: 'El Cid' })

  })

  .then(function(response) {

    // Transforma la respuesta. En este caso lo convierte a JSON

    return response.json();

  })

  .then(function(json) {

    // Usamos la información recibida como necesitemos

    console.log(json)

  });

Otra versión con función arrow.

fetch('https://jsonplaceholder.typicode.com/users', {

  headers: {

    'Content-type': 'application/json'

  },

  method: 'POST',

  body: JSON.stringify({ id: 11, name: 'Rodrigo Díaz de Vivar', username: 'El Cid' })

  })

  .then((response) => response.json())

  .then((json) => console.log(json));

Usando await

async function anyadirUsuario() {

  // Realiza la petición

  const miFetch = await fetch('https://jsonplaceholder.typicode.com/users', {

  headers: {

    'Content-type': 'application/json'

  },

  method: 'POST',

  body: JSON.stringify({ id: 11, name: 'Rodrigo Díaz de Vivar', username: 'El Cid' })

  });

  // Transforma la respuesta. En este caso lo convierte a JSON

  const json = await miFetch.json();

  // Imprimo por consola

  console.log(json);

}


anyadirUsuario();

PUT

 

Usando .then()

fetch('https://jsonplaceholder.typicode.com/users/1', {

  headers: {

    'Content-type': 'application/json'

  },

  method: 'PUT',

  body: JSON.stringify({ username: 'El Campeador' })

  })

  .then(function(response) {

    // Transforma la respuesta. En este caso lo convierte a JSON

    return response.json();

  })

  .then(function(json) {

    // Usamos la información recibida como necesitemos

    console.log(json)

  });

Otra versión con función arrow.

fetch('https://jsonplaceholder.typicode.com/users/1', {

  headers: {

    'Content-type': 'application/json'

  },

  method: 'PUT',

  body: JSON.stringify({ username: 'El Campeador' })

  })

  .then((response) => response.json())

  .then((json) => console.log(json));

Usando await

async function actualizarUsuario() {

  // Realiza la petición

  const miFetch = await fetch('https://jsonplaceholder.typicode.com/users/1', {

  headers: {

    'Content-type': 'application/json'

  },

  method: 'PUT',

  body: JSON.stringify({ username: 'El Campeador' })

  });

  // Transforma la respuesta. En este caso lo convierte a JSON

  const json = await miFetch.json();

  // Imprimo por consola

  console.log(json);

}


actualizarUsuario();

DELETE

 

Usando .then()

fetch('https://jsonplaceholder.typicode.com/users/2', {

  method: 'DELETE'

  })

  .then(function(response) {

    // Transforma la respuesta. En este caso lo convierte a JSON

    return response.json();

  })

  .then(function(json) {

    // Usamos la información recibida como necesitemos

    console.log(json);

  });

Otra versión con función arrow.

fetch('https://jsonplaceholder.typicode.com/users/2', {

  method: 'DELETE'

  })

  .then((response) => response.json())

  .then((json) => console.log(json));

Usando await

async function borrarUsuario() {

  // Realiza la petición

  const miFetch = await fetch('https://jsonplaceholder.typicode.com/users/1', {

  headers: {

    'Content-type': 'application/json'

  },

  method: 'DELETE'

  });

  // Transforma la respuesta. En este caso lo convierte a JSON

  const json = await miFetch.json();

  // Imprimo por consola

  console.log(json);

}


borrarUsuario();

https://programadorwebvalencia.com/cursos/javascript/fetching-data/


///////


Get and Post method using Fetch API

Difficulty Level : Easy

Last Updated : 17 Sep, 2021

Read

Discuss

Courses

Practice

Video


The fetch() method is used to send the requests to the server without refreshing the page. It is an alternative to the XMLHttpRequest object.

The basic syntax of a fetch() request is as follows: 

 


fetch(url, {options})

.then(data => {

    // Do some stuff here

})

.catch(err => {

    // Catch and display errors

})

The difference between XMLHttpRequest and fetch is that fetch uses Promises which are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.

However there are still some browsers that do not support fetch() method, so for those, we have to stick with the XMLHttpRequest object.

A fetch() method can be used with many type of requests such as POST, GET, PUT and DELETE.

GET method using fetch API: 

In this example, we are going to use JSONPlaceholder which provides REST API get and post random data such as posts, users, etc.

First of all, create an HTML file with the following code: 

 



<!DOCTYPE html>

<html lang="en">

  <head>

    <title>Fetch API</title>

  </head>

  <body>

    <div>

      <h1>Fetch API GET REQUEST</h1>

      <h3>Fetching Users</h3>

 

      <!-- Table to display fetched user data -->

      <table id="users"></table>

    </div>

      

    <!-- Link JavaScript file -->

    <script src="main.js"></script>

  </body>

</html>

In JavaScript, file contains the following code 

 


//  main.js

  

//  GET request using fetch()

fetch("https://jsonplaceholder.typicode.com/users")

   

    // Converting received data to JSON

    .then(response => response.json())

    .then(json => {

  

        // Create a variable to store HTML

        let li = `<tr><th>Name</th><th>Email</th></tr>`;

       

        // Loop through each data and add a table row

        json.forEach(user => {

            li += `<tr>

                <td>${user.name} </td>

                <td>${user.email}</td>        

            </tr>`;

        });

  

    // Display result

    document.getElementById("users").innerHTML = li;

});

Now, when you open the HTML file you’ll see the result as follows: 

 





When you open DevTools in Chrome (Press F12) you’ll see that a fetch request has been made to the route users. 

 




You can get more data from the request, refer to the documentation.

POST request using fetch API: 

The post request is widely used to submit forms to the server. Fetch also supports the POST method call. To do a POST request we need to specify additional parameters with the request such as method, headers, etc. 

In this example, we’ll do a POST request on the same JSONPlaceholder and add a post in the posts. It’ll then return the same post content with an ID.

In the same JavaScript file add the following content: 

 


//  main.js

  

// POST request using fetch()

fetch("https://jsonplaceholder.typicode.com/posts", {

     

    // Adding method type

    method: "POST",

     

    // Adding body or contents to send

    body: JSON.stringify({

        title: "foo",

        body: "bar",

        userId: 1

    }),

     

    // Adding headers to the request

    headers: {

        "Content-type": "application/json; charset=UTF-8"

    }

})

 

// Converting to JSON

.then(response => response.json())

 

// Displaying results to console

.then(json => console.log(json));

Now if you open your javascript console and refresh the page you’ll see a result like below –






Introducción

Enviar solicitudes GET y POST para interactuar con los datos de un servidor es una tarea fundamental para los desarrolladores web. Para realizar esta tarea, existen múltiples bibliotecas y herramientas que facilitan el trabajo, pero una de las opciones más populares y sencillas es el uso de Fetch API de JavaScript.


Realizar una solicitudes GET con Fetch API

Fetch API es una interfaz nativa de JavaScript que permite hacer solicitudes HTTP, como solicitudes GET y POST, de manera más sencilla y eficiente. Al usar Fetch API, no es necesario instalar bibliotecas adicionales y se puede obtener una sintaxis clara y elegante con muy poco código.


La sintaxis para realizar una solicitud GET con Fetch API es muy sencilla. Se debe proporcionar la URL del servidor y opcionalmente algunos parámetros de configuración. A continuación, se muestra un ejemplo de cómo hacer una solicitud GET con Fetch API:


<script>

let url = 'archivo.php?parametro1='+'valor1'+'&parametro2='+'valor2';

 


fetch(url)

  .then(response => response.json())

  .then(data => {

console.log(data);

  })

  .catch(error => {

console.error('Hubo un error:', error);

  });

  

 

</script>

<script>

let url = 'archivo.php?parametro1='+'valor1'+'&parametro2='+'valor2';

 

 

fetch(url)

  .then(response => response.json())

  .then(data => {

console.log(data);

  })

  .catch(error => {

console.error('Hubo un error:', error);

  });

  

 

</script>

En este ejemplo, se hace una solicitud GET a la URL arhivo.php, que se encuentra almacenado en el mismo servidor web. Luego, la respuesta del servidor se convierte en formato JSON y se utiliza el método then para procesar los datos. Si se produce algún error en la solicitud, se maneja en la sección catch. El codigo de ejemplo usado para el archivo nombrado archivo.php es mostrado a continuación:


<?php

$parametro1 = $_GET['parametro1'];

$parametro2 = $_GET['parametro2'];

// Realiza alguna operación con los datos recibidos


$respuesta = array(

  'resultado' => 'ok',

  'mensaje' => 'Operación completada correctamente se ha recibido los parametro1: '.$parametro1.' y parametro2: '.$parametro2

);


header('Content-Type: application/json');

echo json_encode($respuesta);

?>


<?php

$parametro1 = $_GET['parametro1'];

$parametro2 = $_GET['parametro2'];

// Realiza alguna operación con los datos recibidos

 

$respuesta = array(

  'resultado' => 'ok',

  'mensaje' => 'Operación completada correctamente se ha recibido los parametro1: '.$parametro1.' y parametro2: '.$parametro2

);

 

header('Content-Type: application/json');

echo json_encode($respuesta);

?>

Realizar una solicitud POST con Fetch API

Para realizar una solicitud POST con Fetch API, es necesario proporcionar una URL y un objeto con los datos que se desean enviar. A continuación, se muestra un ejemplo de cómo hacer una solicitud POST con Fetch API:


<script>

const datos = new FormData();

datos.append('parametro1', 'valor1');

datos.append('parametro2', 'valor2');


const opciones = {

  method: 'POST',

  body: datos

};




fetch('archivo.php', opciones)

  .then(response => response.json())

  .then(data => {

    console.log(data.mensaje);

  })

  .catch(error => {

    console.error('Hubo un error:', error);

  });

 

</script>


<script>

const datos = new FormData();

datos.append('parametro1', 'valor1');

datos.append('parametro2', 'valor2');

 

const opciones = {

  method: 'POST',

  body: datos

};

 

 

 

fetch('archivo.php', opciones)

  .then(response => response.json())

  .then(data => {

    console.log(data.mensaje);

  })

  .catch(error => {

    console.error('Hubo un error:', error);

  });

 

</script>

En este ejemplo, se hace una solicitud POST a la URL archivo.php, y se proporciona un objeto data con los datos que se desean enviar. Se utiliza la opción method: ‘POST’ para indicar que se trata de una solicitud POST y se establece el encabezado Content-Type en application/json para indicar que se está enviando datos en formato JSON. Al igual que en el ejemplo anterior, se procesa la respuesta del servidor utilizando el método then y se maneja cualquier error en la sección catch. El código PHP del archivo nombrado archivo.php se muestra a continuación:


<?php

$parametro1 = $_POST['parametro1'];

$parametro2 = $_POST['parametro2'];


// Realiza alguna operación con los datos recibidos


$respuesta = array(

  'resultado' => 'ok',

  'mensaje' => 'Operación completada correctamente se ha recibido los parametro1: '.$parametro1.' y parametro2: '.$parametro2

);


header('Content-Type: application/json');

echo json_encode($respuesta);

?>


<?php

$parametro1 = $_POST['parametro1'];

$parametro2 = $_POST['parametro2'];

 

// Realiza alguna operación con los datos recibidos

 

$respuesta = array(

  'resultado' => 'ok',

  'mensaje' => 'Operación completada correctamente se ha recibido los parametro1: '.$parametro1.' y parametro2: '.$parametro2

);

 

header('Content-Type: application/json');

echo json_encode($respuesta);

?>


if (isset($_GET['term'])){

//Conectando a la base de datos

$con = new mysqli('localhost', 'root', '', 'test_autocomplete');

$con->set_charset("utf8");

$term = $con->real_escape_string($_GET['term']);

$return_arr = array();

 

if ($query = $con->query("SELECT * FROM country where name like '%$term%' LIMIT 0 ,50

 ")) {

    while ($obj = $query->fetch_object()) {

        $row_array['id']=$obj->id;

        $row_array['alpha2Code']=$obj->iso;

        $row_array['name'] = $obj->name;

        $row_array['phonecode'] = $obj->phonecode;

        $row_array['nicename'] = $obj->nicename;

        array_push($return_arr,$row_array);

    }

 

    $query->close();

}

 

echo json_encode($return_arr);

}


Comentarios

Entradas populares de este blog

Copia de Seguridad de Archivo MS Access (.mdb) a Pendrive con VB6

INSERTAR Y UPDATE FECHA CON PHP MYSQL EN FORMULARIO METODO POST CON JQUERY ETIQUETA DATE

DETECTAR DIRECCION IP CON PHP Y JS