AngularJS is not creating JSON as desired. With code (below) , it generates array (serialized steam ) but not form . ie
I am getting
{
data : 'value',
date : 'value'
}
But wanted - JSON ie
{
"data" : "value",
"date" : "value"
}
The code for Angular to POST json is ( snippet )
<script>
// Defining angularjs application.
var postApp = angular.module('postApp', []);
// Controller function and passing $http service and $scope var.
postApp.controller('postController', function($scope, $http) {
// create a blank object to handle form data.
$scope.user = {};
// calling our submit function.
$scope.submitForm = function() {
// Posting data to php file
$http({
method : 'POST',
url : 'user.php',
data :JSON.stringify($scope.user),
headers : {'Content-Type': 'application/json'}
})
.success(function(data) {
if (data.errors) {
// Showing some error which has to come from server
} else {
$scope.message = data.message; //make the json
}
});
};
});
</script>
What should i do to get JSON and not Array ?
If you want your data in JSON format you should use JSON.parse();
$http({
method : 'POST',
url : 'user.php',
data :JSON.parse($scope.user),
headers : {'Content-Type': 'application/json'}
})
have you tried angular.toJson method?
Solved .
by using nothing ie.
json: $scope.user it works ...
Related
I am new to angular-js and building a simple to-do application. I am creating a task and displaying the created task in a html table using ng-repeat. But the problem is that after posting the data, $scope.tasks variable is updated on controller side, but not in view. The view updates after refreshing the web page only and the task is added to html table. How can I make the view update after creating the task. Thanks in advance. Here is my code:
In my controller:
var app = angular.module('MyApp', ['ngMaterial', 'ngMessages']);
app.controller('DemoCtrl', function($scope,$mdSidenav,$mdDialog,$interval,$http,$mdToast) {
$scope.tasks = [];
_refreshTaskData(); //initial refresh
$scope.submitForm = function() {
var description = "";
var taskId = "";
$scope.formData = {
taskId: $scope.taskId,
description: $scope.description,
};
$http({
method: "POST",
url: 'savetask',
data: angular.toJson($scope.formData),
headers : {
'Content-Type': 'application/json',
}
}).then(_success, _error);
};
function _refreshTaskData() {
$http({
method : 'GET',
url : 'getTask',
}).then(function(res) { // success
$scope.tasks = res.data;
}, function(res) { // error
console.log("Error: " + res.status + " : " + res.data);
});
}
function _success(res) {
$mdDialog.hide();
console.log('in success function');
_refreshTaskData(); ;
}
function _error(res) {
//error handling
}
});
In my view:
<table>
<tr ng-repeat=" t in tasks">
<td>{{t.id}}</td>
<td>{{t.description}}</td>
</tr>
</table>
You must understand that these JS frameworks are asynchronous. Now what happens is, if you do an API call and make another API call whose result is based on the first one, the console does not wait for the result from one API and directly moves forward. SO what's happening in your case is sometimes/many times, before the POST call is served, the controller is not able to get fresh data with GET in time, thus not updating the view. What you can possibly do is enforce the GET only when POST is served
$http({
method: "POST",
url: 'savetask',
data: angular.toJson($scope.formData),
headers : {
'Content-Type': 'application/json',
}
}).then(function(res){
$http({
method : 'GET',
url : 'getTask',
}).then(function(res) { // success
$scope.tasks = res.data;
}, function(err) { // error
console.log("Error: " + err.status + " : " + err.data);
});
});
It would be best if you are sending a success message from the backend and checking before GET call
I think you are not calling _refreshEmployeeData at any point of time. If you add that instead of _refreshTaskData in your JS, then you will be able to see the result in view.
Also kindly use ng-init to call the _refreshEmployeeData in the controller. That would be the best way to initialize the fields.
i have code like it on angular
my array :
[{"kode":"123","nama":"satu dua tiga"},{"kode":"321","nama":"tiga dua satu"}]
$http({
method: 'POST',
url: 'api/insertCustomerArr',
data: myarray
}).then(function successCallback(response) {
}, function errorCallback(response) {
});
and how i can get this data on controller laravel and how i can looping ?
public function insertCustomerArr(Request $request)
{
echo count($request);
exit;
}
this code result count 1, how i can get data?
You can check using
return $request->all();
this will return all the data you posted from angular request
Laravel $request object has a request property inside of it.
So that basically $request->request->all(); should contain all the data that came from angular.
I want to copy one list(investDtls) to another list (listInvestOptions) which is part of POST body.
Below is the code snippet:
app.controller("OneClickController", function($scope,$location, $resource, $http){
$scope.investDtls ={};
$scope.submitOneClick = function(investDtls) {
//$scope.oneClick.submitOneClickDetails.listInvestOptions = angular.copy(investDtls);
$http({
method : 'POST',
url : '/investor/api/v1/oneclick',
data : $scope.oneClick
}).success(function(response) {
$scope.oneClick.submitOneClickDetails.listInvestOptions = angular.copy(investDtls);
//alert("success");
});
}
});
Here I have some fields inside investDtls list and I want to copy the contents into another list(listInvestOptions) which is part of a POST body
and I am accessing it like:
$scope.oneClick.submitOneClickDetails.listInvestOptions
But as per the above code snippet, list is getting copied after the POST operation.
I want to perform the copy operation just before calling the POST block
$scope.oneClick.submitOneClickDetails.listInvestOptions = angular.copy(investDtls);
$http({
method : 'POST',
url : '/investor/api/v1/oneclick',
data : $scope.oneClick
})
If I am proceeding as above, it will not work as $scope.oneClick.submitOneClickDetails.listInvestOptions part is not accessible unless POST block is exexuted.
Hope I am clear from my side.. Any more clarifications most welcome.. :)
Look at this Plunker and let me know it if helps in any way.
JS
var app = angular.module("app", []);
app.controller("OneClickController", function($scope, $location, $http){
$scope.investDtls = {'test': 'blah'};
$scope.oneClick = {submitOneClickDetails: {listInvestOptions: null}};
$scope.submitOneClick = function(investDtls) {
$scope.oneClick.submitOneClickDetails.listInvestOptions = angular.copy(investDtls);
$http({
method : 'GET',
url : 'data.json',
data : $scope.oneClick
}).success(function(response) {
console.log(response);
console.log($scope.oneClick);
});
}
});
Markup
<body ng-controller="OneClickController">
<button ng-click="submitOneClick(investDtls)">Submit</button>
</body>
Note that I am using GET for test purposes.
I have my data in json at controller, now i want to send that data to an post api call in service.
service - Article
At my controller :
var annotationScripts = {startOffset : range.startOffset , endOffset : range.endOffset};
Article.post({id: $routeParams.articleId},{data : annotationScripts}
);
At my service :
factory('Article', function($resource) {
return $resource('article/:id', {}, {
query: { method: 'GET', isArray: false },
post : { method: 'POST', params:{id : '#id'} , data : {#data}, headers: {'Content-Type': 'application/x-www-form-urlencoded'}}
})
});
Why dont you use $resource out of the box features?
Here's a post example, with a simplified version of what you already have:
Resource service
factory('Article', function($resource) {
var Article = $resource('article/:id', {id: "#id"});
return Article;
});
Controller
var article = new Article();
article.startOffset = range.startOffset;
article.endOffset = range.endOffset;
article.$save();
I have a service where I am pulling data from server. When I click the button to send out the request to server through this service, the window freezes until I receive a response from server. Is there anything I can do to make this request asynchronous ?
Here is my service.
app.factory('service', function($http) {
return {
getLogData : function(startTime,endTime){
return $http({
url: baseURL + 'getLogData',
method: 'GET',
async: true,
cache: false,
headers: {'Accept': 'application/json', 'Pragma': 'no-cache'},
params: {'startTime': startTime , 'endTime': endTime}
});
}
};
)};
HTML.
<button ng-click="getData()">Refresh</button>
<img src="pending.gif" ng-show="dataPending" />
Code
$scope.getData = function(){
service.getLogData().success(function(data){
//process data
}).error(function(e){
//show error message
});
}
While there is some argument about the pros and cons of your approach, I am thinking that the problem is answered here: AJAX call freezes browser for a bit while it gets response and executes success
To test if this in fact part of the problem, dummy up a response and serve it statically. I use Fiddler or WireShark to get the response and then save to a file like testService.json. XHR and all of it's various derivatives like $HTTP $.ajax see it as a service though the headers might be slightly different.
Use the success promise, and wrap up the log data in a set of objects that you can attach to a $scope.
So instead of having your service have a blocking method, have it maintain a list of "LogEntries".
// constructor function
var LogEntry = function() {
/*...*/
}
var logEntries = [];
// Non-blocking fetch log data
var getLogData = function() {
return $http({
url : baseURL + 'getLogData',
method : 'GET',
async : true,
cache : false,
headers : { 'Accept' : 'application/json' , 'Pragma':'no-cache'},
params : {'startTime' : startTime , 'endTime' : endTime}
}).success(function(data) {;
// for each log entry in data, populate logEntries
// push(new LogEntry( stuff from data ))...
};
}
Then in your controller, inject your service and reference this service's log data array so Angular will watch it and change the view correctly
$scope.logEntries = mySvc.logEntries;
Then in the HTML, simply do something over logEntries:
<p ng-repeat="logEntry in logEntries">
{{logEntry}}
</p>
use this code to config
$httpProvider.useApplyAsync(true);
var url = //Your URL;
var config = {
async:true
};
var promise= $http.get(url, config);
promise.then(
function (result)
{
return result.data;
},
function (error)
{
return error;
}
);