I have used JQuery since a long time and i am familar with the AJAX-Calls in it. I often had the situation where i had to wait until multiple requests have been finished and continue after that with the results.
The JQuery syntax was the following:
$.when(
$.ajax({
type: "POST",
url: '/Services/Service.asmx/GetResults1',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
},
error: function (e) {
console.log('ERROR! ' + e.responseText);
}
}),
$.ajax({
type: "POST",
url: '/Services/Service.asmx/GetResults2',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
...
});
},
error: function (e) {
console.log('ERROR! ' + e.responseText);
}
})
).done(function (result1, result2) {
// Do s.th. with result1 and result2 what is already
// available here
updateUI();
...
});
How can you do this in VanillaJS?
Here is an example using the new vanilla JS fetch API
fetch('URL', {
method: "POST/PUT/GET/DELETE",
body: JSON.stringify({
name: Name,
otherData : otherData
}),`enter code here`
headers: {"content-type": "application/json"}
})
.then(res => res.json())
.then(response => {
//do what you want with the response here
})
For a GET request you can opt-out the body in fetch like
fetch('URL', {
method: "GET",
headers: {"content-type": "application/json"}
})
.then(res => res.json())
.then(response => {
//do what you want with the response here
})
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
document.getElementById("userID").innerHTML = json.userId;
document.getElementById("title").innerHTML = json.title;
document.getElementById("completed").innerHTML= json.completed;
})
<div>The User ID is : </div>
<div id="userID">
</div>
<div>The Title is : </div>
<div id="title">
</div>
<div>Completed : </div>
<div id="completed">
</div>
Compare this one with your AJAX request:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
receivedJSON = JSON.parse(xhttp.responseText);
//Your success: function here...
}else{
//Your error: function here...
}
};
xhttp.open("POST","/Services/Service.asmx/GetResults1",true);
xhttp.send(/**Your JSON Data**/);
Related
I'm using this exact same function for a different xml and it works perfectly. This function was actually working perfectly yesterday now I wake up today and its giving me a 422 error.
useEffect(()=>{
$.ajax({
url: 'https://api.rss2json.com/v1/api.json',
method: 'GET',
dataType: 'json',
data: {
rss_url: 'https://basketball.realgm.com/rss/wiretap/0/0.xml',
}
}).done(function (response) {
if(response.status !== 'ok'){ throw response.message; }
let a = response.items
let b = a.filter((el, i) => {
return !el.title.toLowerCase().includes('realgm')
})
setNewNews(b)
});
},[])
I have the code below which is in a Vue script.
user_id = 100; //sample data
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: function (user) {
user_id = user.user_id;
console.log(user_id); //returns 1
},
error: function (result) {
}
});
console.log(user_id); //returns 100 not 1
I want to be able to store the value that is resulted from the ajax request which is 1. However, when I console.log at the end of the script it returns 100 not 1. I think that I need to use a promise/callback to solve this but I am not sure how/what I need to do. Can someone help me?
Define your method and return as a promise.
function getUsers() {
return new Promise((resolve, reject) => {
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: function (data) {
resolve(data);
},
error: function (error) {
reject(error);
}
});
});
}
You would call the method as below.
getUsers().then((data) => {
console.log(data); /* you will get the new data returned from ajax.*/
}).catch((error) => {
console.log(error);
});
This is how you can promisify callbacks in general:
let doXWithCallback = callback => {
// do x...
callback();
};
let doXPromisified = () => new Promise(doXWithCallback);
doXWithCallback(() => console.log('do x with callback'));
doXPromisified().then(() => console.log('do x promisified'));
For your example specifically:
let doRequest = () =>
new Promise((resolve, reject) =>
$.ajax({
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: "GET",
url: '/user',
success: user => resolve(user.user_id),
error: reject(),
}));
doRequest.then(userId => console.log('userId is', userId));
After a successful login, the returned value is always false. I'm using the default Authentication system that's provided by Microsoft.Identity ("Individual User Accounts" option) with no modifications. Any thoughts?
[HttpGet]
[Route("get-userId")]
public bool CurrentUserId()
{
return User.Identity.IsAuthenticated;
}
Client-side codes:
Login.html:
$(document).ready(function () {
$('#btnLogin').click(function () {
$.ajax({
url: '/token',
method: 'POST',
contentType: 'application/json',
data: {
username: $('#txtUsername').val(),
password: $('#txtPassword').val(),
grant_type: 'password'
},
success: function (response) {
sessionStorage.setItem("accessToken", response.access_token);
window.location.href = "Momo.html";
},
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
});
Momo.html:
$(document).ready(function () {
if (sessionStorage.getItem('accessToken') == null) {
window.location.href = "Login.html";
}
$.ajax({
url: '/api/Account/get-userId',
method: 'GET',
success: function (response) {
console.log(response);
}
});
console.log(response) returns false.
You need to send the token to the server with each request. Add the following to your Ajax call:
headers: { "Authorization": 'Bearer ' + token }
You can rewrite your code like this:
$(document).ready(function () {
var token = sessionStorage.getItem('accessToken');
if (token == null) {
window.location.href = "Login.html";
}
$.ajax({
url: '/api/Account/get-userId',
method: 'GET',
headers: { "Authorization": 'Bearer ' + token },
success: function (response) {
console.log(response);
}
});
I am trying to pass json string from angularjs to my websrvice and used below code.Can someone please let me where i went wrong with the below code?
Controller method:
[httpget]
public string BulkData(JObject jObjectData)
{
var x = jObjectData;
return (jObjectData != null ) ? “SUCCESS”: “FAIL”;
}
Javasctiprt method :
function Get(url, data) {
var getReq = {
method: "GET",
url: url,
dataType: 'json',
data: JSON.stringify(data),
headers: { "Content-Type": "application/json;charset=UTF-8" }
};
return $http(getReq).then(function (response) {
$log.debug('**response from EXECUTE:', response);
return response;
}, function (error) {
$log.error('**error from EXECUTE', error);
return error;
});
}
You need [HttpPost] method, and make post request
Controller method:
[HttpPost]
public string BulkData(JObject jObjectData)
{
var x = jObjectData;
return (jObjectData != null ) ? “SUCCESS”: “FAIL”;
}
Javasctiprt method :
function Get(url, data) {
var getReq = {
method: "POST",
url: url,
dataType: 'json',
data: JSON.stringify(data),
headers: { "Content-Type": "application/json;charset=UTF-8" }
};
return $http(getReq).then(function (response) {
$log.debug('**response from EXECUTE:', response);
return response;
}, function (error) {
$log.error('**error from EXECUTE', error);
return error;
});
}
Apologies if worded awkwardly, but I have to make an rest API call using jQuery. I've already made the call using angularJS before, but for this case I can't use that. I tried translating it to jQuery but I'm not getting the same results. Is there anything I'm doing wrong or am I missing information? I'm fairly new to jQuery so I feel as if I'm missing something crucial or misunderstood something.
Working code with angularJS:
var req = {
method: 'POST',
url: 'https://fakeurl.com/rest/v1/portal/user/' + $scope.email.value,
headers:{
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
}
};
restCall($http, req).then(function (res) {
// check for error even though 200 response
if (res.error) {
console.error("Error reported...");
} else {
` //enter success code here
}
});
var restCall = function(http, req) {
var _url = getBaseUrl() + req.url;
req.url = _url;
return new Promise(function(fulfill, reject) {
try {
http(req).then(function (res) {
// check for error even though 200 response
if (res.data.error) {
if (res.data.error === '601') {
console.error('Token is invalid or has expired');
} else {
console.error("Error from end point: " + res.data.error);
}
}
fulfill(res.data);
}, function(err) {
console.error('Error calling rest endpoint',err);
reject();
});
} catch (ex) {
console.error('Exception calling rest endpoint',ex);
reject(ex);
}
});
};
My failing jQuery code:
var processCreate = function (email) {
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: 'POST',
headers: {
'Content-Type': 'application/json',
'Header_1': 'Yes',
'x-access-token': 'glsFromWebsite' //$scope.authInfo.token
},
success: function (res, a, b) {
if (res === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function () {
console.error("Error...");
}
});
}
Try making an ajax call like this
var processCreate = function (email) {
var authHeaders = {};
authHeaders.Authorization = 'Bearer ' + 'glsFromWebsite';
$.ajax({
url: 'https://fakeurl.com/rest/v1/portal/user/' + email.value,
type: "POST",
cache: false,
dataType : "json",
contentType: "application/json; charset=utf-8",
headers: authHeaders,
success: function (data) {
//console.log(data);
if (data === 'NOT FOUND') {
//code that runs when this case is true
} else {
//code that runs when this case is false
}
},
error: function (xhr) {
console.log(xhr);
}
});
}