its been two days since i start to learning about angular js.
its quite fun actually. fyi, im still using static data.
it means nothing when you cant manipulate database rite?
so i jump into the next step. connect it with my db. im using regular php.
if success, i will jump into next step, combining angular and php framework like laravel or codeigniter.
actually, its quit easy to retrieve data from database.
but, im here not to share that story, i found difficulties when trying to input it into database. i dont understand why. the point is i cant get the data from the form in html. im using factory in angular.
here is my add.html :
<h1>add newdata</h1>
new name :
<input type='text' ng-model='newdata.name'> <br>
new city :
<input type='text' ng-model='newdata.city'> <br>
<button ng-click='addData()'>submit</button>
here is my index.html :
//define dependency ngRoute module
var test = angular.module('testPeople', ['ngRoute']);
test.factory('factoryPeople', function($http) {
var factoryPeople= {};
factoryPeople.getPeople = function() {
return $http.get('data.php');
};
factoryPeople.addPeople = function() {
return $http.post('add.php');
};
return factoryPeople;
});
routes :
test.config(function($routeProvider) {
$routeProvider
.when('/add', {
templateUrl : 'add.html',
controller : 'add'
})
.when('/contact', {
templateUrl : 'contact.html'
})
.when('/second', {
templateUrl : 'index2.html'
})
.otherwise({redirectTo: '/'});
});
controller :
test.controller('add', function($scope, $http, factoryPeople){
$scope.tambahData = function() {
//bikin format file json, dari hasil tangkapan form di file add.html
databaru = {
name: $scope.newdata.name,
city: $scope.newdata.city
}
factoryPeople.addPeople(newdata).success(function(result) {
//update data using push method
$scope.listofname.push({
name: $scope.newdata.name,
city: $scope.newdata.city
});
//set form data empty again
$scope.newdata.name= '';
$scope.newdata.city = '';
alert(result);
});
here is my add.php :
<?php
header("Access-Control-Allow-Origin: *");
$host = "localhost";
$user = "root";
$pass = "";
$db = "angular";
$link = mysqli_connect($host, $user, $pass, $db) or die(mysqli_error($link));
// get input data
$data = json_decode(file_get_contents("php://input"));
// take value from array
$name= $data['name'];
$city= $data['city'];
// query insert
$sql = "insert into users (name , city) values ('$name', '$city') ";
// echo message
if(mysqli_query($link, $sql)):
echo"input success| name: $name| city: $city";
else: echo"input failed| name : $name | city: $city";
endif;
?>
if i run that script, data will always succesfully insert into database.
but the problems is $name and $city has no value.
i dont understand why.
am i wrong using php_get_contents or what?
can you guys tell me what should i do in order to get a better result?
Hope you guys can help me.
Thanks a lot.
You forgot to pass the parameters. Change your factory (addPeople() function):
factoryPeople.addPeople = function(data) {
return $http.post('add.php', data);
};
And then just use $_POST on the server like you usually (I guess) do
Related
I have error ->
"Failed to load resource: the server responded with a status of 405
(Method Not Allowed)"
when send Ajax data to PHP in larval.
(I made route)
Ajax code
function insertData()
{
var text = document.getElementById('humanText').value;
var user = document.getElementById('userName').innerText;
$.ajax({
type:"POST",
url: "insertContentData",
data:{text:text, user:user},
success: function(data){
alert(data);
}
});
document.getElementById('humanText').value = "";
};
insertData();
and my php code "insertContentData.php"
<?php
$data = $_POST['text'];
$user = $_POST['user'];
echo $data.", ".$user;
?>
why not work this?
Thanks for your help.
In the http world the "METHOD" normally used is "GET" which is simply pulling data from the server. When you want to send data from the user to the server you used "POST". These are the two most commonly used methods.
The errors says that the METHOD IS NOT ALLOWED. You are AJAX code shows that you are using the POST method.
In Laravel you need to define a route that allows for the POST method. So instead of Route::get($uri, $callback); it would be Route::post($uri, $callback); Some more information can be found in the Laravel Routing documentation. However I think you are missing some concepts based on the primitive PHP code you posted, that code should be inside a controller.
Try to run like this. I hope it works.
function insertData(){
var text = document.getElementById('humanText').value;
var user = document.getElementById('userName').innerText;
$.ajax({
type:"POST",
url: "insertContentData",
data:{text:text, user:user},
success: function(data){
alert(data);
}
});
document.getElementById('humanText').value = "";
};
window.onload = function(){
insertData();
}
<?php
$data = $_POST['text'];
$user = $_POST['user'];
echo $data.", ".$user;
?>
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();
});
});
index.php
<!doctype html>
<html ng-app="rjtApp">
<head>
<title>PHP MySQL API Consumed with AngularJS</title>
<script src="angular.min.js"></script>
<script src="data.js"></script>
</head>
<body>
<div ng-controller="GetUsers">
<table>
<thead><tr><th>Name</th></tr></thead>
<tbody>
<tr ng-repeat="user in users"><td>{{ user.name }}</td></tr>
</tbody>
</tfoot></tfoot>
</table>
</div>
</body>
</html>
api.php (this connection has no problem i tested.)
<?php
// set up the connection variables
$db_name = 'air';
$hostname = '127.0.0.1';
$username = 'root';
$password = '123456';
// connect to the database
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
// a query get all the records from the users table
$sql = 'SELECT USER_NAME FROM air_users LIMIT 1';
// use prepared statements, even if not strictly required is good practice
$stmt = $dbh->prepare( $sql );
// execute the query
$stmt->execute();
// fetch the results into an array
$result = $stmt->fetch( PDO::FETCH_ASSOC );
// convert to json
$json = json_encode( $result );
// echo the json string
echo $json;
?>
data.js
alert("this is connect");
var app = angular.module("rjtApp", []);
app.controller("GetUsers", function($scope, $http)
{
function getProject(){
$http.get("api.php").success(function(data){
$scope.projects = data; //the data are stored in projects
});
};
});
getProject();
My intention is to make a live validation to check database name exited, but I cannot even figure how to connecting AngularJS to database, what I have been doing wrong?
You are calling getProject from outside the controller, so it is undefined out there (it is local to the controller). So move that call inside:
alert("this is connect");
var app = angular.module("rjtApp", []);
app.controller("GetUsers", function($scope, $http)
{
function getProject() {
$http.get("api.php").success(function(data) {
$scope.projects = data; //the data are stored in projects
});
};
getProject(); // moved this line
});
Then, the $http service should run. Technically, you should be using a GET request, but it will still work the same way with POST. I do want to point out that you are not currently using projects anywhere in your page - so you will only see the data in the network console.
It looks to me like your big issue here is that you are using $http.post instead of $http.get. Post is designed for submitting changes and new objects (think submitting a form), while get is designed for grabbing output.
So, you should be able to change
$http.post("api.php").success(function(data){
$scope.projects = data; //the data are stored in projects
});
to
$http.get("api.php").success(function(data){
$scope.projects = data; //the data are stored in projects
});
This will store the output of loading api.php (as if you visited the website yourself rather than in code) in projects. A useful debug tip is to put
alert(JSON.stringify(varname))
in your code if you wish to debug. This will pop up an alert containing the JSON contents of your variable as a string. In your case this would be:
alert(JSON.stringify($scope.projects)).
I apologize for any code formatting issues. I'm new to the stack overflow system.
my view contains the following code
this.keypadDisplay = Ext.create('Ext.field.Text', {
xtype:'textfield',
disabled: true,
value: ''
});
my ajax request code is
handler: function(b, e) {
var thisUser = this.getValue();
alert(thisUser);
//params[this.getSubmitParamName()] = this.getValue();
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: thisUser,
method:'GET',
success: function(response, opts){
var text = response.responseText;
console.log(response.responseText);
alert(thisUser);
//alert(this.getValue());
//alert('Value: ' + this.getValue());
Ext.Msg.alert('success', text);
},
failure: function(response, opts){
Ext.Msg.alert('Error','Error while submitting the form');
console.log(response.responseText);
},
scope: this
});
}
here i'm getting the "this.getValue" successfully. i want to insert to this.getValue to the code table.
my code.php contains the following code
<?php
$con = mysql_connect("localhost","root","");
mysql_select_db('form',$con);
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisUser.value']."')";
if(mysql_query($insert))
{
echo('values inserted successfully');
}
else
{
echo('failure' . mysql_error());
}
?>
here im getting the error as "Undefined index:thisUser.Value in .../keypadapp/code.php " on line 5.
can anyone help me to ? thanks in advance...
Assign param value to variable in ajax call:
Ext.Ajax.request({
url:'http://localhost/sencha2011/keypadapp/code.php',
params: 'thisuser='+thisUser,
Then in php, access the value:
$insert = "INSERT INTO codetable(password) VALUES ('".$_GET['thisuser']."')";
Try changing $_GET['thisUser.value'] to $_GET['thisUser_value'] dots in $_GET and $_POST get converted to underscores in PHP. See this for more info https://stackoverflow.com/a/68742/589909
Update
Looking closer at your code you can't get javascript values of an object in php like you are doing. I assume that thisUser is an object. So when passing it as a param its properties will be posted to the server individually. So if it had a property called foo you would get it like so. $_GET['foo']; also you could dump the get request to see what was sent. var_dump($_GET);
I'm trying to post some data to a function that will do a mysql insert. Nothing fancy about that. but I can get the thing to work and my question is where should I be telling jQuery to post to and will it honor php includes?
This is what I have
include_once 'modules/interviews/helper.php';
if($link == 'my_interviews'){
include_once 'modules/interviews/my_interviews.php';
} elseif($link == 'interview_panel'){
include_once 'modules/interviews/interview_panel.php';
}
Above is my index.php, which loads in the page where the form is submitted
$('.addinote').click(function() {
var app = $(this).attr("data-app"),
user = $(this).attr("data-subi"),
txt = $('#' + app).val();
if(txt === ''){
alert('Whoops, did you enter something?');
}else{
var params = {};
params['user_id'] = user;
params['app_id'] = app;
params['inote'] = txt;
params['subinote'] = '1';
$.post('http://localhost/gem/modules/interviews/index.php', params,
function(data){
if(data){
}
else{
alert('Whoops, there was a problem, please try again!');
}
});
}
helper.php contains this...
if(isset($_POST['subinote'])){
$apply->inote();
}
and the class contains this....
function inote(){
$query = "INSERT INTO `app_notes` (`user_id`, `application_id`, `inote`)
VALUES ('{$_POST['user_id']}', '{$_POST['app_id']}',
'{$_POST['inote']}')";
$GLOBALS['DB']->insertQuery($query);
}
Where should I be posting to?
You should be posting to index.php if this is the one reading the $_POST variable.
Also you should be using relative url's for example if helper.php is in the same directory as your html file use ./index.php or simply index.php as your post url. I prefer the former as it states explicitly what you intended.