AngularJS - $http missed specific key from request Payload - javascript

I'm using angular 1.5.7, and no idea why It's missing that key. Frequency of that bug is really low.
Server side rarely get post Request Payload without "priceMin":
expected:
{priceMin: 0, priceMax: 964, category: "", name: ""}
what I've get:
{priceMax: 964, category: "", name: ""}
function _doRequestPOST(request_url, data) {
var def = $q.defer(),
request = {
headers: {
'X-Requested-With' :'XMLHttpRequest'
},
method : 'POST',
url : request_url,
data : data
};
http = $http(request).then(
function(response){
//success
def.resolve(response);
},
function(response){
//error
def.reject(response);
}
);
delete http;
return def.promise;
};
this.sendStats = function(){
var requestData = {
priceMin: self.priceRange.min,
priceMax: self.priceRange.max,
category: self.filterExterior,
name: self.searchBot.name
};
_doRequestPOST('/saveFilterData', requestData);
}
};

Related

How to set headers in Ajax call?

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

jsGrid plugin - How to filter with remote data?

I'm a newbie when it comes to javascript. I'm using the jsGrid plugin to display a grid in the browser. The grid column headers will have the values "Request Status" and "Request Id". I can make it work with static data.
(function() {
var adminDashboardController = {
loadData: function(filter) {
return $.grep(this.requests, function(request) {
return (!filter.Status || request.Status === filter.Status)
&& (!filter.RequestId || request.RequestId.indexOf(filter.RequestId) > -1)
});
},
insertItem: function(insertingReq) {
},
updateItem: function(updatingReq) {
},
deleteItem: function(deletingReq) {
}
};
window.adminDashboardController = adminDashboardController;
adminDashboardController.status = [
{ Name: ""},
{ Name: "Requested"},
{ Name: "Declined"}
];
//This is the static data
adminDashboardController.requests = [
{ "Status": "Requested", "RequestId": "1"},
{ "Status": "Declined", "RequestId": "2"}
];
}());
But when it comes to fetching the data from an ajax call (using a json file for testing as the data source), the data no longer gets filtered when I choose "Requested" or "Declined" as the filtering criterion. I'm using the format mentioned in the documentation like this -
(function() {
var adminDashboardController = {
loadData: function (filter) {
return $.ajax({
type: "GET",
dataType: "json",
url: "/json/db514.json",
data: filter
});
},
insertItem: function(insertingReq) {
},
updateItem: function(updatingReq) {
},
deleteItem: function(deletingReq) {
}
};
adminDashboardController.status = [
{ Name: ""},
{ Name: "Requested"},
{ Name: "Declined"}
];
}());
I can't understand how to implement the filtering in this case!
The reason is that filtering should be implemented in the code.
In general it can be done:
on the client (just as in your first sample)
on backend, then you have to pass the filter to your endpoint, which will do filtering and return data.
combined approach (partially on backend and after on the client)
In your case you could either add an endpoint on backend, which will load json and filter data, or still do filtering on client-side, for example:
loadData: function (filter) {
return $.ajax({
type: "GET",
dataType: "json",
url: "/json/db514.json"
}).then(function(requests) {
return $.grep(requests, function(request) {
return (!filter.Status || request.Status === filter.Status)
&& (!filter.RequestId || request.RequestId.indexOf(filter.RequestId) > -1)
});
});
}
Checkout this issue on GtiHub https://github.com/tabalinas/jsgrid/issues/32.

Saving data to server via AJAX not working

having some issues with my save function on knockout. I was following the tutorial on the Knockout site http://jsfiddle.net/rniemeyer/bGsRH/. WHen I implement the code to my site I get an error an error 400 Bad request stating that my JSON data is invalid. After debugging a bit more I see that it`s returning [object, object] instead of my modified JSON data.
To give a little context, I basically have a table with my list of data and each row has their edit button. Upon clicking the edit button it opens a modal and shows the data of the selected item. The issue occurs when I try to modify and then save the data.
Here is my javascript code I have so far, would anyone know what im missing?:
<script type="text/javascript">
function EmployeeModal() {
var self = this;
self.Employees = ko.observableArray([]);
//Start of select/edit functions
//This codes allows to pass selected data to the hidden modal
self.currentEmployee = ko.observable(null);
self.showEmployee = function(vm){
self.currentEmployee(vm);
$('#myModal').modal('show');
};
//END of select/edit functions
//Start of the save function
self.save = function() {
var New_Incident_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents';
var UPDATE_Incident_URL = '../../../../_vti_bin/listData.svc/GDI_PROD_Incidents('+ encodeURIComponent($('#Incident_ID').val())+')';
var createIncidentUrl = $('#Incident_ID').val() != '' ? UPDATE_Incident_URL : New_Incident_URL;
var CREATE_Headers = {"accept": "application/json;odata=verbose"};
var UPDATE_Headers = {"accept" : "application/json;odata=verbose","X-HTTP-Method":"MERGE","If-Match":"*"};
var headertype = $('#Incident_ID').val() != '' ? UPDATE_Headers : CREATE_Headers;
$.ajax(createIncidentUrl, {
data: {
json: ko.toJSON({
Description: this.Description,
Incident: this.Incident
})
},
type: "POST",
processData: false,
contentType: "application/json;odata=verbose",
headers: headertype,
success: function(result) {
alert(ko.toJSON(result));
$('#myModal').modal('hide');
}
});
};
//Start - Go get data from Sharepoint.
$.getJSON("../../../../_vti_bin/listData.svc/GDI_PROD_Incidents?$filter=ÉtatValue%20ne%20%27Fermé%27&$orderby=PrioritéValue desc",
function (data) {
if (data.d.results) {
self.Employees(ko.toJS(data.d.results));
}
}
);
//END - Go get data from Sharepoint.
}
$(document).ready(function () {
ko.applyBindings(new EmployeeModal());
});
</script>
EDIT:
Here is an example of my data from the server.
[{
ID: "123",
Description: "The server x is unavailable",
Incident: "1234"
}, {
ID: "124",
Description: "The router located downtown is down",
Incident: "12345"
}, {
ID: "125",
Description: "Fiber optic cable downtown is flapping",
Incident: "123456"
}, {
ID: "126",
Description: "Network unvailable at the beaver site",
Incident: "1234567",
}];

