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;
});
}
Related
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 using cryptojs to encrypt and decrypt a file. I also have a web service to upload the encrypted files to a server. I can upload and save the ecnrypted object as a file on the server, but when I decrypt it, the file does not open correctly. My concern is if I am saving the ecnrypted object correctly or not.
Tutorial that I followed initially: http://tutorialzine.com/2013/11/javascript-file-encrypter/
encryt method:
function encrypt() {
var folderPath = "C:\\User\\test\\javascript-file-encrypter\\";
selectedFiles = document.getElementById("MainContent_file1");
var sfile = selectedFiles.files[0];
var read = new FileReader();
read.onload = function (e) {
var encrypted = CryptoJS.AES.encrypt(read.result, '123456');
var ct2 = encrypted.toString();
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
},
data: { 'folderPath': folderPath, 'uploadData': ct2, 'fileName': sfile.name + '.encrypted' },
success: function (response) {
console.log(response);
debugger;
},
error: function (xhr, textStatus, error) {
debugger;
console.log(xhr.statusText);
}
});
}
read.readAsDataURL(sfile);
}
decrypt method:
function decrypt() {
var sfiles = document.getElementById("MainContent_file1");
var sfile = sfiles.files[0];
var freader = new FileReader();
freader.onload = function (e) {
var decrypted = CryptoJS.AES.decrypt(freader.result, '123456');
var dct = decrypted.toString(CryptoJS.enc.Latin1);
//var dct2 = decrypted.toString();
//console.log(dct);
//console.log(dct2);
debugger;
$.ajax({
async: 'true',
url: "http://localhost:51936/WebService1.asmx/FileUpload",
method: "POST",
processData: 'false',
headers: {
'content-type': "application/x-www-form-urlencoded",
'cache-control': "no-cache"
},
data: { 'folderPath': folderPath, 'uploadData': dct, 'fileName': sfile.name.replace('.encrypted', '') },
success: function (response) {
console.log(response);
debugger;
},
error: function (xhr, textStatus, error) {
debugger;
console.log(xhr.statusText);
}
});
};
freader.readAsText(sfile);
}
webservice method:
[WebMethod]
public bool FileUpload(string folderPath, string uploadData, string fileName)
{
bool returnValue = false;
try
{
File.WriteAllText(folderPath + fileName, uploadData);
returnValue = true;
}
catch (Exception ex)
{
returnValue = false;
}
return returnValue;
}
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);
}
});
}
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: ");
}
}