Javascript await is only valid in async functions - javascript

I have this function to delete items once a popup returns true:
function deleteItems(selectedItems){
if (selectedItems.length > 0) {
$("#confirm-popup-modal").modal("show");
$("#confirm-popup-modal").one('hidden.bs.modal', function (event) {
if ($("#confirm-modal").val() == "true") {
var form_data = selectedItems;
$.ajax({
url: "#Url.Action("Delete", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
if (result.Result == true) {
var deleteId = result.Output;
await CompletedJobsAccess(deleteId);
table.draw();
}
},
error: function (error) {
console.log(error);
}
});
}
});
}
}
Inside the Ajax success is another function called CompletedJobsAccess that will keep looping every 3 seconds to check if a job deletion has been completed:
function CompletedJobsAccess(DeleteId){
return new Promise((resolve,reject)=>{
var loopInterval = setInterval(function() {
$.ajax({
url: "#Url.Action("Verify", "CompletedJobsAccess", new {area="Base" })",
method: "POST",
data: JSON.stringify(DeleteId),
contentType: "application/json",
success: function(verifyResult) {
if (verifyResult.IS_COMPLETED == true && verifyResult.IS_PROCESSING == false) {
if (verifyResult.IS_SUCCESSFUL == true) {
console.log(verifyResult.OUTPUT);
$.each($.parseJSON(verifyResult.OUTPUT), function(index, value) {
if (value.Result == true) {
toastr.success(value.Message);
}else{
toastr.error(value.Message);
}
});
clearInterval(loopInterval);
} else {
toastr.error(verifyResult.ERROR_MESSAGE);
}
}
},
error: function(innerError) {
console.log(innerError);
}
});
}, 3000);
});
}
However, when I load the page, and call deleteItems(selected);, this is the error I get:
Uncaught SyntaxError: await is only valid in async functions and the
top level bodies of modules
I tried searching around but I can't find if it can work within an ajax success function.
EDIT:
Added async to the ajax success function but the table draw function doesn't run.
function deleteItems(selectedItems){
if (selectedItems.length > 0) {
$("#confirm-popup-modal").modal("show");
$("#confirm-popup-modal").one('hidden.bs.modal', function (event) {
if ($("#confirm-modal").val() == "true") {
var form_data = selectedItems;
$.ajax({
url: "#Url.Action("Delete", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: async function (result) {
if (result.Result == true) {
var deleteId = result.Output;
console.log("table before");
await CompletedJobsAccess(deleteId);
console.log("table draw");
table.draw();
}
table.draw();
},
error: function (error) {
console.log(error);
}
});
}
});
}
}
EDIT 2: Updated CompletedJobsAccess to resolve promises:
function CompletedJobsAccess(DeleteId){
return new Promise((resolve,reject)=>{
var loopInterval = setInterval(function() {
$.ajax({
url: "#Url.Action("Verify", "CompletedJobsAccess", new {area="Base" })",
method: "POST",
data: JSON.stringify(DeleteId),
contentType: "application/json",
success: function(verifyResult) {
if (verifyResult.IS_COMPLETED == true && verifyResult.IS_PROCESSING == false) {
if (verifyResult.IS_SUCCESSFUL == true) {
console.log(verifyResult.OUTPUT);
$.each($.parseJSON(verifyResult.OUTPUT), function(index, value) {
if (value.Result == true) {
toastr.success(value.Message);
}else{
toastr.error(value.Message);
}
});
clearInterval(loopInterval);
return Promise.resolve();
} else {
toastr.error(verifyResult.ERROR_MESSAGE);
return Promise.resolve();
}
}
},
error: function(innerError) {
console.log(innerError);
}
});
}, 3000);
});
}

