W1ldworm W1ldworm - 2 months ago 9
AngularJS Question

Dynamic http post parameter name in AngularJS

I'm using an API for updating profile, by adding nickname, email, phone or password in request parameters each of them will be updated in database.

I want to pass one of these each time depending on user's choice for example when I want to update Nick name:

{
"nickname": "alifa",
"device_id": "chrome",
"device_model": "browser",
"device_os": "angularJS"
}


or for updating email:

{
"email": "info@example.com",
"device_id": "chrome",
"device_model": "browser",
"device_os": "angularJS"
}


I want to do this by passing property name and property value to a function and it will make an object and send http post request:

this.updateDetails = function(dataName, dataValue){
Loader.global.show();
var data = $.param({
device_id: app.device_id,
device_os: app.device_os,
device_model: app.device_model
});
data[dataName] = dataValue;
console.log(data);
return $http.post(app.baseUrl + 'profile/' , data).success(function(){
Loader.global.hide();
}).error(function(){
Loader.global.hide();
})
}


but what it sends to server is just:

Sent data

Is there any possible way to do this?

Answer

You need to modify the object you pass to param. Adding a property to the string you get out of param is pointless.

var data = {
  device_id: app.device_id,
  device_os: app.device_os,
  device_model: app.device_model
};
data[dataName] = dataValue;
var encoded_data = $.param(data);