var app = angular.module("myApp",[]);
app.controller("myCtrl",function($scope,$http){
$http({
method: 'POST',
url: '../api/CreateOrder',
data: Object.toparams(myobject),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response) {
window.location.href = "checkout.html?OrderId=" + response.data;
}, function errorCallback(response) {
alert("Error. while updating user Try Again!");
});
});
Here is my code , I am receiving response from http GET , How to transfer the response data which has OrderId to window.location.href as Parameter?
Let's assume that response.data is [{OrderId : 25 }] then try
window.location.href = "checkout.html?OrderId=" + response.data[0].OrderId;
search(search, [paramValue]);
This method is getter / setter.
Return search part (as object) of current URL when called without any parameter.
Change search part when called with parameter and return $location.
$location.search({OrderId : 25 });
locationSearchStatus = $location.search();
AngularJs Doc
Related
I want to submit data from a form and display the result in the view directly after http request returns a result. But it's not happening.
$scope.formData = {};
$scope.add = function (){
$http.post('add.php',$scope.formData,{'Content-Type': 'application/x-www-form-urlencoded'})
.then(function (result) {
console.log(result.data);
if (result){
$scope.data = result.data;
}
});
};
And this is add.php. In this file I just want to return the posted data in json.
function index(){
$data = $this->input->post();
echo json_encode($data);
}
I find it returns false value. I wonder how I process data submitted with post method using $http.post like this.
You can try this way to pass data to add.php service
$scope.add = function (){
$http({
method: 'POST',
url: 'add.php',
headers: {
'Content-Type': application/x-www-form-urlencoded
},
data:$scope.formData
}).then(function successCallback(response) {
$scope.data = response.data.data;
}, function errorCallback(response) {
console.log(response);
});
}
Try this in PHP:
$data = $this->input->post(NULL, TRUE);
In AngularJS, inject $httpParamSerializerJQLike in your service/factory
$scope.add = function (){
$http({
method: 'POST',
url: '/add.php',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $httpParamSerializerJQLike($scope.formData);
}).then(function resolve(response) {
console.log(response);
$scope.data = response.data.data;
}, function reject(response) {
console.log(response);
});
}
I am newbie of angularJS. I want to add header in my http request but i am not understanding how? so far i've written this code.
Original code without header:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http.post(url, dataObj);
}
Now i am adding header to it, the code becomes like this:
function saveUser(user, $http) {
var token = "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjYxLCJpc3MiOiJodHRwOlwvXC8zNC4yMDQuMjIyLjExM1wvYXBpXC91c2VycyIsImlhdCI6MTQ5NTE4MDY3MCwiZXhwIjoxNDk1MTg0MjcwLCJuYmYiOjE0OTUxODA2NzAsImp0aSI6IkdkNXdUSmZQMDRhcjc2UWIifQ.dKGZTysAibFbtruvSI7GwFV61kh43CX22g8-sRV9roQ";
var url = __apiRoot + "/users/" + user.id;
var dataObj = {
payload: JSON.stringify(user),
_method: "PUT",
}
return $http({headers: {
'Authorization': token
}}).post(url, dataObj);
}
By adding header, i am getting this error:
angular.js:14525 Error: [$http:badreq] Http request configuration url
must be a string or a $sce trusted object. Received: undefined
You're using the wrong syntax. Take a look at the angular documentation for $http here.
Your code should look like this:
$http({
method: 'POST',
url: __apiRoot + "/users/" + user.id,
data: JSON.stringify(user)
headers: {
'Authorization': token
}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I am attempting to pass a value from angular to my MVC Core controller to use in a repository function as simple string. However, I've noticed that it's passing a null value to the MVC controller. I don't want to create an MVC model just to use the POSTed JSON as a string.
Function excerpt from MVC controller
[HttpPost("api/specials/GetCurrentSpecialsBySiteID")]
public ActionResult GetCurrentSpecials([FromBody] string siteID)
{
return Ok(_repo.GetAllSpecialsBySiteID(siteID));
}
$Http Angular function
$http({
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: siteID,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
.then(function (response) {
// success
console.log(response);
vm.Specials.push(response.data);
angular.copy(response.data, vm.Specials);
console.log(vm.Specials);
// clear the form
vm.newSpecials = {};
}, function (response) {
// failure
console.log("Error !" + response.data);
vm.errorMessage = "Failed to save subscription";
})
.finally(function () {
vm.isBusy = false;
});
In mvc controller you are passing action parameter as string.
Please check you "siteID" Type in your JS.
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: siteID,
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
From your example it looks like you should probably be performing a GET rather than a POST, however you can adapt your methods as follows to get up and running:
[HttpPost("api/specials/GetCurrentSpecialsBySiteID")]
public ActionResult GetCurrentSpecials([FromUri] string siteID)
{
return Ok(_repo.GetAllSpecialsBySiteID(siteID));
}
And your angular function:
$http.post('/api/organisations/test?siteID=' + siteID)
.then(function (response) {
...
})
.finally(function () {
...
});
Try to pass object in $Http Angular function.
$http({
method: 'POST',
url: '/api/specials/GetCurrentSpecialsBySiteID',
data: {siteID: siteID},
headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})
.then....
For more just check $http service documentation here.
i' using AngularJS v1.4.2. i have 2 html page , they have 2 controller.both controller have save event. how to use use http post method
first controller i'm calling post method given below
var promisePost = crudService.post(Countries);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getCountry();
$stateParams.country = "";
}, function (err) {
alert("NOt Inserted")
});
second controller i'm calling post method given below
var promisePost = crudService.post(Levels);
promisePost.then(function (pl) {
alert("Sucessfully Inserted")
getLevel();
}, function (err) {
alert("NOt Inserted")
});
my app.js
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.post = function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.post = function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
but this code only take last post method.How to selecet post method properly. Anyone can helpme?
User countryPost and levelPost as follows and call those accordingly.
myapp.service('crudService', function ($http, RESOURCES) {
//Create new record
this.countryPost= function (Country) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
return request;
}
this.levelPost= function (Level) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
return request;
}
});
The best practice for using services is to return an object from it
myapp.factory('crudService', function ($http, RESOURCES) {
return {
saveCountry : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveCountry",
data: Country
});
},
saveLevel : function(){
return $http({
method: "post",
url: RESOURCES.baseUrl + "saveLevel",
data: Level
});
}
}
});
then inject it into your controller dependencies and use it like :
crudService.saveLevel().then(function(){
//do some code here
})
Create a single post method instead and receive the url to call in it as parameter along with the data. As shown below:
this.post = function (data, remainingUrl) {
var request = $http({
method: "post",
url: RESOURCES.baseUrl + remainingUrl,
data: data
});
return request;
}
I've angularjs post call (submit a login form data) to a /login nodejs API endpoint. The data received at Nodejs endpoint (in request.body) is not in json format but it has extra padding as shown below,
{ '{"email": "a#b.com", "password": "aaa"}': ''}
What is this format? How do I access 'email' and/or password from this object?
Client code,
login: function(loginData, callback) {
$http({
method: 'POST',
url: '/api/login',
data: loginData,
headers: {'Content-Type': 'application/x-www.form-urlencoded'}
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
}
Server code:
app.post('/login', function(req, res) {
console.log('Email:' + req.body.email); //this gives undefined error
console.log(req.body); // shows { '{"email": "a#b.com", "password": "aaa"}': ''}
}
What am I missing? Any help is appreciated.
--Atarangp
By default angularjs use JSON.stringify. If you wanna use x-www-form-urlencoded, you have to specify your transform function.
// transforme obj = {attr1: val1} to "attr1=" + encodeURIComponent(val1) + "&attr2=" ...
function transformRequestToUrlEncoded(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
}
$http({
method: 'POST',
url: your_url,
headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
transformRequest: transformRequestToUrlEncoded, // specify the transforme function
data: datas
});