Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive and process JSON using fetch API in Javascript

In my Project when conditions are insufficient my Django app send JSON response with message.

I use for this JsonResponse() directive,

Code:

data = {
    'is_taken_email': email
}
return JsonResponse(data)

Now I want using Javascript fetch API receive this JSON response and for example show alert.

I don't know how to use fetch API to do this. I want to write a listener who will be waiting for my JSON response from Django App.

I try:

function reqListener() {
  var stack = JSON.parse(data);
  console.log(stack);
}

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;

I want to compare JSON from my Django app with hardcoded JSON:
For example: fetch( 'is_taken_email': email) - > then make something

OR

receive JSON from my Django app and as AJAX make it:

success: function(data) { if (data.is_taken_email) { make something; }

Thanks in advance!


1 Answers

A fetch API is provided in the global window scope in javascript, with the first argument being the URL of your API, it's Promise-based mechanism.

Simple Example

// url (required)
fetch('URL_OF_YOUR_API', {//options => (optional)
    method: 'get' //Get / POST / ...
}).then(function(response) {
    //response
}).catch(function(err) {
// Called if the server returns any errors
  console.log("Error:"+err);
});

In your case, If you want to receive the JSON response

 fetch('YOUR_URL')
    .then(function(response){
         // response is a json string
        return response.json();// convert it to a pure JavaScript object
    })
    .then(function(data){
         //Process Your data  
      if (data.is_taken_email)   
           alert(data);
    })
    .catch(function(err) {
        console.log(err);
      });

Example using listener based on XMLHttpRequest

function successListener() {  
  var data = JSON.parse(this.responseText);  
  alert("Name is: "+data[0].name);  
}

function failureListener(err) {  
  console.log('Request failed', err);  
}

var request = new XMLHttpRequest();  
request.onload = successListener;  
request.onerror = failureListener;  
request.open('get', 'https://jsonplaceholder.typicode.com/users',true);  
request.send();

Example of Using Listener as setInterval (I'm not sure that you want to do something like this, it's just to share with you)

var listen = setInterval(function() {

  fetch('https://jsonplaceholder.typicode.com/users')
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      if (data[0].name)
        console.log(data[0].name);
    })
    .catch(function(err) {
      console.log(err);
    });

}, 2000);//2 second

I am not familier with Django, but I hope this could help you.

like image 186
iLyas Avatar answered Jun 28 '26 11:06

iLyas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!