Convert jquery ajax to fetch - javascript

Does someone knows jquery and can help me convert this ajax to js fetch ?
Unfortunately, I don't know jquery and I need to convert this into js fetch.
function ajaxLogoutDetailsApi() {
$.ajax({
type: "GET",
url: "OIDCGetLogoutDetails",
async: false,
cache: false,
data: "json",
success: function (data, status, xhr) {
data = data.replace('\/\*', '');
data = data.replace('\*\/', '');
var dataJson = JSON.parse(data);
if (dataJson.logoutUrl != null) {
document.location.href = dataJson.logoutUrl;
}
},
error: function (xhr, status, err) {
console.log("error in ajaxLogoutDetailsApi");
}
});
}
Appreciate every hint.

I was going to use async/await but since there's that odd replacing before the JSON gets parsed I've reverted to old-school fetch with "thenables".
function ajaxLogoutDetailsApi() {
const endpoint = 'OIDCGetLogoutDetails';
// Fetch the JSON
fetch(endpoint)
// This is returned as the first argument
// of "then"
.then(json => {
// Weird replacement stuff
const updated = json
.replace('\/\*', '')
.replace('\*\/', '');
// Parse the JSON
const data = JSON.parse(updated);
// Set the new page if the condition is met
if (data.logoutUrl) {
window.location.href = data.logoutUrl;
}
})
// Catch any errors
.catch(error => {
console.error('Error:', error);
});
}

Related

Returned array from function - TypeError: callback is not a function

I am writing a simple js function to return an array of strings fetched using the fetch API. Whenever I try to run code, I get this error: TypeError: callback is not a function
This is my code
function getFlavors(franchise, callback) {
const fetch = require('node-fetch');
let flavors= [];
fetch('url', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({ "franchise": franchise })
})
.then(res => res.json())
.then(json => {
json.forEach(element => {
flavors.push(element.flavor)
});
// console.log(flavors);
callback(flavors); <-- VALUES DISPLAYED ON CONSOLE
})
.catch(error => {
console.log(error);
})
}
let benJerrysFlavors = [];
getFlavors("ben&jerrys",benJerrysFlavors);
I am able to see the values on the console but when attempting to return the array from function, I get the callback error
Any ideas as to what might be the issue?
It should be called with a callback function passing the data to it. And you can uptate your array then with the returned data:
let benJerrysFlavors = [];
getFlavors("ben&jerrys", (ret) => {
benJerrysFlavors = ret;
});
Try to change from:
callback(flavors)
To:
callback.push(...flavors)

Axios and response data set split to multiple arrays

I'm trying to get data from an API using axios command like
function fetchData(apiURL){
let data = [];
let options = {
method: "GET",
url: apiURL,
headers: {
"Access-Control-Allow-Origin": "*"
},
credentials: "include"
};
axios(options)
.then(response => {
data = response.data;
console.log(data);
})
.catch(function (error) {
console.log("System error : " + error);
});
return data;
}
but that will produce sets of arrays which will store arrays of JSONs from response.data in count of 100 per array set.
I haven't had problem using fetch() to retrieve all data. How I can get similar response of one large array of JSON objects instead of a split?
PS.
I have triggered that function in the
componentDidMount() {
const apiURL = process.env.REACT_APP_API;
let tableData = fetchData(apiURL);
console.log("DATA " + JSON.stringify(tableData));
this.setState({tblData : tableData});
}
Axios requests are asynchronous and return promises, so you need to adjust your example a bit so that your function returns a promise.
/**
* #return {Promise<T>}
*/
function fetchData(apiURL){
const options = {
method: "GET",
url: apiURL,
headers: {
"Access-Control-Allow-Origin": "*"
},
credentials: "include"
};
return axios(options)
.then(response => {
return response.data;
})
}
Now, when you consume this API do so asynchronously.
function somethingThatUpdatesThatUI() {
fetchData("/api/foo/bar")
.then((data) => {
//perform updates to UI or state here
})
.catch((err) => {
//alert the users that an error has happened here
})
}
You can update the componentDidMount function:
componentDidMount() {
const apiURL = process.env.REACT_APP_API;
fetchData(apiURL).then(data => {
console.log(data ${JSON.stringify(tableData)})
this.setState({tblData : data});
})
}

How to re render a .ejs page with new data after ajax request

