Passing data entered from directive to controller in AngularJS - php

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"

Related

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

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);
}
};
});

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>

Updated values are not being added to server database using ajax? [duplicate]

This question already exists:
Database values are not updating?
Closed 8 years ago.
I am using this code to call ajaxvote.php
$('.vote').click(function(){
$.ajax({
url: 'ajaxvote.php',
type: 'POST',
cache: 'false',
success: function () { alert("Success!"); } ,
error: function () { alert("Error!"); }});
var self = $(this);
var action = self.data('action');
var parent = self.parent().parent();
var postid = parent.data('postid');
var score = parent.data('score');
if (!parent.hasClass('.disabled')) {
if (action == 'up') {
parent.find('.vote-score').html(++score).css({'color':'orange'});
self.css({'color':'orange'});
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
else if (action == 'down'){
parent.find('.vote-score').html(--score).css({'color':'red'});
self.css({'color':'red'});
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
parent.addClass('.disabled');
This is the code from my webpage
<div class="item" data-postid="<?php echo $rows['ID'] ?>" data-score="<?php echo $rows['VOTE'] ?>">
<div class="vote-span">
<div class="vote" data-action="up" title="Vote up"><i class="fa fa-camera-retro"></i></div>
<div class="vote-score"><?php echo $rows['VOTE'] ?></div>
<div class="vote" data-action="down" title="Vote down"><i class="fa fa-camera-retro"></i></div>
</div>
This is my php code
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) && (isset($_POST['action']))) {
$postId = $_POST['postid'];
if (isset($_SESSION['vote'][$postId])) return;
$query = $mysqli - > query("SELECT VOTE from stories WHERE ID = $postId LIMIT 1");
while ($rows = mysqli_fetch_array($query)) {
if ($_POST['action'] === 'up') {
$vote = ++$rows['VOTE'];
} else {
$vote = --$rows['VOTE'];
}
$mysqli - > query("UPDATE stories SET VOTE = $vote WHERE ID = $postId ");
$_SESSION['vote'][$postId] = true;
}
}
}
I know I can connect to database because I can login. I also get the alert success I have set up above, However, the values are not updating in Database.
EDIT
I have added more Ajax code that I had already written.
When posting via ajax, you need to send through the data you actually want to post.
var postData = {name:"Mister",lastName:"Frodo"}; //Array
$.ajax({
url : "ajaxvote.php",
type: "POST",
data : postData,
success: function(data, textStatus, jqXHR)
{
//Handle response
},
error: function (e) {
// Handle error
}
});
In this case, the post ID and score needs to be grabbed. You also need to grab what kind of action is clicked (typically through a click event bind on the divs with class="vote". For example purposes, let's just set it to "up" for now:
var postId = $('div.item').attr('data-postid').val();
var score = $('div.item').attr('data-score').val();
var postData = {postId: postId, score: score, action: 'up'}
You can now post that "postData" to your ajaxvote.php.
Also, you can use jQuery's $.POST method
$.post("ajaxvote.php", { name: "Mister", lastName: "Frodo" } );
Now for parsing your form, have a look at jQuery's serialize which goes through your form takes each input's [name] attribute along with the value to create a data-string.
Example
name=Mister&lastName=Frodo
This is ideal for sending through with the "data" attribute in $.ajax. Have a look at this answer for more regarding jQuery's serialize.

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") .

How to pass data to controller to view using json in php?

I using codeigniter.I need to pass data to my controller to view somehow.I manage to pass view to controller(in view when drop-down selected value pass to controller using ajax)
this is my HTML code
<div class="form-group">
<label for="lastname" class="control-label">Your Packages</label>
<?php if(isset($tourbuddy_packages)){?>
<select id="itemType_id" class="form-control input-sm" name="tripbuddy_PackageTitle" onChange="disp_text()">
<?php
foreach ($tourbuddy_packages as $packages) {?>
<option value="<?php echo $packages['PackageID'] ?>"><?php echo $packages['PackageTitle']?></option>
<?php } ?>
</select>
<input type="hidden" name="PackageID" id="country_hidden">
<?php } else { ?>
<select class="form-control input-sm" name="tripbuddy_PackageTitle">
<option>Add Packages</option>
</select>
<?php } ?>
</div>
when drop-down selected a vale i pass data to controller by using ajax and java Script
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
Selected vale pass to tea method in controller
public function tea()
{
$this->session->set_userdata(array('tripbuddy_PackageID'=>$_POST['id']));
$package_data = $this->ci->package_model->get_package($_POST['id']);
$package_cat = $this->ci->package_model->get_package_categories();
$data = array();
$data['tourbuddy_selected_package'] = $package_data[0];
$data['tourbuddy_selected_package_cat'] = $package_cat;
//echo $data['package']['AlbumID'];
$data['tourbuddy_selected_photos'] = $this->photo->get_package_photo_stream($data['tourbuddy_selected_package']['AlbumID']);
//echo var_dump($data['photos']);
echo json_encode($data);
}
now I need to pass $data array to my view without refreshing view page how can i do this ? need a quick help
First you need to add the correct header to your tea() function as it will be returning json
public function tea()
{
header('Content-Type: application/json');
//...
}
Then you will need to add the dataType parameter to your ajax call
$("#itemType_id").change(function() {
$.ajax({
url : "feature/tea/",
method: "POST",
dataType: 'json', //Added this
data: "id=" + $(this).val(),
success: function(response) {
// handle
}
})
});
In your success function you will then be able to access the data like
success: function(response) {
response.tourbuddy_selected_photos.data
}
Controller
class Feature extends CI_Controller
{
public function tea()
{
$post = $this->input->post(); //do some form validation here
$model = Model::get($post); // do all business logic in the model
if(!$model){
//return a Response header rather than a 404View
return $this->output->set_status_header(404);
}
$responce = array(
'something' => $model->something
);
return $this->output
->set_content_type('application/json')
->set_output(json_encode($responce))
->set_status_header(200);
}
}
Untested Javascript
var URL = <?php echo site_url(); ?>// Global URL variable
(function($){
var Form = {
init : function(){
this.Form = $("form#formId"),
this.ItemType = this.Form.find("#itemtype_id");
this.ItemType.on('change', $.proxy(this.change, this));
},
/**
* -----------------------------------------------------------------
* Bind the ItemTypeId change event to this function using $.proxy
* Ajax return's a deffered(promise) so capture it, and do stuff
* -----------------------------------------------------------------
**/
change : function(event){
this.doAjax(event.target).then(
function( data ) // success
{
$(this).html('Success'); // $(this) -> context
},
function( reason ) //fail
{
switch(reason.code)
{
case 404:
default:
$(this).html('no results found');
break;
}
}
);
},
/**
* -----------------------------------------------------------------
* Make the ajax request a wait for it to return a promise
* -----------------------------------------------------------------
**/
doAjax : function( target ){
var data = {
id : target.id
}
return $.ajax({
cache: false,
url : URL + 'feature/tea/',
context : target,
method: "POST",
data : data,
dataType : 'json',
}).promise();
}
}
Form.init();
}(jQuery));

Categories