AngularJS: replacing text in a foreach loop - php

New to Angular, I am accessing data from db via $http services and want to replace values in a textarea content matching words found in the db.
app.controller('myController', function($scope, $http) {
$scope.translate = function() {
$http
.get('translate.php')
.then(function(data){
var alldata = data.data;
angular.forEach(alldata, function(v,k) {
$scope.message = alldata.replace("\\b"+v.one+"\\b/gi",v.two);
});
}, function(data) {
// error handling
});
};
})
Textarea has ng-model of "message". It's not working and I'm getting an error:
TypeError: alldata.replace is not a function

try this,
app.controller('myController', function($scope, $http) {
$scope.message = '';
$scope.translate = function() {
$http
.get('translate.php')
.then(function(data){
var alldata = data.data;
angular.forEach(alldata, function(v,k) {
$scope.message = $scope.message.toString().replace("\\b"+v.one+"\\b/gi",v.two);
});
}, function(data) {
// error handling
});
};
})

Related

how do i send data to php from AngularJS controller?

I'm suffering a lot trying to do this, in words:
Trying to send a token to a myfunction.php so it can do it's job, then make it return 2 variables so I can use em in my Javascript controller (Made with angularJS).
So far i heard I should use $http, but I can't understand how I should do this
create an angularjs service and use it in your controller.
here is the service which can provide Create, read, write and delete functionality:
app.service("MainService", ['$http', function ($http) {
this.getItems = function (url) {
return $http.get(url);
};
this.getItem = function (id, url) {
return $http.get(url + "/" + id)
};
this.post = function (itemToCreate, url) {
var request = $http({
method: "post",
url: url,
data: itemToCreate
});
return request;
};
this.put = function (id, itemToChange, url) {
var request = $http({
method: "put",
url: url + "/" + id,
data: itemToChange
});
return request;
};
this.delete = function (id, url) {
var request = $http({
method: "delete",
url: url + "/" + id
});
return request;
};
}]);
next add this service as a dependency to your controller and use it's methods like this:
app.controller("MyCtrl", ['$scope', '$rootScope', '$timeout', 'MainService', function ($scope, $rootScope, $timeout, MainService) {
//Get All Items::
$scope.GetItems = function () {
var getAllItems = MainService.getItems("YOUR_API_URL_FOR_GET_ITEMS");
getAllItems.then(function (response) {
$scope.items = response.data;//use items with ng-repeat in you html code
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Create New Item::
$scope.Create = function () {
//CREATE an Object and send it via post request. for example:
var category = new CategoryObject($scope.Title, $scope.Description);
var promisePost = MainService.post(category, "YOUR_API_URL_FOR_Post_Item");
promisePost.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Edit an Item::
$scope.Edit = function () {
//CREATE an Object:
var category = new CategoryObject($scope.Title, $scope.Description);
//Then set it's Id
category.Id = $scope.CategoryId;
var promisePut = MainService.put($scope.CategoryId, category, "YOUR_API_URL_FOR_Put_Item");
promisePut.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
};
//Delete an Item::
$scope.delete = function (id) {
var promiseDelete = MainService.delete(id, "YOUR_API_URL_FOR_Delete_Item");
promiseDelete.then(function (response) {
alert("SUCCESSFUL");
})
.catch(function (response) {
alert("YOUR_ERROR_MESSAGE");
})
.finally(function () {
alert("AFTER_METHOD_EXECUTION");
});
}
}]);

Wordpress AJAX call response 0

I'm tryng to set up a panel, this one
The menu on the top calls different ajax functions in order to display a thumb. Clicking on the thumb you can see the details in the last box of the panel.
I have this php functions
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
function GetPostEnte(){
$catEnte = "loop_pb_ente";
get_template_part($catEnte);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostEnte', 'GetPostEnte');
function GetPostColl(){
$catColl = "loop_pb_coll";
get_template_part($catColl);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostColl', 'GetPostColl');
function GetPostMedia(){
$catMedia = "loop_pb_media";
get_template_part($catMedia);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostMedia', 'GetPostMedia');
function GetPostDetails(){
$pb_details = $_POST['postURL'];
get_template_part($pb_details);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostDetails', 'GetPostDetails');
And those are called by these ajax functions
$(document).delegate('h4.homus-partners-global-ajax[data-pb- cat*=pb_partner]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_partner";
var data = {
'action': 'GetPostPartner',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_ente]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_ente";
var data = {
'action': 'GetPostEnte',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_coll]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_coll";
var data = {
'action': 'GetPostColl',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('h4.homus-partners-global-ajax[data-pb-cat*=pb_media]', 'click', function(event) {
event.preventDefault();
var pb_cat = "pb_media";
var data = {
'action': 'GetPostMedia',
catURL : "loop_"+ pb_cat,
};
$.post(ajaxURL, data, function(response) {
$( 'ul.homus-partners-section-slide' ).html(response);
});
});
$(document).delegate('li.homus-partners-section-single', 'click', function(event) {
event.preventDefault();
var pb_post_id = $(this).data('post-id');
var data = {
'action': 'GetPostDetails',
postURL : "single_pb_post_details",
post_id: pb_post_id
};
$.post(ajaxURL, data, function(response) {
$( '.homus-partners-detalis' ).html(response);
console.log(pb_post_id);
console.log(data.postURL);
console.log(response);
});
});
the response that I have is always 0 even if the console of the last ajax call here above return the right postid. You can find the whole project in this repo
https://github.com/wanbinkimoon/homus-web.git
in the code
function GetPostPartner(){
$catPartner = "loop_pb_partner";
get_template_part($catPartner);
wp_die();
}
add_action('wp_ajax_nopriv_GetPostPartner', 'GetPostPartner');
instead of including the file by get_template_part paste the code here and then try

submit form to a php file with angular

i would like to submit my form to a php file
var myApp = angular.module('myApp',[]);
myApp.controller('FormController', function($scope, $http) {
$scope.task = {
group: 'fix',
showme: true,
select1: 'basique',
select2: 'micro',
select3: '1',
select4: '1',
select5: 'jour'
};
var server = 'http://localhost/myserver.php?cd=add';
var parameters;
$scope.submit = function(form) {
angular.forEach($scope.task, function(value, key) {
if(value) {
if(key === 'date') {
value = new Date(value).getTime();
}
parameters += '&'+key+'='+value;
}
});
console.log(server+parameters);
//$http.post(server+parameters)
//.success(function(result) {
// console.log("success", result);
//})
//.catch(function(error) {
// console.log("error", error);
//})
}
})
this is the codpen codepen
is this valid?
the result at should be http://localhost/myserver.php?cd=add'name='&'describe='
You are create query string using foreach() and pass with server url but. you are use $http.post(). you have to use $http.get() if you want pass with server url.
Below example with help
$scope.submitForm = function($valid)
{
myobject = {'email' : $scope.user.email, 'pass' : $scope.user.pass};
Object.toparams = function ObjecttoParams(obj)
{
var p =[];
for (var key in obj)
{
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
url: WSURL + '/login',
method: "POST",
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data, status, headers, config)
{
}
}).error(function (data, status, headers, config)
{
});
}

Why Error:input is undefined AngularJS

I am trying make an ajax request to php from angular js. But I am not getting the data I have sent by php file.
I'm getting this error:
Error:input is undefined
My source:
File view.html:
<div class="content-panel" >
<div class="content-panel-title">
<h2> Date : {{jalse.contentDate}}</h2>
</div>
<div>
<h4>{{jalse.contentAbstract}}</h4>
<div>
{{jalse.contentText}}
</div>
</div>
</div>
File app.js:
(function () {
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'contentsCtrl',
templateUrl: 'views/contents.php'
})
.when('/jalse/:jalseId', {
controller: 'recordsCtrl',
templateUrl: 'views/jalse.php'
})
.otherwise({redirectTo: '/'});
});
}());
File jalseFactory.js:
(function () {
'use strict';
var jasleFactory = function ($http, $q) {
var factory = {};
factory.getJalse = function () {
var deferred = $q.defer();
$http({method: 'GET', url: 'includes/records.php'}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
return factory;
};
jasleFactory.$inject = ['$http', '$q'];
angular.module('myApp').factory('jasleFactory', jasleFactory);
}());
File recordsCtrl.js:
(function () {
'use strict';
var recordsCtrl = function($scope, $routeParams , jasleFactory) {
var jalseId = $routeParams.jalseId;
$scope.records = jasleFactory.getJalse();
$scope.jalse = null;
function init() {
for (var i = 0, len = $scope.records.length; i < len; i++) {
if ($scope.records[i].contentID == parseInt(jalseId)) {
$scope.jalse = $scope.records[i];
break;
}
}
}
init();
};
recordsCtrl.$inject = ['$scope','$routeParams', 'jasleFactory'];
angular.module('myApp').controller('recordsCtrl', recordsCtrl);
}());
Your code is making an ajax and then assuming that the response is set the records variable, As you are dealing with async call you should call the method which are going to call on $scope.records inside its success.
Factory Method
factory.getJalse = function () {
return $http({method: 'GET', url: 'includes/records.php'});
};
Controller
(function() {
'use strict';
var recordsCtrl = function($scope, $routeParams, jasleFactory) {
var jalseId = $routeParams.jalseId;
jasleFactory.getJalse().success(function(data, status, headers, config) {
$scope.records = data.records;
init(); //this will fix your error.
}).
error(function(error, status, headers, config) {
console.log("error occured " + error)
});
$scope.jalse = null;
function init() {
for (var i = 0, len = $scope.records.length; i < len; i++) {
if ($scope.records[i].contentID == parseInt(jalseId)) {
$scope.jalse = $scope.records[i];
break;
}
}
}
//we will call this as soon as $scope.records gets filled
//init();
};
recordsCtrl.$inject = ['$scope','$routeParams', 'jasleFactory'];
angular.module('myApp').controller('recordsCtrl', recordsCtrl);
}());
Update
Your json is also not valid because it contains a malicious field which
"contentText": "1\ u0645\ u0637\ u0644\ u0628 < \/p>",
"3":"1\ u0645\ u0637\ u0644\ u0628 < \/p>",
If you remove this two field, you code will work as is
Working Plunkr

Error: [ng:areq] Angular when Ajax request to get data from php

I am trying make an ajax request to php from angular js. But I am not getting the data I have sent by php file.
I'm getting this error:
Error: [ng:areq] http://errors.angularjs.org/1.3.15/ng/areq?p0=recordsCtrl&p1=not%20a%20function%2C%20got%20undefined
My source:
File app.js:
(function () {
var app = angular.module('myApp', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'contentsCtrl',
templateUrl: 'views/contents.php'
})
.when('/jalse/:jalseId', {
controller: 'recordsCtrl',
templateUrl: 'views/jalse.php'
})
.otherwise({redirectTo: '/'});
});
}());
File view.html:
<div class="content-panel">
<div class="content-panel-title">
<h2> {{jalse.contentDate }}</h2>
</div>
<div ng-repeat="jalse in records">
{{jalse.contentDate }}
</div>
File jalseFactory.js:
(function () {
'use strict';
var jasleFactory = function ($http, $q) {
var factory = {};
factory.getJalses = function () {
var deferred = $q.defer();
$http({method: 'GET', url: 'includes/records.php'}).
success(function (data, status, headers, config) {
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
deferred.reject(data);
});
return deferred.promise;
};
return factory;
};
jasleFactory.$inject = ['$http', '$q'];
angular.module('myApp').factory('jasleFactory', jasleFactory);
}());
File recordsCtrl.js:
(function () {
'use strict';
var recordsCtrl = function ($scope, $http, $routeParams) {
var jalseId = $routeParams.jalseId;
$scope.records = jasleFactory.getJalse();
$scope.jalse = null;
function init() {
for (var i = 0, len = $scope.records.length; i < len; i++) {
if ($scope.records[i].contentID == parseInt(jalseId)) {
$scope.jalse = $scope.records[i];
break;
}
}
}
init();
};
}());

Categories