how to fix 'fetch' is undefined in ie11? - javascript

I am coming to an issue where my code below, says that 'fetch' is undefined in internet explorer 11. I am using the latest jquery which is jquery-3.3.1.min.js and I even tried $.ajax instead of fetch but that did not work. Can anyone help me solve this issue, with my code below. That it can even work in ie11. thank you very much!
when I do $_ajax instead fetch I get an console error saying res.text is not a function TypeError: res.text is not a function
Here is my code:
"use strict";
$(function () {
var myData = [];
$.get("#{request.contextPath}/JobSearchItem.xhtml", function (data) {
$("#searchTextField").autocomplete({
minLength: 2,
source: myData,
select: function select(event, ui) {
event.preventDefault();
var url = '#{request.contextPath}/index.xhtml';
var searchValue = ui.item.value;
var data = new FormData();
data.append('searchValue', searchValue);
fetch(url, {
body: data,
method: "post"
}).then(function (res) {
return res.text();
}).then(function (text) {
$('#results').append($(text).find('#textTable'));
$('#results').append($(text).find('table'));
$('#results').append($(text).find('#bestTable'));
$("#clearone").show();
});
},
response: function response(event, ui) {
if (!ui.content.length) {
var message = { value: "", label: "NO SEARCH RESULT FOUND" };
ui.content.push(message);
}
}
});
$.each(data, function (k, v) {
myData.push({
id: v.id,
label: v.label,
value: v.id
});
});
});
$("#sJobClass").change(function () {
var jobClassCd = $(this).val();
if (jobClassCd !== 0) {
var url = '#{request.contextPath}/index.xhtml';
var searchValue = $('#sJobClass').val();
var data = new FormData();
data.append('searchValue', searchValue);
fetch(url, {
body: data,
method: "post"
}).then(function (res) {
return res.text();
}).then(function (text) {
$('#results').append($(text).find('#textTable'));
$('#results').append($(text).find('table'));
$('#results').append($(text).find('#bestTable'));
$("#clearone").show();
});
};
});
});

Do this-
npm install --save isomorphic-fetch es6-promise
import it in your code and use it.

Related

Service method not getting fired using .then

Below is my AngularJs code where I am trying to call TalentPoolService.search() after succussfull ProcessCriteria call, however for some reason it not hitting the TalentPool.Service. What am I doing wrong here?
$scope.Search = function (item, SolrLabel) {
if (item != null) {
console.log('Item: ' + item.Key);
console.log('SolrLabel: ' + SolrLabel);
console.log($localStorage.message);
var pvarrData = new Array();
pvarrData[0] = JSON.stringify($localStorage.message);
pvarrData[1] = item.Key;
pvarrData[2] = SolrLabel;
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
console.log('ProcessCriteria Success fired');
$localStorage.message = response.data;
console.log(response.data);
return response.data;
},
function (response) {
// failed
console.log('facet post error occured!');
}).then(
function () {
TalentPoolService.search().then(function successCallback(response1) {
$scope.talentpoolist = response1.data.model;
$localStorage.message = response1.data.baseCriteria;
console.log('TalentPoolService.search successCallback fired');
setTimeout(function () {
LetterAvatar.transform();
}, 20);
}, function errorCallback(response1) {
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!' + response;
})
}
);
}
}
You must return data for chaining to work.
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
console.log('ProcessCriteria Success fired');
$localStorage.message = response.data;
console.log(response.data);
return response.data; // **return here**
},
function(response) {
// failed
console.log('facet post error occured!');
}).then(
function() {
TalentPoolService.search().then(function successCallback(response1) {
$scope.talentpoolist = response1.data.model;
$localStorage.message = response1.data.baseCriteria;
setTimeout(function() {
LetterAvatar.transform();
}, 20);
}, function errorCallback(response1) {
$scope.errors = [];
$scope.message = 'Unexpected Error while saving data!!' + response;
})
}
);
Why because, the next then which you are using expects some data to work on. So, if you don't return it can't. So, must return data.

Binding a service response in Angular JS