How to post data with angular js to sql server

Thanks for all your input, but now I have more or less a similar problem, I have the data that needs to be stored in sql-server database, when I try to post it the data does not get written. Is my code structure correct?
self.CurrentDowntimeEvent = {
method: 'POST'
, url: 'someurl/test'
, data: {
DepartmentId: cookie
, CategoryId: -1
, Comment: ""
, DowntimeStart: "2014-07-07T10:00:00"
, DowntimeEnd: null
}
, headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
console.log(data);
}).error(function (data) {
});
$http is a service which should be injected into the controller, so you shouldn't need self. to reference it:
self.RecordsSave = function () {
for (var i = 0; i < self.Employees.length; i++) {
var employee = self.Employees[i];
var params = {
CompanyNumber: employee.ClockNumber,
Department: employee.DepartmentID,
Present: employee.Present,
Reason: employee.AbsentCode
};
$http.post(SAVE_EMPLOYEERECORDS, {
params: params
}).success(function (data) {
alert("testing");
});
}
};

AngularJS passing data to $http.get request

I have a function which does a http POST request. The code is specified below. This works fine.
$http({
url: user.update_path,
method: "POST",
data: {user_id: user.id, draft: true}
});
I have another function for http GET and I want to send data to that request. But I don't have that option in get.
$http({
url: user.details_path,
method: "GET",
data: {user_id: user.id}
});
The syntax for http.get is
get(url, config)
An HTTP GET request can't contain data to be posted to the server. However, you can add a query string to the request.
angular.http provides an option for it called params.
$http({
url: user.details_path,
method: "GET",
params: {user_id: user.id}
});
See: http://docs.angularjs.org/api/ng.$http#get and https://docs.angularjs.org/api/ng/service/$http#usage (shows the params param)
You can pass params directly to $http.get() The following works fine
$http.get(user.details_path, {
params: { user_id: user.id }
});
Starting from AngularJS v1.4.8, you can use
get(url, config) as follows:
var data = {
user_id:user.id
};
var config = {
params: data,
headers : {'Accept' : 'application/json'}
};
$http.get(user.details_path, config).then(function(response) {
// process response here..
}, function(response) {
});
Solution for those who are interested in sending params and headers in GET request
$http.get('https://www.your-website.com/api/users.json', {
params: {page: 1, limit: 100, sort: 'name', direction: 'desc'},
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
});
Complete service example will look like this
var mainApp = angular.module("mainApp", []);
mainApp.service('UserService', function($http, $q){
this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {
var dfrd = $q.defer();
$http.get('https://www.your-website.com/api/users.json',
{
params:{page: page, limit: limit, sort: sort, direction: direction},
headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
if ( response.data.success == true ) {
} else {
}
}, function(x) {
dfrd.reject(true);
});
return dfrd.promise;
}
});
You can even simply add the parameters to the end of the url:
$http.get('path/to/script.php?param=hello').success(function(data) {
alert(data);
});
Paired with script.php:
<? var_dump($_GET); ?>
Resulting in the following javascript alert:
array(1) {
["param"]=>
string(4) "hello"
}
Here's a complete example of an HTTP GET request with parameters using angular.js in ASP.NET MVC:
CONTROLLER:
public class AngularController : Controller
{
public JsonResult GetFullName(string name, string surname)
{
System.Diagnostics.Debugger.Break();
return Json(new { fullName = String.Format("{0} {1}",name,surname) }, JsonRequestBehavior.AllowGet);
}
}
VIEW:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module("app", []);
myApp.controller('controller', function ($scope, $http) {
$scope.GetFullName = function (employee) {
//The url is as follows - ControllerName/ActionName?name=nameValue&surname=surnameValue
$http.get("/Angular/GetFullName?name=" + $scope.name + "&surname=" + $scope.surname).
success(function (data, status, headers, config) {
alert('Your full name is - ' + data.fullName);
}).
error(function (data, status, headers, config) {
alert("An error occurred during the AJAX request");
});
}
});
</script>
<div ng-app="app" ng-controller="controller">
<input type="text" ng-model="name" />
<input type="text" ng-model="surname" />
<input type="button" ng-click="GetFullName()" value="Get Full Name" />
</div>
For sending get request with parameter i use
$http.get('urlPartOne\\'+parameter+'\\urlPartTwo')
By this you can use your own url string

Categories