here's my issue:
I did a very basic angularJS app which is supposed to get data from a php file and bind them into the scope. So the php file (linked to MySQL DB) output is:
[{"hum":"55.36","temp":"20.86","unixtime":"2015-10-29 17:39:42","coreid":"xxxxxx","moist":"0.02","volt":"4.30","soc":"114"},
{"hum":"55.33","temp":"20.84","unixtime":"2015-10-29 17:39:50","coreid":"xxxxxx","moist":"0.00","volt":"4.30","soc":"114"},
{"hum":"55.42","temp":"20.84","unixtime":"2015-10-29 17:39:58","coreid":"xxxxxx","moist":"0.02","volt":"4.30","soc":"114"}]
The app's code is:
var dashb = angular.module('dashboard', []);
//avoid cross domain issue
dashb.config(['$httpProvider', function($httpProvider) {
$http.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
dashb.controller('dbCtrl', ['$scope', '$http', function ($scope, $http) {
$http.get("http://www.domain.com/php_file_url.php")
.success(function(data) {
$scope.data = data;
$scope.hum = data.hum;
})
.error(function() {
$scope.data = "error in fetching data";
});
}]);
But when I run it it doesn't work. I get no data. What do I do wrong? Thank you
If you're sure you're getting data from your query, you just need to send it as JSON. Add this before the echo $res; line:
header('Content-Type: application/json');
Also, in your code, change the following
$http.defaults.useXDomain = true;
to
$httpProvider.defaults.useXDomain = true;
Related
I've literally checked out every single ng-repeat question out there but a lot of them don't deal with databases and people just use arrays in JS and a simple $scope.array.push("stuff") works for them.
I've tried $scope.apply, $rootScope and even calling the GET request right after a successful POST request.
I have a form with 2 text inputs, date and content.
When the submit button is pressed, date and content are added into a MySQL database using PHP.
The data is added just fine to the MySQL database and retrieving also works properly.
Even the GET request inside the successful POST request is executed.
So I don't understand why it forces me to refresh the page to see the updated ng-repeat results.
Am I missing something?
Any help or suggestions is greatly appreciated, thanks!
Relevant HTML code
<div ng-controller="insertController">
<h2> What I learned today </h2>
<form>
Date <br>
<input type="text" ng-model="date"><br><br>
Content <br>
<textarea rows="10" cols="50" ng-model="content"></textarea><br><br>
<input type="button" value="Submit" ng-click="insertdata()">
</form>
</div>
<div ng-controller="fetchController">
<span ng-repeat="item in results">
{{item.date}}<br>
{{item.content}}<br><br>
</span>
</div>
insertController.js
var app = angular.module('myApp', []);
app.controller('insertController', function($scope, $http) {
$scope.insertdata = function() {
$http({
method: 'POST',
url: 'http://localhost/storestuff/insert.php',
data: {'date':$scope.date, 'content':$scope.content, 'in':'json-format'},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function(res) {
console.log("Successful response", res)
$scope.date = "";
$scope.content = "";
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
alert("GOT NEW DATA");
$scope.results = response.data; // Allow angular to access the PHP output data
});
$scope.apply;
})
.catch(function(err) {
console.error("Error with POST", err);
});
}
});
insert.php
<?php
header('Access-Control-Allow-Origin: *');
$theConnection = mysqli_connect("localhost", "root", "", "storestuff");
if(mysqli_connect_errno()) {
echo "Failed to connect to MySQL.";
}
$theData = json_decode(file_get_contents('php://input'));
$date = mysqli_real_escape_string($theConnection, $theData->date);
$content = mysqli_real_escape_string($theConnection, $theData->content);
mysqli_query($theConnection, "INSERT INTO thestuff(date, content) VALUES('$date', '$content')");
mysqli_close($theConnection);
?>
fetchController.js
app.controller('fetchController', function ($scope, $http) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
$scope.results = response.data; // Allow angular to access the PHP output data
});
});
fetch.php
<?php
header('Access-Control-Allow-Origin: *'); // clientside(Node) <-> serverside(PHP)
$mysqli = new mysqli("localhost", "root", "", "storestuff");
if($mysqli->connect_error) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT * FROM thestuff";
$theData = array();
if($result = $mysqli->query($query)) {
while($row = mysqli_fetch_array($result)) {
$theData[] = array(
'date'=>$row['date'],
'content'=>$row['content']);
}
echo json_encode($theData); // Echo the output for the controller to access
$result->free(); // Free the result set
}
else {
echo "0 results.";
}
$mysqli->close(); // Close the connection
?>
The problem with this code is that you have two different controllers, both with separate scopes. Inserting/updating the $scope.results object/array in one controller, will not update the other $scope; they are separate distinct scopes, both with a copy of the data.
Using two controllers looks correct in your use case. However you should be using a service to access your remote data. Check out this answer for some advice on this https://stackoverflow.com/a/20181543/2603735.
Using a service like in that answer, will allow you to store the array/object of remote data in one place, and reference the SAME object from both controllers. Therefore updating from one controller, will also update the other.
For anyone who will ever stumble on my question, I don't want to just leave my broken code there with no answer but neither can I edit the question and put in my answer cause that would defy the purpose of StackOverflow.
So here is my answer to my own question.
I had to make quite a few changes to what I had before. The biggest change by far, is how I handled the data that was returned by fetch.php.
Instead of just taking the output into $scope.results = response.data;, which would work fine if I wasn't dynamically adding to the database, but for this case, I ended up using a service. (Thanks #jayden-meyer for suggesting Angular services.)
The service allowed me to access the same array from my insertController and from my fetchController instead of having a copy of the same array in both controllers which was my problem.
No changes in the HTML code.
No changes to insert.php.
No changes to fetch.php.
insertController.js
I removed the extraneous GET request I had inside the .then method which was completely unneeded since I can just push to the existing array.
(Thanks #charlietfl for the tip)
Instead I added resultsService.addItem($scope.date, $scope.content); inside of the .then method.
I also added my service as an argument.
app.controller('insertController', function($scope, $http, resultsService) {
result.js
app.service('resultsService', function() {
var results = new Array();
var addItem = function(date, content) {
var obj = new Object();
obj["date"] = date;
obj["content"] = content;
results.push(obj);
}
var getItems = function() {
return results;
}
return {
addItem: addItem,
getItems: getItems
};
});
fetchController.js
var size = 0;
var count = 0;
app.controller('fetchController', function ($scope, $http, resultsService) {
$http.get('http://localhost/storestuff/fetch.php')
.then(function successCallback(response) {
size = (response.data).length;
while(count < size) {
var date = response.data[count].date;
var content = response.data[count].content;
resultsService.addItem(date, content);
count++;
}
size = 0;
count = 0;
$scope.results = resultsService.getItems();
});
});
https://localbitcoins.com/sell-bitcoins-online/{contry code}/.json
this is the content i get from my moudle in php and i want to print this list in angular so i can live update it
app.controller('list', function($scope, $http, $interval) {
$http.get('http://localhost/mvcang/list_it/sell/SWISH')
.then(function(response) {
$scope.values = response.data.profile;
});
});
this is the angular code i use to get the info from my localhost
how do i do so it prints the list i get dublicate error and when i do .profile i get nothing!
have any idées or solutions please help:D
app.controller('list', function($scope, $http, $interval) {
$interval(function () {
$http.get('http://localhost/mvcang/list_it/sell/SWISH')
.then(function(data) {
data = data.data;
if($scope.phones != data){
$scope.phones = data;
}
});
}, 1000);
});
worked it out it way a that i didnt understand that it was data in the json object
I'm trying to create an app in AngularJS that aggregates data from multiple APIs. With some public APIs there are request limits and much of the data I want to pull is not updated very frequently, so only one request a month for a particular ID is necessary. To get past this, I've set up a Factory that first checks for a local file on the server, if it is not present, it then goes to the API and performs a GET request.
From there, once the request is complete, I want to save that file to the server with a name set by a field in the response.
I've found some examples using PHP with AngularJS but I'm not sure on how to save the JSON file with the dynamic name...or if this is even the best thing to do in order to avoid the request limits.
var apiUrl = 'https://example.com/api?userID=';
$http.get(apiUrl + $stateParams.userID).
success(function(data) {
$scope.content = data;
$scope.userID = data.userID
function(){
$http.post('saveJson.php', $scope.content).then(function() {
// log success
});
};
}).
error(function() {
// log error
});
PHP
<?php
$json = file_get_contents("php://input");
$file = fopen('/var/www/USERID.json','w+');
fwrite($file, $json);
fclose($file);
?>
If you do this in a service, and just call a method from a view button click, it would be more like this:
angular.module('app.services', [
])
.service('MyService', function ($http) {
var MyService = this;
this.aggregatedData = { content: [], filename: null };
this.apiUrl = 'https://example.com/api?userID=';
this.saveUrl = 'saveJson.php';
this.getData = function (url) {
return $http.get(url + $stateParams.userID).then(function (response) {
MyService.aggregatedData.content.push(response.data);
});
};
this.saveData = function (url, fileName) {
this.aggregatedData.filename = fileName;
return $http.post('saveJson.php', this.aggregatedData).then(function () {
// do something with the post response if desired
});
};
})
Then wire up buttons in your view to fetch and save by having the controller call the service methods.
I have an AngularJS app which has a mailer script written in PHP. I'm trying to refer to the PHP file via the angular $http service but I keep getting a 404 error when I try to use it via my contact form, in the corresponding controller, like so:
angular.module('myModule')
.controller('contactUsController', ['$scope', '$http', function ($scope, $http) {
$scope.formData = {};
$scope.submitted = false;
$scope.submit = function(contactform) {
console.log('Form data', $scope.formData);
$scope.submitted = false;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : "app/process.php",
data : $.param($scope.formData),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(data){
console.log(data);
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorEmail = data.errors.email;
$scope.errorTextarea = data.errors.message;
$scope.submissionMessage = "Sorry. Error sending message. Please try again.";
$scope.submission = true; //shows the error message
} else {
// if successful, bind success message to message
$scope.formData = {}; // form fields are emptied with this line
$scope.submissionMessage = "Thank you! Your message has been sent successfully.";
$scope.submitted = true; //shows the success message
}
});
} else {
}
}
}]);
So each time I invoke the submit() function by pressing the send button, the browser complains like so:
I've been searching around for an answer, but I haven't found one that could help me out.
I am using npm start to run my app. My project structure is as shown in the image below:
Any idea what could be going wrong? Any help is appreciated.
I am using a service to update a DB table.
myApp.factory('createGal', function ($http, $q)
{
return {
createGal: function ()
{
var deferred = $q.defer();
var newGalleryArray = {};
newGalleryArray.galleryName = 'New Image Gallery';
newGalleryArray.client = 245;
$http.post('/beta/images/create', {newGalleryArray: newGalleryArray}).success(function(data)
{
console.log(data);
deferred.resolve(data);
});
return deferred.promise;
}
};
});
PHP
public function create()
{
print_r($_POST);
}
The array is returning empty. Am i passing the array incorrectly?
Chrome Dev
Thanks
It's been a while since I've used PHP, but doesn't $_POST just contain request paramaters? $http.post sends data through a JSON payload, not request parameters. So, you'll need to use something like json_decode