I am trying to send the http response as a JSON body to an error handler if an error occurs. I am not really sure how to do this as I am a little inexperienced in this area. Here is the relevant code that I have currently:
Controller:
for (var prop in $scope.applicants) {
var applicant = $scope.applicants[prop];
$scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant));
}
$scope.sendATSError = function (applicant, error) {
return AtsintegrationsService.applicantErrorHandling(applicant.dataset.atsApplicantID);
};
$scope.sendApplicantsToSR = function(applicant) {
return AtsintegrationsService.sendApplicantsToSR(applicant);
};
Service:
srvc.sendApplicantsToSR = function (applicant) {
var applicantURL = {snip};
return $http({
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'POST',
url: applicantURL,
data: applicant
});
};
srvc.applicantErrorHandling = function (applicantID, error) {
var url = srvc.url + {snip};
return $http({
method: 'POST',
url: url,
data: { "error_message": error }
});
};
So, ideally, I would like to pass the result of $scope.sendApplicantsToSR to $scope.sendATSError only when an error occurs.
Inside your controller
YourService.getdatafromservice().then(function(SDetails) {
//response from service
console.log(SDetails);
});
Inside your service
return {
getData: getData
};
function getData() {
var req = $http.post('get_school_data.php', {
id: 'id_value',
});
return req.then(handleSuccess, handleError);
function handleSuccess(response) {
response_data = response.data;
return response_data;
}
function handleError(response) {
console.log("Request Err: ");
}
}

Sinon timeouts on AJAX call

Using Mocha Chai and Sinon, I have a test to get back a specific record from a revealing module pattern. The test fails with a timeout. How should I test a method to assign variables from a AJAX request?
Test.js
(function () {
'use strict';
describe('Employee Module', function() {
var server,
employeeJSON = {
"employeeTemplate" : [
{
"userId": 1
}
]
};
before(function () {
server = sinon.fakeServer.create();
server.respondWith(
"GET",
"/employees.json",
[200, { "Content-Type": "application/json" }, JSON.stringify(employeeJSON)]
);
});
after(function () {
server.restore();
});
it('should get Employee by ID', function(done) {
var employee = new Employee(),
employeeData;
employee.getData(1).done( function (data) {
employeeData = data.employeeTemplate[0];
assert.equal(employeeData.userId, 1, 'Employee ID equals 1');
done();
});
});
});
})();
Employee.js
var Employee = function() {
var EmployeeInfo = {};
var loadUserinfo = function(userid) {
return $.ajax({
type: 'GET',
data:{userid: userid},
url: '/employees.json',
dataType: 'json',
async: true,
success: function(data) {
return data;
}
});
};
var getData = function (userid) {
return loadUserinfo(userid).done();
};
return {
getData: getData
};
};
You need to tell FakeServer when to respond. See the FakeServer API docs for reference.
For example:
it('should get Employee by ID', function(done) {
var employee = new Employee(),
employeeData;
employee.getData(1).done( function (data) {
employeeData = data.employeeTemplate[0];
assert.equal(employeeData.userId, 1, 'Employee ID equals 1');
done();
});
server.respond(); // Please respond mr. sinon so my test may continue
});

Angularjs - Abort/cancel running $http calls

I've got a call using Resource in angularjs but i get some problems because i can't abort every calls it does. This kind of structure i use for an autocomplete.. is it possible convert from resource call to http? This is the code
var Resource = $resource(URL, {},{ getAutocompleteResults: { method: "GET", params: {text: ""} }});
var locked = false;
function getMoreData() {
if(locked)
return;
locked = true;
Resource.autoCompleteResults()
.$promise.then(function(data) {
$scope.autocompleteViewResults = data;
locked = false;
});
}
This is what i've tried so far with no success.
$scope.autocompleteViewResults = function () {
$http
.get(URL, {
params: {
text = ""
}
})
.success(function (data) {
$scope.autocompleteViewResults = data;
});
};
Or if someone knows an alternative method..
The $scope.autocompleteViewResults variable is being assigned 2 times.
Try this:
$scope.autocompleteViewResults = {};
$scope.getResults = function(valueAsTyped) {
$http
.get(URL, {
params: {
text: valueAsTyped
}
})
.success(function (data) {
$scope.autocompleteViewResults = data;
});
};
Update
If you need to cancel old requests.
var promiseCanceller = $q.defer();
$scope.autocompleteViewResults = {};
$scope.getResults = function(valueAsTyped) {
promiseCanceller.resolve('request cancelled'); // cancel currently running request
$http
.get(URL, {
params: {
text: valueAsTyped
},
timeout: promiseCanceller.promise // pass promiseCanceller as the timeout
})
.success(function (data) {
$scope.autocompleteViewResults = data;
});
};

Create GitHub repo from node.js

I have this function in my node project, that should create a new GitHub repository for a specific user:
exports.create_repo = function (repo) {
var options = {
host: "api.github.com",
path: "/user/repos?access_token=" + repo.accessToken,
method: "POST",
json: { name: repo.name },
headers: { "User-Agent": "github-app" }
};
var request = https.request(options, function(response){
var body = '';
response.on("data", function(chunk){ body+=chunk.toString("utf8"); });
response.on("end", function(){
var json = JSON.parse(body);
console.log(json);
});
});
request.end();
}
Every time I use it, the response is:
{ message: 'Not Found',
documentation_url: 'https://developer.github.com/v3' }
What do I do wrong ?

Categories

Resources