I've checked every similar question on here, the solutions and more, but still can't find a solution that works for me.
First: I'm absolutely new to Ajax and just got a project to fix from some developer that isn't reachable anymore, so I'm at my wits end...
Basically, this is the code-snippet for the Link that is clicked, which action works perfectly fine when I debug the whole process and just "step-over" everything, but simply running it will always end it in error instead of success.
var serviceURL = "http://address";
function bestellePosition(token, artikelId, userId, menge) {
var authheader = 'Bearer ' + token;
var url = "/WarenkorbPositions/AddMengeToCart";
var type = "POST";
$.ajax({
cache: false,
type: type,
url: serviceURL + url,
beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', authheader); },
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
userId: userId,
artikelId: artikelId,
menge: menge
}),
success: function (result) {
if (result.result === true) {
alert('it worked');
} else {
alert('it didnt work');
}
},
error: function (result) {
alert(result.result);
}
});
}
Additional things I tried were adding dataType: "json", , which seemingly didn't do anything.
Adding a timeout: 10000 which also didn't seem to do anything.
Just sending the data as data: {...} instead of using JSON.stringify which didn't work at all.
EDIT:
URL-Method
private PostXnameEntities db = new PostXnameEntities();
private String conStr = #"Server=xxx\SQLEXPRESS,xxx;Initial Catalog=xxx;Persist Security Info=True;UID=xxx;Password=xxx;";
public Boolean AddMengeToCart(int userId, int artikelId, decimal menge)
{
var positionen = db.WarenkorbPosition.Include(w => w.Artikel).Include(w => w.User);
var posquery = from p in positionen where p.UserId == userId && p.ArtikelId == artikelId select p;
WarenkorbPosition pos = new WarenkorbPosition();
if (posquery.ToList().Count > 0)
{
pos = posquery.ToList().First();
if (menge == 0)
{
int rows = 0;
SqlConnection sqlConn = new SqlConnection(conStr);
string queryOrder = "DELETE FROM [PostXname].[dbo].[WarenkorbPosition] WHERE [UserId] = #UserId And [ArtikelId] = #ArtikelId";
SqlCommand cmd = new SqlCommand(queryOrder, sqlConn);
cmd.Parameters.AddWithValue("#UserId", userId);
cmd.Parameters.AddWithValue("#ArtikelId", artikelId);
try
{
sqlConn.Open();
rows = cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
sqlConn.Close();
}
else
{
decimal posMenge = pos.Menge.Value;
decimal MengeGesamt = posMenge + menge;
int rows = 0;
SqlConnection sqlConn = new SqlConnection(conStr);
string queryOrder = "UPDATE [PostXname].[dbo].[WarenkorbPosition] SET [Menge] = #Menge WHERE [UserId] = #UserId And [ArtikelId] = #ArtikelId";
SqlCommand cmd = new SqlCommand(queryOrder, sqlConn);
cmd.Parameters.AddWithValue("#UserId", userId);
cmd.Parameters.AddWithValue("#ArtikelId", artikelId);
cmd.Parameters.AddWithValue("#Menge", Convert.ToDecimal(MengeGesamt));
try
{
sqlConn.Open();
rows = cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
sqlConn.Close();
}
}
else
{
int rows = 0;
SqlConnection sqlConn = new SqlConnection(conStr);
string queryOrder = "INSERT INTO [PostXname].[dbo].[WarenkorbPosition]([UserId],[ArtikelId],[Menge])VALUES(#UserId,#ArtikelId,#Menge)";
SqlCommand cmd = new SqlCommand(queryOrder, sqlConn);
cmd.Parameters.AddWithValue("#UserId", userId);
cmd.Parameters.AddWithValue("#ArtikelId", artikelId);
cmd.Parameters.AddWithValue("#Menge", Convert.ToDecimal(menge));
try
{
sqlConn.Open();
rows = cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
sqlConn.Close();
}
return true;
}
can you check the below code and try once.
can you also check the the url method u mentioned is a GET or POST type
Please also tell what u got in result in error method (result.result)
var serviceURL = "http://address";
function bestellePosition(token, artikelId, userId, menge) {
var authheader = 'Bearer ' + token;
var url = "/WarenkorbPositions/AddMengeToCart";
var type = "POST";
$.ajax({
cache: false,
type: type,
url: serviceURL + url,
beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', authheader); },
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
userId: userId,
artikelId: artikelId,
menge: menge
}),
success: function (result) {
if (result.result === true) {
alert('it worked');
} else {
alert('it didn\'t work');
}
},
error: function (result) {
alert(result.result);
}
});
}
Related
I am trying to redirect to another server call but unfortunately browser sometimes redirect or sometime just refresh the current page.
Redirect is in getCheckOutOfHrs async function and I tried all three options
1). window.location = myurl;
2). window.location.href = myurl;
3). window.location.assing(myurl);
4). window.location.replace(myurl);
Nothing is 100% a working solution in my case. sometimes browser redirects and sometimes not.
I don't know why browser is doing this. see my tried code is below.
I am trying to use async function.
$('#btn-search-car').click(function(e) {
searchCar(e)
});
function searchCar(e) {
try {
//debugger;
e.preventDefault();
var obj = {
Branch: lStrLocNam.trim(),
PickupLocId: lIntPickupLocId,
FranchiseId: lIntFranchiseId,
SubofficeId: lIntSubofficeId,
StartDate: dtStart /*startDate*/ ,
StartTime: startTime,
EndDate: dtEnd /*endDate*/ ,
EndTime: endTime,
VehicleType: selectedVehType,
VehicleCategoryId: carCat,
IsNewSearch: true
};
saveElement('SelectedParamInSearch', obj);
let apiUrl = REACT_APP_CheckOutOfHours;
getCheckOutOfHrs(obj);
} catch (err) {
//hideProgress();
}
};
const getCheckOutOfHrs = async(obj) => {
let abortController = new AbortController();
let lattitude = 0;
let longitude = 0;
let resultPages = [];
let apiUrl = REACT_APP_CheckOutOfHours;
const settings = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(obj),
signal: abortController.signal
};
const responseDetail = await fetch(apiUrl, settings);
//abortController.abort();
if (responseDetail && !responseDetail.ok) {
resultPages = [];
} else {
resultPages = await responseDetail.json();
}
try {
let OutOfHours = resultPages; //? JSON.parse(resultPages):'';
//debugger;
debugger;
if (OutOfHours) {
saveElement('OutOfHoursParam', OutOfHours);
//OutOfHours = OutOfHours.replace('"', '').replace('"', '');
if (OutOfHours.length != 0 && OutOfHours.item2 && OutOfHours.item2.indexOf("£") > 0) {
//window.location = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
let redirectLocalUrl = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
window.location.replace(redirectLocalUrl);
// window.location.href = redirectLocalUrl;
// windowtruelocation.assign(redirectLocalUrl);
return false;
/* $.ajax({
url: "/Home/FindBranch",
data: obj,
success: function (data) {
window.location.href = "/Home/FindBranch";
},
dataType: "html",
type: "POST",
cache: false,
error: function () {
}
}); */
} else if (OutOfHours.length != 0 && OutOfHours.item2 && OutOfHours.item2.indexOf("£") < 0) {
//OutOfHours = OutOfHours.replace("\\", "'").replace("\\", "");
alert(OutOfHours.item2);
return false;
} else {
//FindBranch
//window.location = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
let redirectLocalUrl = "/Home/FindBranch/?franchiseId=" + obj.FranchiseId;
window.location.replace(redirectLocalUrl);
// window.location.href = redirectLocalUrl;
// window.location.assign(redirectLocalUrl);
return true;
/* $.ajax({
url: "/Home/FindBranch",
data: obj,
success: function (data) {
// debugger;
window.location.href = "/Home/FindBranch";
//hideProgress();
},
dataType: "html",
type: "POST",
cache: false,
error: function () {
// hideProgress();
}
}); */
}
}
} catch (error) {
debugger;
}
};
Help is appreciated.
public JsonResult SaveAttachment(string buyerCode)
{
Dictionary<int, CheckSessionData> IDictionary = CheckSessionData.GetSessionValues();
long companyId = (long)IDictionary[1].Id;
long userId = (long)IDictionary[3].Id;
var buyer = DB.Buyers.FirstOrDefault(x => x.Code == buyerCode);
string basePath = "~/Upload/BuyerAttachment/";
string path = Server.MapPath(basePath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
HttpFileCollectionBase files = Request.Files;
List<string> filePathList = new List<string>();
for (int i = 0; i > files.Count; i++)
{
HttpPostedFileBase file = files[i];
var date = DateTime.Now.ToString().Replace('/', '_');
string FilePath = Path.Combine(path, date.Replace(':', ' ') + file.FileName);
file.SaveAs(FilePath);
filePathList.Add(FilePath);
}
foreach (var item in filePathList)
{
var buyerAttachment = new Buyer_Attachment();
buyerAttachment.BuyerId = buyer.BuyerId;
buyerAttachment.DateOfEntry = DateTime.Now;
buyerAttachment.EntryBy = userId;
buyerAttachment.AttachmentURL = path;
DB.Buyer_Attachment.Add(buyerAttachment);
}
try
{
DB.SaveChanges();
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
return Json(true);
}
}
function SaveAttachment(code) {
var files = $("#CustomerAttachment").get(0).files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append("fileInput", files[i]);
}
$.ajax({
type: "POST",
url: "/BuyerSimple/SaveAttachment?buyerCode="+code,
dataType: "json",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result, status, xhr) {
filePathList = result;
$('#AttachmentPathList').val(result);
},
error: function (xhr, status, error) {
alert(status);
}
});
}
I am struggling with the Response of the Javascript fetch() method. What is my objective: a) to send multiple lines to the backend to save those to a database and b) get a guid in return for further processing.
I succeed in objective a (save to database), but the return message fails to materialise. Response.ok is true, but no message is part of the return message.
What should I do to accomplish this?
My javascript is:
function saveAll(event) {
event.preventDefault();
var newDeelnemers = new Array();
var lijst = document.querySelectorAll('#tblDeelnemers tbody tr')
lijst.forEach(function (dnmr) {
var row = dnmr;
var deelnemer = {};
var nDnmr = row.children;
//deelnemer.Id = nDnmr[0].innerHTML;
deelnemer.FamilielidFirstName = nDnmr[0].innerHTML;
deelnemer.Achternaam = nDnmr[1].innerHTML;
deelnemer.DOB = nDnmr[2].innerHTML;
deelnemer.Programma = nDnmr[3].innerHTML;
deelnemer.EetMee = nDnmr[4].firstChild.checked;
deelnemer.Dieet = nDnmr[5].innerHTML;
deelnemer.Bedrag = nDnmr[6].innerHTML;
newDeelnemers.push(deelnemer);
});
fetch("/Familiedag/Registreer", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newDeelnemers)
}).then(function (response) {
console.log('eerste keer: ' + response);
if (response.ok) {
alert('De registratie is gelukt');
//redirect("/Familiedag/RegistreerConfirm?")
}
});
}
The controller
[HttpPost]
public IActionResult Registreer([FromBody] List<FdDeelnemer> newDeelnemers)
{
if (newDeelnemers.Count == 0)
{
return null;
}
Guid registratieGuid = Guid.NewGuid();
foreach (var ndn in newDeelnemers)
{
FdDeelnemer VM = new FdDeelnemer();
VM.RegistratieGuid = registratieGuid;
VM.FamilielidFirstName = ndn.FamilielidFirstName;
VM.Achternaam = ndn.Achternaam;
VM.EetMee = ndn.EetMee;
VM.Dieet = ndn.Dieet;
VM.Programma = ndn.Programma;
VM.DOB = ndn.DOB;
VM.Bedrag = ndn.Bedrag;
VM.CreatedBy = User.Identity.Name;
VM.CreatedOn = DateTime.UtcNow;
_context.Add(VM);
}
Guid geregistreerdeDeelnemers = registratieGuid;
return Json(geregistreerdeDeelnemers);
}
add another .then that return the json
fetch("/echo/json/", {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"tes": "data"
})
}).then(function(response) {
return response.json();
}).then(function(json) {
console.log('eerste keer: ', json);
alert('De registratie is gelukt');
//redirect("/Familiedag/RegistreerConfirm?")
});
You can try to return it like that:
return Json(new { AnythingYouWant = geregistreerdeDeelnemers });
In my flow say i am using an access token for getting my data. When my access token expires i get a 401 error i am using the refresh token to get a new access token.
Note : My access token and refresh token is stored in a cookie and i am updating the same after a 401 error.
My question how do i retry the same operation which i was in the middle of?
My Code (services.js):
var refresh_token = "na";
function get_api_data(url, api_token) {
var returnData = handleApiData(url, api_token, "GET");
return returnData;
}
function post_api_data(url, api_token, post_data) {
var returnData = handleApiData(url, api_token, "PUT", post_data);
return returnData;
}
function handleApiData(url, access_token, type, post_data) {
return $.ajax({
url: url,
type: type,
data: post_data,
error: failHandler,
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + access_token);
}
})
}
function handleData(data, textStatus, jqXHR) {
return data;
}
function failHandler(jqXHR, textStatus, errorThrown) {
switch (jqXHR.status) {
case 401:
var api = get_api_token();
checkApiToken(api.refresh_token);
break;
default:
alert(errorThrown);
}
}
function checkApiToken(refresh_token) {
if (refresh_token != "na") {
$.post("/Account/Refresh/?refresh_token=" + refresh_token);
//location.reload();
}
}
My Code (notification.js):
$(function () {
var api = get_api_token();
if (api != null)
get_notification_data(api.access_token);
});
function get_notification_data(api_token) {
var notifications = get_api_data(urls.notifications.list, api_token);
if (notifications != undefined)
notifications.success(function (data) {
items = data.records;
_.each(items, function (item) {
item.Status = ko.observable(item.status);
item.onClick = function () {
if (item.Status() === 'UNREAD') {
var post_data = { id: item.id };
post_api_data(urls.notifications.list, api_token, post_data).success(function (response, textStatus) {
if (response.success)
item.Status('READ');
$(location).attr("href", item.action_link);
});
}
else {
$(location).attr("href", item.action_link);
}
}
});
var model = {
items: ko.observableArray(items),
onCancel: function (item) {
}
}
ko.applyBindings(model, $("#notificationBar")[0]);
})
}
Edit: My AccountController code that sets the new API cookie:
[HttpPost]
public ActionResult Refresh(string refresh_token)
{
string token_string = string.Empty;
try
{
token_string = OAuthHelper.getTokenViaRefreshTokenFromAPIServer(refresh_token);
if(token_string != null)
Response.Cookies[Constants.Cookies.API].Value = token_string;
}
catch (Exception ex)
{
Log.Info(string.Format("AccountController.cs -Refresh Token Error ", ex.Message));
}
return RedirectToAction("Index","Home");
}
Given the following object:
var MyObject = function(field1, field2) {
this.field1 = field1;
this.field2 = field2;
}
MyObject.prototype.setField1 = functioin(field1) {
this.field1 = field1;
}
MyObject.prototype.apply = function() {
...
this.setField1("hello");
log("field1: " + this.field1); // field1 has not been set to "hello"
}
I want to change the value of field1... but the code above doesn't seem to work. Am I missing something? Tx.
EDIT
OK, it's worth providing you with the real case. Here below is my customization of Swagger for dealing with JWT:
var TokenAuthorization = function(appId, value) {
this.appId = appId;
this.value = value;
this.type = null;
this.expirationTime = null;
};
TokenAuthorization.prototype.set = function(value, type, expirationTime) {
this.value = value;
this.type = type;
this.expirationTime = expirationTime;
};
TokenAuthorization.prototype.apply = function(obj, authorizations) {
var now = Math.round(new Date().getTime() / 1000);
var appId = this.appId;
var value = this.value;
var type = this.type;
var expirationTime = this.expirationTime;
if (value == null || (type == "browse" && this.expirationTime <= now)) {
var baseUrl = "http://localhost:9000/auth";
$.ajax({
type: "GET",
url: baseUrl + "/apps/" + appId + "/apikey"
}).done(function(data) {
$.ajax({
type: "POST",
data: JSON.stringify({ principal: appId, secret: data.apiKey }),
url: baseUrl + "/apps/credentials",
contentType: "application/json"
}).done(function(data) {
value = data.token;
$.ajax({
type: "GET",
headers: { "Authorization": "Token " + value },
url: baseUrl + "/users/credentials"
}).done(function(data) {
type = data.token.header.typ.split('/')[1],
expirationTime = data.token.claims.exp
})
})
});
}
this.set(value, type, expirationTime);
log("token: " + this.value); // value is null
log("typ: " + this.type); // type is null
log("exp: " + this.expirationTime); // expirationTime is null
obj.headers["Authorization"] = "Token " + this.value;
return true;
};
The code above performs three REST calls to obtain a token and let the client application browse thru the API. Finally, here is how I create the object:
window.authorizations.add("authToken", new TokenAuthorization("myApp", null));
Since I pass null as the second parameter (token), I need to get a browse token for the current client app. That's it.
I guess the problem has to do with the fact I'm performing async REST calls.
OK, after some debugging I figured out what problem was. ajax is async, so apply returns immediately and of course the data is still null.
Rewriting the code like this solved the problem:
var e = (typeof window !== 'undefined' ? window : exports);
var TokenAuthorization = function(appId, token, type, expirationTime) {
this.appId = appId;
this.token = token;
this.type = type;
this.expirationTime = expirationTime;
this.locked = false
};
TokenAuthorization.prototype.lock = function() {
this.locked = true;
};
TokenAuthorization.prototype.unlock = function() {
this.locked = false;
};
TokenAuthorization.prototype.apply = function(obj, authorizations) {
var now = Math.round(new Date().getTime() / 1000);
if (!this.locked && (this.token == null || (this.type == "browse" && this.expirationTime <= now))) {
var baseUrl = obj.url.split("api-docs")[0] + "auth";
var appId = this.appId;
this.lock();
$.ajax({
type: "GET",
url: baseUrl + "/apps/" + appId + "/apikey"
}).done(function(result) {
$.ajax({
type: "POST",
data: JSON.stringify({ principal: appId, secret: result.apiKey }),
url: baseUrl + "/apps/credentials",
contentType: "application/json"
}).done(function(result) {
var token = result.token;
$.ajax({
type: "GET",
headers: { "Authorization": "Token " + token },
url: baseUrl + "/users/credentials"
}).done(function(result) {
e.authorizations.add("authToken", new TokenAuthorization(
appId, token,
result.token.header.typ.split('/')[1],
result.token.claims.exp
));
log("token: " + token);
obj.headers["Authorization"] = "Token " + token;
})
})
});
} else if (!this.locked) {
obj.headers["Authorization"] = "Token " + this.token;
}
return true;
};
This way, if a token already exists, it is used as is, otherwise a new one will be set once the REST calls complete.