Just make the success function async
$.ajax({
url: "https://jsonplaceholder.typicode.com/users/3",
method: "GET",
success: async function(data) {
console.log("first - now wait a second ...");
await new Promise((res) => setTimeout(res, 1000));
console.log("second, data:",data);
},
error: function(innerError) {
console.log(innerError);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Working JSFiddle (can't work on this site because of CORS)

In CompletedJobsAccess(DeleteId) you return a promise. But the way you set it up it will never execute the resolve function. So your await will wait forever ...
You could place the line
resolve();
right after
clearInterval(loopInterval);
in your CompletedJobsAccess function to make it work.
Do not return yet another Promise.resolve() like you did in your edited code.
A resolve function for a promise is never returned but executed.

Try Adding async before all the function keyword like async function deleteItems(selectedItems){ and also $("#confirm-popup-modal").one('hidden.bs.modal', async function (event) { and it should do the job.

You're using await in functions that don't use the async keyword. await isn't available in regular functions. To solve this, you can change all the functions using await to async function to make it into an asynchronous function.
And if you don't want want to go through every function to make it asynchronous, you can just put the entire code inside an asynchronous IIFE

Related

Return promise after multiple calls with the same instance of an Ajax method

I'm using Ajax with JQuery to fetch data from an API that only returns 100 records at a time. If my query gives a result with more than 100 records, the API will include an "offset" parameter in the response. I have to use this offset parameter in a new API call to get the next 100 records. The API will include a new offset parameter if there's even more records to fetch. And so on until all records are fetched.
As you can see I've solved this by having the function call itself until the "offset" parameter is no longer included. I.e. until there are no more records to fetch.
Because of this behavior of the API, I cannot use the Ajax method's own .done-function, since it would be executed multiple times (for each iteration of the Ajax method).
How can adjust the function below to return a promise when all Ajax calls have been done?
function getContracts(offset) {
var data = {};
if (offset !== undefined) {
data["offset"] = offset;
}
$.ajax({
url: url,
headers: {
Authorization: apiKey
},
data: data,
success: function(result){
$.each(result.records, function() {
contracts.push(this);
});
if (result.hasOwnProperty("offset")) {
getContracts(result.offset);
}
}
});
}
Real and full code as requested:
var objectContracts = [];
var landContracts = [];
var locations = [];
var customers = [];
var landOwners = [];
var frameworkAgreements = [];
function getObjectContracts(offset) {
return new Promise((resolve, reject) => {
var data = {};
data["view"] = 'Alla Objektsavtal';
if (offset !== undefined) {
data["offset"] = offset;
}
$.ajax({
url: url + "Objektsavtal",
headers: {
Authorization: apiKey
},
data: data,
success: function(result){
$.each(result.records, function() {
objectContracts.push(this);
});
if (result.hasOwnProperty("offset")) {
getObjectContracts(result.offset);
} else {
resolve();
}
}
});
});
}
function getLandContracts(offset) {
return new Promise((resolve, reject) => {
var data = {};
data["view"] = 'Alla Markavtal';
if (offset !== undefined) {
data["offset"] = offset;
}
$.ajax({
url: url + "Markavtal",
headers: {
Authorization: apiKey
},
data: data,
success: function(result){
$.each(result.records, function() {
landContracts.push(this);
});
if (result.hasOwnProperty("offset")) {
getLandContracts(result.offset);
} else {
resolve();
}
}
});
});
}
function getLocations(offset) {
return new Promise((resolve, reject) => {
var data = {};
data["view"] = 'Alla Uppställningsplatser';
if (offset !== undefined) {
data["offset"] = offset;
}
$.ajax({
url: url + "Uppställningsplatser",
headers: {
Authorization: apiKey
},
data: data,
success: function(result){
$.each(result.records, function() {
locations.push(this);
});
if (result.hasOwnProperty("offset")) {
getLocations(result.offset);
} else {
resolve();
}
}
});
});
}
function getCustomers(offset) {
return new Promise((resolve, reject) => {
var data = {};
data["view"] = 'Alla Kunder';
if (offset !== undefined) {
data["offset"] = offset;
}
$.ajax({
url: url + "Kunder",
headers: {
Authorization: apiKey
},
data: data,
success: function(result){
$.each(result.records, function() {
customers.push(this);
});
if (result.hasOwnProperty("offset")) {
getCustomers(result.offset);
} else {
resolve();
}
}
});
});
}
function getLandOwners(offset) {
return new Promise((resolve, reject) => {
var data = {};
data["view"] = 'Alla Markägare';
if (offset !== undefined) {
data["offset"] = offset;
}
$.ajax({
url: url + "Markägare",
headers: {
Authorization: apiKey
},
data: data,
success: function(result){
$.each(result.records, function() {
landOwners.push(this);
});
if (result.hasOwnProperty("offset")) {
getLandOwners(result.offset);
} else {
resolve();
}
}
});
});
}
function getFrameworkAgreements(offset) {
return new Promise((resolve, reject) => {
var data = {};
data["view"] = 'Alla Ramavtal';
if (offset !== undefined) {
data["offset"] = offset;
}
$.ajax({
url: url + "Ramavtal",
headers: {
Authorization: apiKey
},
data: data,
success: function(result){
$.each(result.records, function() {
frameworkAgreements.push(this);
});
if (result.hasOwnProperty("offset")) {
getFrameworkAgreements(result.offset);
} else {
resolve();
}
}
});
});
}
If I've understood your question perfectly, you want to resolve a Promise if there is no offset in the response from your Ajax request.
I haven't tested this code but you can do something like this:
function getContracts(offset) {
return new Promise((resolve, reject) => {
var data = {};
if (offset !== undefined) {
data['offset'] = offset;
}
$.ajax({
url: url,
headers: {
Authorization: apiKey,
},
data: data,
success: function(result) {
$.each(result.records, function() {
contracts.push(this);
});
if (result.hasOwnProperty('offset')) {
getContracts(result.offset);
} else {
// I guess this is what you want
// If there is no offset property => resolve the promise
resolve('Your result goes here');
}
},
});
});
}
See the else block.
You can pass your final result (whatever you want to achieve after the completion of your task) inside the resolve. For example, you can create an array and append your result to that and at the end, you can pass that array inside resolve.
You can resolve this using .then() or async/await
async () => {
const result = await getContracts(offset);
};
or
getContracts(offset).then(result => { console.log(result) });
If you see some Unhandled Promise Rejection warning/error, you can always use try/catch block with async/await and .catch after .then.
EDIT:
First, you're not passing anything inside resolve. Whatever you pass inside the resolve will be reflected in .then(result).
Second, you have global variables and storing all your data inside them. So now you don't need to pass them inside the resolve but this is not a good approach because any function or the code outside can modify it. So I'll give you one example.
function getObjectContracts(offset) {
return new Promise((resolve, reject) => {
var data = {};
const objectContracts = [];
data['view'] = 'Alla Objektsavtal';
if (offset !== undefined) {
data['offset'] = offset;
}
$.ajax({
url: url + 'Objektsavtal',
headers: {
Authorization: apiKey,
},
data: data,
success: function(result) {
$.each(result.records, function() {
objectContracts.push(this);
});
if (result.hasOwnProperty('offset')) {
getObjectContracts(result.offset);
} else {
resolve(objectContracts);
}
},
});
});
}
Now, the other question is, how to resolve all these promises at once.
const finalFunction = async () => {
const [result1, result2, result3] = await Promise.all([
getObjectContracts(offset1),
getLandContracts(offset2),
getLocations(offset3),
]);
console.log(result1, result2, result3);
};
finalFunction();

Using jQuery when to defer ajax processing

I have a list of 15+ ajax requests that need to be called in a specific order. I need each ajax call to wait until the previous function finishes before making the next call. This issue arises because my ajax call, has a direct callback that is also an ajax call.
createCheckIn() {
this.selectedList = [...] // long list of objects
count = 0
for ( i=0; i < this.selectedList.length; i++ ) {
$.ajax({
method: "POST",
url: url,
data: {
check_in: {
client_id: this.selectClient.id,
program_id: this.program_id
}
},
success: function(res) {
that.createWeighIn(count, res.id)
count = count + 1
},
error: function(err) {
console.log(err)
}
})
}
},
createWeighIn(index, check_in_id) {
let data = {}
let that = this
data.weigh_in = this.selectedList[index]
$.ajax({
method: "POST",
url: url,
data: data,
success: function(res) {
console.log(res)
},
error: function(err) {
console.log(err)
}
})
}
the correct data is generated but I believe the ordering is off because eventually there is a call to createCheckIn() that begins before the previous entry has completed.
Is there a way to chain these functions such that createCheckIn() and createWeighIn() are called (and complete) before selectedList iterates.
your for loop in createCheckIn() will not stop to wait on your ajax return. you can do something like:
function createCheckIn(oldI, oldCount){
var count = 0;
var currentI = 0;
if(oldCount != null){
count = oldCount;
}
if(oldI != null){
currentI = oldI;
}
if(currentI < this.selectedList.length){
$.ajax({
method: "POST",
url: url,
data: {
check_in: {
client_id: this.selectClient.id,
program_id: this.program_id
}
},
success: function(res) {
that.createWeighIn(count, res.id)
createCheckIn(currentI + 1, count + 1);
},
error: function(err) {
console.log(err)
}
}); //ajax
} // if
}
seems likely that you can eliminate one of those counters too, the i or the count
Seems like this is missing some potentially really important details about what you need to do leading up to this (ie. this.selectedItems generation) and what happens after (what if one call checkin fails, what if a checkin succeeds but its corresponding weighIn fails, etc..). That said...
It seems you are not actually using the counter for anything other than to reference data you already have, so why not just pass that in directly like:
createWeighIn(weighInData, check_in_id) {
let data = {};
let that = this;
data.weigh_in = weighInData;
// ... your other code
}
I would make createCheckIn only handle doing the ajax request and making a single "reservation" in your system. Then i would make a new method called checkIn that uses the two previous method to process all of selected items:
checkIn() {
let self = this;
let promises = [];
let this.selectedList = [...];
for (let = 0; i < this.selectedList.length; i++) {
// always create the deferred outside the call
let def = $.Deferred();
promises.push(def.promise());
this.createCheckIn().done(function (res) {
self.createWeighIn(self.selectedList[i], res.id))
.done(function () {
// resolve
def.resolve.apply(def, Array.prototype.slice.call(arguments);
})
.fail(function () {
def.reject.apply(def, Array.prototype.slice.call(arguments);
});
}).fail(function () {
// if checkin fails, always reject because we know weighIn wont be called
def.reject.apply(def, Array.prototype.slice.call(arguments);
});
};
// this will resolve/fail when all promises (from createWeighIn) resolve/fail
return $.when.apply(null, promises);
}
so putting it all together:
{
createCheckIn() {
let request = $.ajax({
method: "POST",
url: url,
data: {
check_in: {
client_id: this.selectClient.id,
program_id: this.program_id
}
}
})
.fail(function(err) {
console.log(err)
});
};
return request;
},
createWeighIn(data, check_in_id) {
let params = {};
params.weigh_in = data;
let request = $.ajax({
method: "POST",
url: url,
data: params,
success: function(res) {
console.log(res)
},
error: function(err) {
console.log(err)
}
});
return request;
},
checkIn() {
let self = this;
let promises = [];
let this.selectedList = [...];
for (let = 0; i < this.selectedList.length; i++) {
// always create the deferred outside the call
let def = $.Deferred();
promises.push(def.promise());
this.createCheckIn().done(function (res) {
self.createWeighIn(self.selectedList[i], res.id))
.done(function () {
// resolve
def.resolve.apply(def, Array.prototype.slice.call(arguments);
})
.fail(function () {
def.reject.apply(def, Array.prototype.slice.call(arguments);
});
}).fail(function () {
// if checkin fails, always reject because we know weighIn wont be called
def.reject.apply(def, Array.prototype.slice.call(arguments);
});
};
// this will resolve/fail when all promises (from createWeighIn) resolve/fail
return $.when.apply(null, promises);
}
}
I ended up introducing promises, and some recursion and removing the loop altogether. I basically begin the process by calling createCheckIn() with an index of 0:
this.createCheckIn(0)
createCheckIn(index) {
this.selectedList = [...] // long list of objects
count = 0
let prom = new Promise(function(resolve, reject) {
$.ajax({
method: "POST",
url: url,
data: {
check_in: {
client_id: that.selectClient.id,
program_id: that.program_id
}
},
success: function(res) {
resolve(that.createWeighIn(index, res.id))
},
error: function(err) {
reject(console.log(err))
}
})
})
},
createWeighIn(index, check_in_id) {
let data = {}
let that = this
data.weigh_in = this.selectedList[index]
let prom = new Promise(function(resolve, reject) {
$.ajax({
method: "POST",
url: url,
data: data,
success: function(res) {
console.log(res)
if ( index == (that.selectedList.length - 1) ) {
that.complete = true
resolve(console.log("complete"))
} else {
index++
resolve(that.createCheckIn(index))
}
},
error: function(err) {
console.log(err)
}
})
})
}

Close modal in ajaxStop

I have the following code:
var menuButtonClick = {
onReady: function () {
$(document).on('click', '.menu-button', function () {
menuButtonClick.clickedButton($(this).html());
});
},
clickedButton: function (val) {
switch (val) {
case 'CheckModelBank':
modelBankHandler.get();
break;
}
}
}
var modelBankHandler = (function () {
var get = function () {
var selectedCellData = handsonTable.selectedCellData.get();
var webGrid = handsonTable.WebGrid.get();
$.ajax({
type: 'POST',
url: "http://localhost:56292/api/Data/CheckModelBank",
data: { "": selectedCellData },
success: function (response) {
if (response != null) {
serverResult = JSON.parse(response);
printModelBank(serverResult, webGrid);
}
},
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus == "error") {
modalHandler.printErrorModal();
}
}
});
}
var printModelBank = function (serverResult, webGrid) {
///
}
return {
get: get
}
})();
var fileHandler = {
onReady: function () {
var documentType = "";
$('.upload-file').click(function () {
$('[data-remodal-id=documentModal]').remodal().open();
});
$('.document-option').click(function () {
//Need to get the type of document the user is going to work with so we can parse the document correctly to the webgrid
documentType = $(this).html();
$('#fileUpload').click();
});
$('#fileUpload').change(function () {
fileHandler.upload(documentType);
});
$('.save-to-excell').click(fileHandler.saveDocument);
},
upload: function (documentType) {
var formData = new FormData();
var totalFiles = document.getElementById("fileUpload").files.length;
for (var i = 0; i < totalFiles; i++) {
var file = document.getElementById("fileUpload").files[i];
formData.append("fileUpload", file);
}
$.ajax({
type: 'post',
url: 'http://localhost:59973/Home/Upload',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (response) {
jsonData = JSON.parse(response.data);
if (jsonData != null) {
if (documentType == "Infolog") {
fileHandler.printDocument(jsonData); //This is used for pickinglist and infolog
} else {
var webGrid = handsonTable.WebGrid.get();
webGrid.loadData(jsonData);
}
}
},
error: function (error) {
if (textStatus == "error") {
modalHandler.printErrorModal();
}
}
});
},
}
$(document).ready(function () {
handsonTable.init();
menuButtonClick.onReady();
fileHandler.onReady();
buttonClicks.onReady();
}).ajaxStart(function () {
$('[data-remodal-id=modalAjax]').remodal().open();
}).ajaxStop(function () {
$('[data-remodal-id=modalAjax]').remodal().close();
});
When I upload a file (fileHandler), the modal shows during ajaxStart and closes on ajaxStop. However, If I click on a button in my menu (menuButtonclick) which trigger my modelBankHandler function, the modal shows during ajaxstart, but does not close on ajaxStop.
Why? All the data are retrieved as expected in my modelBankHandler, so why does not the modal closes?
If you have pressed F12 in the browser and looked at the console you would probably have found an error there. This video might help you to figure out basic problems yourelf.
I think printModelBank might throw an error, if the success or error functions throw an error then jQuery crashes and does not execute the ajaxStop handler:
$(document)
.ajaxStart(function () {
console.log("open model");
}).ajaxStop(function () {
console.log("close model");
});
$.ajax({
type: 'GET',
url: "/none",
data: {},
success: function (response) {
console.log("success");
throw new Error("now stop won't execute");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error");
throw new Error("now stop won't execute");
}
});
You could solve this by having success and error as promise handlers, errors in promise handlers should not crash jQuery (but it does):
$(document)
.ajaxStart(function () {
console.log("open model");
}).ajaxStop(function () {
console.log("close model");
});
$.ajax({
type: 'GET',
url: "/none",
data: {}
})
.then(
response => {
console.log("success");
throw new Error("now stop won't execute");
},
(jqXHR, textStatus, errorThrown) => {
console.log("error");
throw new Error("now stop won't execute");
}
);
You could try native promises (jQuery still doesn't get promises right) and have it not crash on error in handler:
$(document)
.ajaxStart(function () {
console.log("open model");
}).ajaxStop(function () {
console.log("close model");
});
Promise.resolve()
.then(_ =>
$.ajax({
type: 'GET',
url: "/none",
data: {}
})
)
.then(
response => {
console.log("success");
throw new Error("now stop WILL execute");
},
(jqXHR, textStatus, errorThrown) => {
console.log("error");
throw new Error("now stop WILL execute");
}
);
IE does not support native promises so you will need a polyfill or try babel with ES2016

How can I wait until both ajax requests done?

Here is a simplified of my code:
var res = array();
$.ajax({
url: 'test1.php',
async: true,
success: function (data) {
res[1] = data.result;
}
});
$.ajax({
url: 'test2.php',
async: true,
success: function (data) {
res[2] = data.result;
}
});
if ( /* both ajax request are done */ ) {
// do stuff
} else {
// wait
}
As you can see I've used async: true to run those ajax requests at the same time (in parallel). Now I need to wait until both requests done. How can I determine an ajax request is done? If not wait until it get done?
You can use promises:
Promise.all([
$.ajax({ url: 'test1.php' }),
$.ajax({ url: 'test2.php' })
])
.then(([res1, res2]) => {
// Both requests resolved
})
.catch(error => {
// Something went wrong
});
You can use callback function as well.
var res = [];
function addResults(data) {
res.push(data);
console.log('Request # '+res.length);
if ( res.length >= 2 ) {
// do stuff
console.log('both request has done.');
} else {
// wait
}
}
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
success: function (data) {
addResults(data);
}
});
$.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
success: function (data) {
addResults(data);
}
});
Use Promise.all function. It will be resolved if all of the promises is resolved and pass the data as array to the then function, else it will be rejected with the first promise failure value
Promise.all([
$.ajax({ url: 'test1.php'}),
$.ajax({ url: 'test2.php'})
])
.then(results => {
// results is an array which contains each promise's resolved value in the call
})
.catch(error => {
// The value of the first rejected promise
});
this official document could help you.
http://api.jquery.com/ajaxStop/
example:
var res = [];
$.ajax({
url: 'test1.php',
async: true,
success: function (data) {
res.push('Ajax one is complete');
}
});
$.ajax({
url: 'test2.php',
async: true,
success: function (data) {
res.push('Ajax two is complete');
}
});
var resALL = function(){
console.log(this)
}
//After the requests all complete
$(document).ajaxStop(resALL.bind(res))

Translating a rest API call from angular to jQuery

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);
}
});
}

Categories

Resources