Posting data to JSON - Angular .post - javascript

I am working on an application and am having an issue posting to a .JSON file in my assets. I am working with an Angular based application. The error code I get is 404 with a response of: Cannot POST /assets/data/card-stack.json. Now the problem is, when I work with my get to retreive the JSON data it works perfect. It is only when I am using .post. Here is what I am doing:
$http.get('./../../assets/data/card-stack.json').success(function(data) {
$scope.cards = data;
// Set the showdown images from the card data grabbed from the card-stack.json file
$scope.showdowns = [
$scope.cards[0].url,
$scope.cards[1].url,
$scope.cards[2].url,
$scope.cards[3].url
];
});
// Simple POST request example (passing data) :
$http.post('./../../assets/data/card-stack.json', {url : './../images/banana.jpg'}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
console.log(data);
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Suggestions?

A .json file is a static file that just contains json data so you won't be able to post to it. Instead you would need to use a server side page or service such as php to process the posted data.

Try to set the $http header:
$http.defaults.headers.post["Content-Type"] = "application/json";
Try it.

Related

Dealing with cache and updated JSON files in AngularJS

I'm building an app where I add and delete items from a JSON file.
I've encountered the following problem: When I delete an item, it gets reflected in the frontend (the item disappears), but it takes a couple of hard page reloads for the app to read the new JSON file produced by my PHP file instead of the cached one.
If I just reload once, it will just read the JSON file in cache, which doesn't reflect the changes made.
Is there any way to deal with this issue directly in AngularJS?
Here's my Angular code:
$scope.remove = function(array, index){
if($scope.totsselected){
array.splice(index, 1);
$http.post("deleteall.php", {
data : array
})
.then(function(data, status, headers, config) {
$http.get('data/all.json')
.then(function (response) {
$scope.productesgenerals = response.data;
console.log($scope.productesgenerals);
}).catch(function (error) {
});
});
}
)};
And my PHP code:
<?php
$contentType = explode(';', $_SERVER['CONTENT_TYPE']);
$rawBody = file_get_contents("php://input"); // Read body
$data = json_decode($rawBody); // Then decode it
$all = $data->data;
$jsonData = json_encode($all);
file_put_contents('data/all.json', $jsonData);
?>
It sounds like you have $http caching turned on. Try disabling it for this request
$http.get('data/all.json', {cache: false})
https://docs.angularjs.org/api/ng/service/$http#caching
If that doesn't work (it is still cached), then it sounds like server-side caching. You can bust this by sending a unique query string.
$http.get('data/all.json?_=' + Date.now(), {cache: false})
This will make each request a unique request and should prevent the server side caching.
One caveat is that since you are ignoring the caching, you lose all the performance benefits of caching.

AngularJS HTTP Call / Response

This is probably something very simple but I am having some problem making an HTTP GET request, getting the data back, and attaching it onto the javascript global window variable.
Simple HTTP Call:
$http.get("production/dashboard?dashboard_type=A").success((data) ->
$scope.pods = data;
window.pods = $scope.pods.to_json;
window.type = 'A';
alert(window.pods)
alert(window.type)
alert "success1"
return
).error (data, status, headers, config) ->
return
Upon execution, I am getting:
1. Alert("undefined")
2. Alert("A")
I thought that the promise of the http request will get resolved when the response returns?
I checked the Network tab and there is indeed JSON data being sent back as the response to the request.
I must be missing something simple...
$http.get("production/dashboard?dashboard_type=A")
.success(function(data) {
$scope.pods = data;
window.pods = $scope.pods;
window.type = 'A';
alert(window.pods);
alert(window.type);
alert("success1");
return
}).error (function(data, status, headers, config){
return;
});
This is assuming it has access to the window where your code is. Is this wrapped in a module and controller?
As we need json data to get from $http.. Trying putting .json like below.
$http.get('/products.json')
Regarding your another issue.. you might get a hint with this link AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

POST Ajax request by AngularJS to Symfony controller

