I have the following submit method:
submitForm(e) {
e.preventDefault();
var token = document.getElementsByTagName("meta")[0].getAttribute("content");
var form = document.querySelector('.form');
if(navigator.onLine && JSON.parse(localStorage.getItem('candidates'))) {
axios({
url: '/save-data',
method: 'POST',
contentType: 'application/json',
data: {
"candidates": localStorage.getItem('candidates')
},
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token
}
}).then(function(response) {
console.log(response);
})
.catch(function(e){
console.log(e);
});
}
else {
var singleCandidate = serialize(form, { hash: true });
var fromStorage = localStorage.getItem("candidates");
if (fromStorage) {
var parsedFromStorage = JSON.parse(fromStorage)
parsedFromStorage.push(singleCandidate)
localStorage.setItem("candidates", JSON.stringify(parsedFromStorage));
}
else {
localStorage.setItem("candidates", JSON.stringify([singleCandidate]));
}
}
}
it loads data from local storage and submits it if there is data and connection at the same time.
However there is something that doesn't work with the following:
data: {
"candidates": localStorage.getItem('candidates')
},
if I do:
data: {
"candidates": [
{
"name": this.state.firstName,
"email": this.state.email,
"university": this.state.university,
"degree": this.state.degree
}
]
},
I get a positive response, form data gets submitted. However I have to submit this value (localStorage.getItem('candidates')) and when I do that I get the following:
Should "localStorage.getItem('candidates')" be changed to another format?
Related
Vue-Cookies .set function doesn't seem to set the cookie in Chrome, Safari or Firefox. Below is the code I'm using, called whenever someone authenticates:
vm.$cookies.set('token', response.headers.authorization)
Where "response.headers.authorization" is a real variable fetched from response data.
I get no errors in the console and I am able to see the site's cookies using the .keys function.
Does anyone have any ideas? I've posted a bigger block below to give some context.
export default {
name: 'Home',
components: {},
methods: {
sso: function () {
var vm = this;
axios({
method: 'POST',
url: api + 'secure/use',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
data: {
username: vm.$refs.username.value,
password: vm.$refs.password.value
}
}).then(function (response) {
vm.response = response.data;
if (response.headers.authorization) {
console.log(vm.$cookies.keys()) //THIS WORKS.
vm.$cookies.set('token', response.headers.authorization) //THIS HAS NO EFFECT.
vm.$router.push('/')
} else {
vm.error = true;
}
})
}
}...
I am developing multi-language website using Angularjs and a Web api as backend. I am trying to send RequestedPlatform and RequestedLanguage in the header whenever I make an API call.
Below is my Ajax request call.
$http.post(url,RegistrationData).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function (error) {
toastr.error('', 'Error Occured');
});
updated code
var RegistrationData = {
FirstName: $scope.user.Fname,
LastName: $scope.user.Lname,
Password: $scope.user.password,
Gender: "Male",
DateOfBirth: "2017-04-04",
Nationality: $scope.user.selectedGlobe,
Mobile_CountryCod: "91",
MobileNumber: $scope.user.mobilenumber,
EmailId: $scope.user.email,
Home_Location: $scope.user.homeLocation,
Home_City: $scope.user.homeCity,
Home_Neighbourhood: $scope.user.homeNeighbourhood,
Home_HouseNumber: $scope.user.housenumber,
Home_MainStreet: $scope.user.homemainstreet,
Home_SubStreet: $scope.user.homesubstreet,
Work_Location: $scope.user.worklocation,
Work_City: $scope.user.workcity,
Work_Neighbourhood: $scope.user.workNeighbourhood,
Work_HouseNumber: $scope.user.workhousenumber,
Work_MainStreet: $scope.user.workmainstreet,
Work_SubStreet: $scope.user.worksubstreet
};
var req = {
method: 'POST',
url: url,
data: { RegistrationData: RegistrationData },
headers: {
RequestedPlatform: "Web",
RequestedLanguage: "English"
}
}
$http(req).then(function (response) {
var pageList = response.data.ID;
toastr.success('', 'Registered Succesfully');
$state.go('Registration.OTPVerification', { pageList });
}, function () {
toastr.error('', 'Error Occured');
});
May I get some help to set headers in Ajax. Any help would be appreciated.
you can send headers with headers property of $http
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});
and if you want headers for all the requests that can be fully configured by accessing the $httpProvider.defaults.headers configuration object,
Reference
There are few ways and I have posted one which I have been using it for a while. I hope you are looking for the below
$http.post('test', data, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined
}
})
This is how I currently make a PUT request:
var data = {
'Content-Type': 'application/json',
'number': 'TEST12345'
}
var post = {
"number": "TEST12345",
"parameters":
{
"START_NUMBER" : {
"value": 5,
"effectiveDate": "2016/01/01 10:10"
}
}
}
var myInit = {
method: 'POST',
mode: 'cors',
headers: data,
body: JSON.stringify(post)
};
fetch('http://localhost:8080/form/upload/post/save', myInit)
.then(result=>{console.log(result.json())})
So I was wondering if it's possible to do the same but for a PUT request? If so how can I go about doing so?
I have written the following code to insert records in a list which is contained in the host site.
var projectItems = [
{ Title: "SharePoint", ProjectDescription: "SharePoint 2013", ProjectManager: "Test0" },
{ Title: "Lync", ProjectDescription: "Lync 2013", ProjectManager: "Test1" },
{ Title: "Exchange", ProjectDescription: "Exchange 2013", ProjectManager: "Test2" }
];
function insertListItems(items) {
for (var item in items) {
var inputData = new Object();
var type = new Object();
type.type = getListItemType(listName);
inputData.__metadata = type;
for (var prop in items[item]) {
inputData[prop] = items[item][prop];
}
console.log(JSON.stringify(inputData));
console.log(url);
var obj = {
url: url,
type: "POST",
contentType: "application/json; odata=verbose",
data: JSON.stringify(inputData),
headers: { "Accept": "application/json; odata=verbose", "X-RequestDigest": $("#__REQUESTDIGEST").val() },
success: function (successData) { console.log("insert successful"); },
error: function (errorData) { console.log("insert failed") }
};
if (parent) {
var exec = new SP.RequestExecutor(appWebUrl);
exec.executeAsync(obj);
} else {
$.ajax(obj);
}
}
}
insertListItems(projectItems);
when I run it it prints
{"__metadata":{"type":"SP.Data.ProjectsListItem"},"Title":"SharePoint","ProjectDescription":"SharePoint 2013","ProjectManager":"Test0"}
http://app-e9f4c136adfd88.abhiapps.com/SPAppHelper/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Projects')/items?#target='http://dev.abhi.com'
{"__metadata":{"type":"SP.Data.ProjectsListItem"},"Title":"Lync","ProjectDescription":"Lync 2013","ProjectManager":"Test1"}
http://app-e9f4c136adfd88.abhiapps.com/SPAppHelper/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Projects')/items?#target='http://dev.abhi.com'
{"__metadata":{"type":"SP.Data.ProjectsListItem"},"Title":"Exchange","ProjectDescription":"Exchange 2013","ProjectManager":"Test2"}
http://app-e9f4c136adfd88.abhiapps.com/SPAppHelper/_api/SP.AppContextSite(#target)/web/lists/getbytitle('Projects')/items?#target='http://dev.abhi.com'
insert successful
insert successful
insert successful
I have multiple problems with this source code
No records actually get inserted. but no errors are thrown.
How do I ensure that in my main method... the code which comes after the insertListItems method is only executed when all the 3 records have been inserted successfully. currently because of the async nature of javascript the flow moves forward even before anything has been inserted.
I googled on option 2 and found that jquery has a promise and deffered object pattern but it seems SP.RequestExecutor.executeAsync does not follow that and throws an error on the "done" method saying no such method is supported.
This is how my lists looks
Replace your obj with this:
....
method: "POST",
body: JSON.stringify(inputData),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
}
....
....
in my MVC layout page I have the following:
$("body").ajaxError(
function (e, request) {
if (request.status == 403 || request.status == 500) {
window.location = '#Url.Action("LogOn", "Account", new {area = "", msg = "forbidden", returnUrl = HttpContext.Current.Request.RawUrl})' + window.location.hash;
return;
}
window.location = '#Url.Action("Index", "Error")';
}
);
on another page I'm performing an ajax call like so:
...
$.when(refreshActionLinks(row, machineId, packageId)).done(function(a1) {
row.find("span").text(opStatus).removeClass("pending");
progressbar.progressbar("destroy");
$(row).flash(bg[1], 1000);
});
...
javascript function:
function refreshActionLinks($row, machineId, packageId) {
try {
var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
console.log("refreshActionLinks => " + json);
$row.find("td.options div.actionLinks").html("<img src='#Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
return $.ajax({
url: "#Url.Action("GetActionLinks", "Packages")",
data: json,
timeout: 50000,
contentType: 'application/json',
type: 'POST',
success: function (data) {
if ($row.length) {
$row.find("td.options div.actionLinks").html(data);
}
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
} catch(e) {
// hide icons
$row.find("a.action").remove();
}
}
The issue is that while refreshAction function is executing, clicking a menu link causes the ajax call to error out - which in this case is correct. BUT it does take me to /Index/Error page which is NOT correct. I would like "$("body").ajaxError" to handle all ajax errors on the site EXCEPT on the page I'm calling refreshActionLinks. Notice, I already have try/catch surrounding my ajax call. why doesn't that work?
thanks
figured it out:
ajax has a settings:
global: false
now my function looks like this:
function refreshActionLinks($row, machineId, packageId) {
try {
var json = JSON.stringify({ packageId: packageId, machineId: machineId, tabType: $("#TabType").val() });
console.log("refreshActionLinks => " + json);
$row.find("td.options div.actionLinks").html("<img src='#Url.Content("~/Content/images/ajax-load2.gif")' />"); // pending
return $.ajax({
url: "#Url.Action("GetActionLinks", "Packages")",
global: false, // disable error pages on failed ajax calls
data: json,
timeout: 50000,
contentType: 'application/json',
type: 'POST',
success: function (data) {
if ($row.length) {
$row.find("td.options div.actionLinks").html(data);
}
}
});
} catch(e) {
// hide icons
$row.find("a.action").remove();
}
}