Error: StringServices.insertString(...) is undefined - php

I am New to angularjs, I am doing basic demo, in that I am inserting data into database using php and angularjs services and passing it to controller, the data is inserting into database but m getting error in console log. can anyone help me solve this error?
here is my app.js
var app = angular.module('myApp', [])
//controller
app.controller("myController",['$scope','StringServices', function($scope,StringServices){
$scope.User= {};
$scope.insert = function(User){
StringServices.insertString($scope.User, function(response){
if(response.FLAG === "_SUCCESS"){
console.log('Success');
}
else{
console.log('Error');
}
}).error(function(error){
console.error(error);
});
}
}])
//services
app.factory('StringServices', function($http){
return {
insertString: function(User){
var data = {name: User.name};
$http.post('http://localhost/anjali_services/server/insert.php',data)
.success(function(response){
return response;
});
}
};
});
index.html
<table>
<tr>
<td>Your Name</td>
<td><input type= "text" ng-model="User.name"></td>
</tr>
<tr>
<td></td>
<td><input type="button" ng-click="insert(User)" value="Insert"></td>
</tr>
</table>
insert.php
<?php
$db = new PDO("mysql:host=localhost;dbname=anjali;port=3306","root","");
$data = json_decode(file_get_contents("php://input"));
$name = $data->name;
$resp = array();
$q = "INSERT INTO udata (name) VALUES (:name)";
$query = $db->prepare($q);
$execute = $query->execute(array(
":name" => $name
));
if($execute == true){
$resp['FLAG'] = "_SUCCESS";
print json_encode($resp);
}else{
echo "ERROR";
}
?>
i am getting this error
See this screenshot

I have to say I can't figure out the root of your problem right-away but I'd suggest you at least return $http promise from your service and handle result using then/catch. At least I find this more easy to read & understand what's going on.
Anyway, modifying your example in this way seems to work just nice. Against mock REST service anyway.
HTML
<body ng-controller="myController as vm">
Your Name:
<input type= "text" ng-model="User.name">
<input type="button" ng-click="insert(User)" value="Insert">
</body>
JavaScript
var app = angular.module('myApp', [])
.controller('myController', function($scope, StringServices) {
$scope.User = {};
$scope.insert = function(User) {
StringServices.insertString(User)
.then(function(response) {
console.log('ok', response);
})
.catch(function(error) {
console.log('failed', error);
});
};
})
.factory('StringServices', function($http){
return {
insertString: function(User){
return $http.post('https://httpbin.org/post', { name: User.name });
}
};
});
Related plunker here https://plnkr.co/edit/MVUSeg

Your insertString function in StringServices takes only one argument that is User, however in your controller you are passing two arguments, i.e User and a function. thus no function insertString with two parameters.
You can have something like this:
var app = angular.module('myApp', [])
//controller
app.controller("myController",['$scope','StringServices', function($scope,StringServices){
$scope.User= {};
$scope.insert = function(User){
StringServices.insertString($scope.User, function(response){
if(response.FLAG === "_SUCCESS"){
console.log('Success');
}
else{
console.log('Error');
}
});
}
}])
//services
app.factory('StringServices', function($http){
return {
insertString: function(User, callbackFn){
var data = {name: User.name};
$http.post('http://localhost/anjali_services/server/insert.php',data)
.success(callbackFn);
}
};
});

Related

Passing data entered from directive to controller in AngularJS