I'm trying to do an Ajax request from my angularJs controller to my Symfony controller. However, for an unknown reason, I cannot receive the data in my Symfony controller. My controller gets called and I can return some information that I will see in the success function on the AngularJS side. However, the data I'm sending via AngularJs cannot be retrieved on the Symfony controller.
Here's what I'm doing on the AngularJS side:
$http.post('{{ path('admin_ima_processmanagement_project_save', {'id':object.id}) }}',{"projectJson":"test"}).
success(function(data, status, headers, config) {
console.log("yeah");
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log("oh non");
console.log(data);
});
I can see in my console "yeah" that is appearing after the execution of this request.
In my Symfony controller, I have the following:
$request = $this->container->get('request');
$projectJson = $request->query->get('projectJson');
$response = array("code" => 100, "success" => true, "projectJson" => $projectJson);
return new Response(json_encode($response));
On the console, after the call, I get {"code":100,"success":true,"projectJson":{}} meaning that projectJson is unfortunately empty...
What should I do to retrieve the data that I'm sending from my client ?&
In class Request property query refers to GET parameters.
In your case you need to access to POST parameters, which are in request property.
So your code should look like this:
$projectJson = $request->request->get('projectJson');
More info about Request you will find here.
Symfony2 does not support AngularJS $http data. Because AngularJS sends data as request body, and SF2 reads only $_GET and $_POST.
You have 2 solutions:
Update Php code to handle such data
Update JS code to send classic form data (check https://gist.github.com/bennadel/11212050 for this)

Angularjs $http.get method not working

HI i have a micro service running on port 8501.
#RestController
#RequestMapping("/feeds")
public class FeedsController {
#RequestMapping(method = GET)
ResponseEntity<?> findAllFeeds() {
return new ResponseEntity<String>("Hello", OK);
}
}
when i add url http://localhost:8501/feeds, browser displays "Hello". Now i am trying to access this through angularjs get call
in my AngularJs my code is
'use strict';
var app = angular.module('commentsjsApp');
app.controller('MainCtrl', function ($scope,$http) {
$http.jsonp('http://localhost:8501/feeds').success(function(data, status, headers, config){
console.debug("Data : "+data+ "Status");
}).error(function(){
console.debug("error");
});
EDIT :
In Network tab (firebug) i can see the GET with 200 status and response is "Hello". Why i am getting the error in console then? Can any one kindly help me.
and when i run this angularjs app. the following output on console as shown in image
You are requesting a JSONP data, but the server is returning a string. Return a proper JSON object from the server to fix the issue.
Note: Hello world is not valid JSON, but "Hello World" is.
You need to add the header 'Access-Control-Allow-Origin' in the response, since your calling from localhost:9000 to localhost:8501 (they are technically different servers).
#RequestMapping(method = GET)
ResponseEntity<?> findAllFeeds(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) {
httpResponse.addHeader("Access-Control-Allow-Origin",
"http://127.0.0.1:9000");
return new ResponseEntity<String>("Hello", OK);
}
Sometimes Angular requires the colon in the URL to be quoted, try this:
$http.get('http://localhost\\:8501/feeds').success(function(data, status, headers, config){
console.debug("Data : "+data);
}).error(function(){
console.debug("error");
});

AngularJS wrapping JSON data returned from server

I have a basic CRUD application up and running, however what I am wanting to do is wrap every response from the server with two additonal parameters namely
'error' => boolean, 'errorMessage' => string, 'data' => {whatever data}
so that I can handle when a successful request is sent and returned from the server, however the database was unable to update for some reason so I can not only keep the UI in sync with the DB, but also present the user an error message on a failed update.
As AngularJS expects an updated object the UI will be in sync if I return the same object on failure, but as there would be no notification of failure the user wouldn't realize what the problem is.
Within my old applications pre-Angular (jQuery based) I could easily decode the json data on every response and if error === true present an error message, but in Angular I cannot seem to figure out how to accomplish this.
I may very well be off base here as I am just getting into Angular so any direction would be helpful.
Make this http request from angularjs and send back a response object from server.
response object --->{'error' => boolean, 'errorMessage' => string, 'data' => {whatever data}}
which gets collected in Resdata. use Resdata to take action.
$http({method: 'POST', url:url, data:body}).success(function(Resdata, status, headers, config) {
console.log(Resdata);
if(Resdata.error == true){
// use Resdata.errorMessage
}
else if(Resdata.error == false){
// use Resdata.data
}
}).error(function(Resdata, status, headers, config) {
console.log("error:", error);
});

Categories