I need to re render my homepage.ejs with new data on the server side after an ajax request. I know you can (somehow) re render the elements in the ajax callback but I was wondering if I could just re render my homapage.ejs since I have if statements that look for vacations, and current_user variables to set the right partialview.ejs
my ajax method:
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
}
});
my server side (inside of a query callback)
get_all_vacations(function (error, vacations) {
if (error) {
console.log("error when getting vacations " + error);
response.json({ success: false });
} else {
request.session.vacations = vacations;
response.render('the_vacation.ejs', { vacations : vacations, current_user : new_current_user }, function() {
response.json({success : true});
console.log("in render method");
});
}
});
i tried this but it does not work.
response.render('the_vacation.ejs', { vacations: vacations, current_user: new_current_user });
I think the simplest way, based on how your code is written would be to use window.location.reload(); when the login is successful.
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
window.location.reload(); // <--- Cause the browser to reload the EJS
}
});

Js Promise for success and error for ajax

I wrote this piece of code where I get the Json from an ajax call. I need to handle the response (success, error) with javascript promise (resolved after 2 seconds) and .then() method. I read a few stuff online but don't know where to begin. Can anybody help me please? Thanks
function jsonResult(spaceName){
var baseUrl = "BaseUrl";
$.ajax({
url:baseUrl + "/api/request/url",
type:"GET",
dataType: "json",
error: function(xhr,status,error) {
console.log(JSON.stringify(error));
},
success: function(response){
getResult(response)
}
});
}
You just need to update your function to return a promise and then in your success and error methods just call resolve and reject respectively. Here is a sample pulled from MDN:
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}
You can read more on this here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Here is a simple implementation of your example code:
function jsonResult(spaceName){
var baseUrl = "BaseUrl";
return new Promise((resolve, reject) => {
$.ajax({
url:baseUrl + "/api/request/url",
type:"GET",
dataType: "json",
error: function(xhr,status,error) {
reject(JSON.stringify(error));
},
success: function(response){
resolve(response);
}
});
});
}
You can user return a promise on calling this function which will resolve in success callbacka and will be rejected in error callback like this
function jsonResult(spaceName){
var baseUrl = "BaseUrl";
return new Promise((resolve, reject) => {
$.ajax({
url:baseUrl + "/api/request/url",
type:"GET",
dataType: "json",
error: function(xhr,status,error) {
console.log(JSON.stringify(error));
reject(error);
},
success: function(response){
resolve(getResult(response));
}
});
}
}
// Usage
jsonResult(someInput).then(response => {
// success
})
.catch(error => {
// error
});
jQuery 3.0 is Promises/A+ compatible so just remove the error/success and do the then/catch
function jsonResult(spaceName) {
var baseUrl = "BaseUrl";
$.ajax({
url:baseUrl + "/api/request/url",
type:"GET",
dataType: "json"
}).then(console.log, console.error)
}
alternativ is the the native fetch api...
fetch(baseUrl + "/api/request/url")
.then(res => res.json())
.then(console.log)

if data exists in localStorage, how to return it, or otherwise perform AJAX request?

Sorry for poor wording. Here's the code
getJSON : function(url) {
if ( localStorage.getItem(url) ) {
console.log('Getting from localStorage instead');
return $.parseJSON(localStorage.getItem(url));
} else {
console.log('No results locally, making XHR request...');
return $.ajax({
url: 'curl.php',
type: 'GET',
data: {
url : url
}
}).done(function (result) {
var json = $.parseJSON(result);
console.log('Setting to localStorage with key:', url);
localStorage.setItem(url, result);
})
}
}
Two ways of getting the data:
If it's in localStorage, this works:
console.log(this.getJSON(url))
If it's not and it's returning the AJAX object:
this.getJSON(url).done(function (result) {
console.log(result);
})
How can this be reformatted so that I can get the data without anticipating of if it's in localStorage or not?
You could add a callback parameter to your getJSON method like so:
this.getJSON = function(callback)
{
if ( localStorage.getItem(url) ) {
console.log('Getting from localStorage instead');
// If it's in local storage execute callback immediately
callback($.parseJSON(localStorage.getItem(url)));
} else {
console.log('No results locally, making XHR request...');
$.ajax({
url: 'curl.php',
type: 'GET',
data: {
url : url
}
}).done(function (result) {
var json = $.parseJSON(result);
console.log('Setting to localStorage with key:', url);
localStorage.setItem(url, result);
callback(json);
});
}
}
You could then call
getJSON(function(json) {
// Do something with json
});

Categories

Resources