I am trying to execute inline editing in angularJS, then update data entered in Mysql table, but i am new in angular and dont know how to handle the data entered (from directive) and passing it to controller to save it in DB, so in the codes below: the variables tid still empty after editing .. how can i store new id after inline editing to send them to database?
html:
<tbody>
<tr ng-repeat="item in ItemsByPage[currentPage]">
<td>
<div contentEditable="true" ng-model="tid" val='tid'>
{{item.id}}
</div>
<button ng-click="inlineupdate()" type="button">
Save
</button>
</td>
</tr>
</tbody>
in controller:
$scope.inlineupdate = function () {
var data = {
tid : $scope.val,
};
var request = $http({
method: "post",
url: "inlineupdate.php",
params: {
action: "post"
},
data: data
});
return( request.then( handleSuccess, handleError ) );
};
and the directive:
myApp.directive('contenteditable', function() {
return {
restrict: 'E',
scope: {
val : '='
},
link: function(scope, elm, ctrl) {
// view -> model
elm.bind('blur', function() {
scope.$apply(function() {
ctrl.$setViewValue(elm.html());
});
});
// model -> view
ctrl.render = function(value) {
elm.html(value);
};
// load init value from DOM
ctrl.$setViewValue(elm.html());
elm.bind('keydown', function(event) {
console.log("keydown " + event.which);
var esc = event.which == 27,
el = event.target;
if (esc) {
console.log("esc");
ctrl.$setViewValue(elm.html());
el.blur();
event.preventDefault();
}
});
}
};
and the inlineupdate.php file to update data in mysql:
<?php
header('Content-Type: application/json');
include 'connect.php';
$db = new database();
$db->setDb_name('training');
$db->connect();
if(isset($_POST)){
$id = $_POST['val'];
$name = 'name';
$data = $db->inlineupdate('user',array('id'=>$id),array('name'=>$name));
echo json_encode($data);
}
mysql_close();
?>
the console fires the notice that "Undefined index: tid in inlineupdate.php file"

Problems populating a select list with angular js and php

I am trying to populate a select list with data from my db (php & mysql). I am working with AngularJs and Angular Material. So for i am not able to show the data from the db in the list
db situation:
tblProjectType -> name of table
2 rows:
id_ProjectType
project_type
Any help or pointers would be great.
This is my html code:
<form ng-controller="AppCtrl">
<div layout="row">
<md-select-label>Project type</md-select-label>
<md-select ng-model="project_type" name="project_type" placeholder="Choose a project type" id="containerProjectType">
<md-option ng-repeat="projecttype in projecttypes" value="{{projecttype.id_ProjectType}}">{{projecttype.project_type}}</md-option>
</md-select>
</div>
</form>
The code of my app.js is:
var app = angular.module("DragDrop", ['ngMaterial']);
app.controller('AppCtrl', function($scope, $mdDialog, $http) {
$scope.projectTypeInfo = [];
var getProjectTypeFunction = function(succesFn, errorFn)
{
$http.get('db.php?action=get_ProjectType_info')// call to the server
.succesFn(function(data){
succesFn(data); //call the function passed into getProjectTypeFunction with the data from the server
console.log('Retrieved data from server');
})
.error(errorFn || function() {
console.log("Error in retrieving data from server");
})
}
this.reloadProjectTypeList = function()
{
getProjectTypeFunction(
/* success function */
function(data) {
//debugger;
$scope.projectTypeInfo = data;
//digest recycle
//if (!$scope.$$phase) { $scope.$apply(); }
},
/* error function */
function()
{
alert("Server load failed");
})
};
My php code is:
<?php
include('config.php');
//echo ('test' . $_GET['action']);
switch($_GET['action']) {
case 'get_ProjectType_info' :
get_ProjectType_info();
break;
}
/** Function to data from tblProjectType **/
function get_ProjectType_info(){
$qry = mysql_query('SELECT * from tblProjectType');
echo("test");
//echo(qry);
$data = array();
while($rows = mysql_fetch_array($qry))
{
$data[] = array(
"id_ProjectType" => $rows['id_ProjectType'],
"project_type" => $rows['project_type']
);
}
print_r(json_encode($data));
return json_encode($data);
}
?>
So for starters lets clean up your JS. We can reduce what you have to this:
var app = angular.module("DragDrop", ['ngMaterial']);
app.controller('AppCtrl', function($scope, $mdDialog, $http)
{
$scope.projectTypeInfo = [];
$scope.getProjectTypeFunction = function()
{
$http.get('db.php?action=get_ProjectType_info')
.success(function(data, status, headers, config)
{
$scope.projectTypeInfo = data;
console.log('Retrieved data from server');
console.log(data);
})
.error(function(data, status, headers, config)
{
console.log("Error in retrieving data from server");
console.log(data,status);
});
};
$scope.getProjectTypeFunction(); //-- call the function that invokes $http.get()
};
In PHP your function needs to echo the data via echo json_encode($data);, not return it (as stated by #Avalanche).
Now, your console should output something, but you need to remove console.log("test"); from your PHP as that will surely cause an error.
edit
Currently your repeat states:
<md-option ng-repeat="projecttype in projecttypes" value="{{projecttype.id_ProjectType}}">{{projecttype.project_type}}</md-option>
We have stored your data in $scope.projectTypeInfo therefore it needs to be modified to:
<md-option ng-repeat="projecttype in projectTypeInfo" ng-value="projecttype.id_ProjectType">{{projecttype.project_type}}</md-option>

Yii, Backbone save(), data did not passed through $_POST

This is my JavaScript in index.php:
MyModel = Backbone.Model.extend({
defaults: {
myID: "",
myName: ""
},
urlRoot: 'testAjaxAdd',
sync: function(method, model, options) {
options = options || {};
options['data'] = {};
options.data["myID"] = model.get("myID");
options.data["myName"] = model.get("myName");
options.data = JSON.stringify(options.data);
return Backbone.sync.apply(this, arguments);
}
});
MyView = Backbone.View.extend({
el: '.page',
render: function(){
var template = _.template($('#add-owner-template').html(), {});
this.$el.html(template);
},
events: {
'submit .create-owner-form': 'saveOwner'
},
saveOwner: function(events) {
var myName= $('input#myName').val();
var owner = new MyModel({
'myID': "111",
'myName': myName
});
owner.save({},{
success: function(model, response, options) {
console.log('success');
console.log(response); // show $_POST from actionSaveOwner in Controller
console.log(model.toJSON()); // show model
console.log(model.get('myID')); // show owner dbcID
console.log(model.get('myName')); // show owner userID
console.log(JSON.stringify(options)); // show options
console.log(options.data["myID"]); // this is shown undefined in console
console.log(options.data["myName"]); // this is shown undefined in console
},
error: function(model, response, options) {
console.log('error');
console.log(response);
console.log(model.toJSON());
}
});
}
});
I have put the code below in very first line within my javascript codes:
Backbone.emulateHTTP = true;
This is my html part of the form, it also a javascript template:
<script type="text/template" id="add-owner-template">
<form class='create-owner-form'>
<label>Name</label>
<input type="text" name="myName" id="myName"/>
<button type="submit" class="btn createcontbutton">Create</button>
</form>
</script>
This is my very simple action in Controller to test out if my backbone works or not:
public function actionTestAjaxAdd()
{
header('Content-type: application/json');
echo CJSON::encode($_POST);
}
However, this is what I see from console in POST tab:
Parameters application/x-www-form-urlencoded Do not sort
{"myID":"111","myName":"i...
But, the $_POST in controller action is nothing when i display it back in console from response.
I finally solved this myself using file_get_contents("php://input") .

Failed to use ajax transfer json data failed to insert with pdo statement and return undefined data

I tried to simply the code as much as possible so you can recreate the scenario.
I do not understand why the data insert will fail since both $('#qcategory').val() and $('#qtype').val(); are all simply value =1.
The ajax will be always return error with undefined data.
I do not understand where is the data went wrong after the json passed into php.
Does it mean that once the json data is passed into php, as I decoded and return it from php?
What eaxactly is the data returned with print $users->addQ($user)?
It has been days I stuck on this problem. I must missed something really really important. Please help me figure this out! Will really really appreciated!
If you do not understand the question, please inform me about what you are not clear of.
Vote down does not really help what so ever if its because you are not able to resolve the problem. Thank You
quiz_controller.js
$(function() {
$(document).on("click", "input#done-add-question", function(){ addQuestion(this); });
});
function addQuestion(element) {
alert('add_question ran!');
$('#indicator').show();
var User = new Object();
User.qcategory = $('#qcategory').val();
User.qtype = $('#qtype').val();
$.ajax({
type: "POST",
url: ".../controller/quiz_controller.php",
dataType: "json",
data: {
//"page":page, //page: value in the url php : currentpage: value in js
action: 'add_question',
user: userJson
},
success: function(data, textStatus) {
alert('add_question works!');
$('#indicator').hide();
},//success: function(data) END
error: function(jqXHR, XMLHttpRequest, textStatus, errorThrown,data) {
alert('add question error!');
alert(" textStatus " + textStatus+" errorThrown " + errorThrown +" XMLHttpRequest " + XMLHttpRequest);
alert("now the data is "+data)
console.log('1'+jqXHR+" |t|t| " +textStatus+" |e|e| " + errorThrown +" |x|x| " + XMLHttpRequest);
console.log('data = '+data);
} //error END
});//$.ajax() END
}
quiz_controller.php
<?php
function __autoload($className){
$classNameUrl="../model/$className.php";
include_once($classNameUrl);
}
$users=new Quiz("localhost","us","pw","equizz");
/*$_POST['action'] ='add_question';
$_POST['user'] ="fs";*/
if(!isset($_POST['action'])) {
print json_encode(0);
print " empty! not ready!";
return;
}
if(get_magic_quotes_gpc()){
$userParams = stripslashes($_POST['user']);
} else {
$userParams = $_POST['user'];
}
switch($_POST['action']) {
case 'add_question':
$user = new stdClass;
$user = json_decode($userParams );
print $users->addQ($user);
break;
}
exit();?>
/model/Quiz.php
<?php
class Quiz {
private $dbh;
public function __construct($host,$user,$pass,$db) {
$this->dbh = new PDO("mysql:host=".$host.";dbname=".$db,$user,$pass);
}
public function addQ($user){
$sth = $this->dbh->prepare("INSERT INTO eq_question1(`qCatID`, `qTypID`) VALUES (?, ?)");
$sth->execute(array($user->qcategory, $user->qtype));
return json_encode($this->dbh->lastInsertId());
}
}//class Quiz END
?>
HTML
<form>
<h1>New Question Settings</h1>
<p>
<label for="qcategory" class="" data-icon="u" > Category </label><br/>
<select id="qcategory" name="qcategory" required="required">
<option value="1">bb</option>
<option value="2">cc Operators</option>
</select>
</p>
<p>
<label for="qtype" class="" data-icon="u" > Type </label><br/>
<select id="qtype" name="qtype" required="required">
<option value="1">ab</option>
<option value="2">cd</option>
>
</select>
</p>
<p class="add-question button">
<input id="done-add-question" type="submit" value="Submit" />
</p>
</form>
Erorr console.log returned by Chrome Inspector
userJson = {"qcategory":"1","qtype":"1"} quiz_controller.js:214
1[object Object] |t|t| |e|e| undefined |x|x| error quiz_controller.js:257
data = undefined
in your quiz_controller.js try the following:
$(function() {
$(document).on("click", "input#done-add-question", function(){ addQuestion(this); });
});
function addQuestion(element) {
var User = new Object();
User.qcategory = $('#qcategory').val();
User.qtype = $('#qtype').val();
var userJson = JSON.stringify(User);
$('#indicator').show();
$.post('controller/quiz_controller.php',
{
action: 'add_question',
user: userJson
},
$('#indicator').hide(),
"json"
);
}
in quiz_controller.php remove:
if(!isset($_POST['action'])) {
print json_encode(0);
print " empty! not ready!";
return;
}
if(get_magic_quotes_gpc()){
$userParams = stripslashes($_POST['user']);
} else {
$userParams = $_POST['user'];
}
Replace with:
if(!isset($_POST['action'])) {
print json_encode(0);
return;
}
if(isset($_POST['user'])) {
$userParams = $_POST['user'];
}

AngularJS service for php files

i am trying to create a service for angular which should get the data from a php that generates a json. Right now my service looks like this
fixEvents.service('contactService', function($http, $q) {
this.getallContact = function() {
var json = $q.defer();
$http.get('models/contact.getall.json')
.success(function(data) {
json.resolve(data);
})
.error(function() {
json.reject();
});
return json.promise;
};
});
and my controller looks like this
fixEvents.controller('contactCtrl', function($scope, contactService) {
$scope.title = "CONTACT";
$scope.jsonContact = contactService.getallContact();
$scope.showMessage = function() {
alert($scope.jsonContact.length);
}
});
the problem is my jsonContact does not get any result. It seems to be undefined. Is there something i did wrong? And by the way is there a better way to do this ? Thank you, Daniel!
You have to use .then back in the controller to work with the data:
var jsonContactPromise = contactService.getallContact();
jsonContactPromise.then(function(data) {
$scope.jsonContact = data
}, function(error) {
console.log("ERROR: " + error);
});

Categories