I have a problem with displaying data using AngularJS.
So my application is based on AngularJS and CodeIgniter 3.
I've created a validation in CodeIgniter written in the form, everything works.
public function create()
{
$this->form_validation->set_error_delimiters('','');
$this->form_validation->set_rules( 'login' , 'Imię' , 'required|min_length[3]' );
$this->form_validation->set_rules( 'email' , 'Email' , 'required|valid_email|is_unique[users.email]' );
$this->form_validation->set_rules( 'password' , 'Hasło' , 'required|matches[passconf]' );
$this->form_validation->set_rules( 'passconf' , 'Powtórz hasło' , 'required|matches[password]' );
if ( $this->form_validation->run())
{
$user = $this->input->post('user');
unset($user['passconf']);
$user['password'] = crypt($user['password'], config_item('encryption_key'));
$this->Users_model->create($user);
}
else
{
$errors['login'] = form_error( 'login' );
$errors['email'] = form_error( 'email' );
$errors['password'] = form_error( 'password' );
$errors['passconf'] = form_error( 'passconf' );
echo '{"records":' . json_encode( $errors ) . '}';
}
}
On the AngularJS side, I wanted errory to appear.
controllersAdmin.controller('userCreate', function( $scope, $http, $timeout ){
$scope.user = {};
$scope.user.role = 'user';
$scope.createUser = function( user ){
$http({
method: 'POST', url: 'api/admin/users/create/' ,
data: {
user : user,
login : user.login,
email : user.email,
password : user.password,
passconf : user.passconf
}}
).then(function ( errors ){
if ( errors )
{
$scope.errors = errors;
}
else
{
$scope.success = true;
$timeout(function(){
$scope.success = false;
$scope.user = {};
} , 3000 );
}
},function (error){
console.log('Blad we wczytywaniu danych');
});
}
});
I created $scope.errors = errors;
When I display it with {{errors}} - data is displayed.
{"data":{"records":{"login":"Pole Imię jest wymagane.","email":"Pole Email jest wymagane.","password":"Pole Hasło jest wymagane.","passconf":"Pole Powtórz hasło jest wymagane."}},"status":200,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"api/admin/users/create/","data":{"user":{"role":"user"}},"headers":{"Accept":"application/json, text/plain, */*","Content-Type":"application/json;charset=utf-8"}},"statusText":"OK","xhrStatus":"complete"}
However, when I give {{errors.login}}, the data is not displayed. Can I count on little help?
There's your problem. Login is not a property of the errors object but a sub property. It should be errors.data.records.login.
Related
I'm having some problems passing the data from my razor page to the server. It is passing NULL value from my abp.ajax({. Is there anything I'm missing from my ajax or the server-side code:
I'm using RAZOR PAGES ABP Framework 5.3
MY AJAX:
$("#frmDistrict").on("submit",
function (event) {
event.preventDefault();
const Url = $(this).attr("action");
const formData = $(this).serialize();
abp.ajax({
type: 'POST',
url: url,
data: JSON.stringify(formData)
}).then(function (result) {
if (data.isValid) {
if (data.IsNew) {
abp.notify.success(data.retmsg);
window.location.href = data.returl;
} else {
}
abp.notify.success(data.retmsg);
} else {
DisplayModelStateErrors(data.retmsg);
}
}).catch(function () {
alert("request failed :(");
});
});
MY SERVER CODE:
public async Task<JsonResult> OnPostAsync()
{
var rt = await Mediator.Send(new CreateDistrictCommand
{
District = district
});
if (rt.Failed) return new JsonResult(new { isValid = false, IsNew = true, retmsg =
rt.Message, sdata = rt.Data });
var retmsg = "District " + rt.Data.Name + " Created successfully.";
var returl = "/Districts/";
return new JsonResult(new { isValid = true, IsNew = true, retmsg, returl });
}
MY FORM
<form method="post" id="frmDistrict" >
<partial name="_AddEditDistrict" model="Model.District" />
</form>
If I use the standard ajax call
``$.ajax({ it works fine
but abp.ajax({ doesn't work
Many thanks
Zak
Using Angularjs here:
I have a form where user fills up some data and clicks save button to save data :
$scope.save = function (isValid) {
if (isValid) {
if (!$scope.checkBoxChecked) {
$scope.getExistingName($scope.uName);
}
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
}
else {
return false;
}
};
In the save method I am checking for uname, which gets it value by calling another api as below:
$scope.getExistingName = function (uName) {
myService.getDataFromApi(uName).then(function (data) {
var existingSetName = '';
if(data.length >0)
{
$scope.uName = data[i].uName;
}
});
}
The issue is $scope.uName in my Save button is always ''. I tried to debug and found out that the result from the $scope.getExistingName method
being is promise is deffered and returned after the orignal call. Because of which my $scope.uName is empty.
What am I missing here?
--Updated---
Save method:
var name = $scope.getExistingName($scope.uName);
Updated getExistingName
$scope.getExistingName = function (uName) {
return myService.getDataFromApi(uName).then(function (data) {
var existingSetName = '';
if(data.length >0)
{
return data[i].uName;
}
});
}
--This works--
if (!$scope.checkBoxChecked) {
$scope.getExistingName($scope.uName).then(function(data)
{
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
});
}
else
{
var name = $scope.uName != '' ? $scope.uName? : 'testuser';
//Call save api
}
I am posting the data to back-end using postman, which works fine. Using the same api I am trying to post the data through angular gives me the issue. But I understand that something going on wrongly between my form data with post process which i am not able to understand.
here is the post function:
.post(function( req, res ){
console.log(' called ', req.body ); 1. //getting all properties
var family = new Family();
family.username = req.body.username,
family.password = req.body.password,
family.familyLeader = req.body.familyLeader,
family.husband = req.body.husband,
family.wife = req.body.wife,
family.kids = req.body.kids;
console.log( 'family username', req.body.username ); 2.//undefined? not getting
family.save(function( err, newFamily ) {
if( err ) {
if ( err.code == 11000) {
return res.json({ success: false, message: 'A user with that username already exists. '});
}
else {
return res.send( err );
}
}
res.json({ message: 'Family created!', newFamily: newFamily });
});
})
There is 2 console I have in above call, in the first console I am getting the properties like this: ( I guess here is the issue, properties being as lable!? )
called { '{"username":"arif","password":"sadfdsa","familyLeader":"sadffsa","husband":"sadfsad","wife":"sadfsad","kids":2}': '' }
and the next console give the value like this:
family username undefined
I have removed header from $http request, and it works fine.
my code with issue is : with header
vm.createNewFamily = function() {
$http({
method : 'POST',
url : '/api/family',
data : vm.form,
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function ( data ) {
console.log('retured!', data );
})
}
and the solution is : ( header removed )
vm.createNewFamily = function() {
$http({
method : 'POST',
url : '/api/family',
data : vm.form
}).success( function ( data ) {
console.log('retured!', data );
})
}
Experts - Please confirm the solution!
I have a form with firstname, lastName, zipcode..etc, in addition to multi value input, in which the user check many checkboxes (which will be an array).
I wanna submit this form using angular js $http, and pass them as a query string, currently I have it like this:
firstName=test&lastName=test&homeZip=44551&carInterested=honda%2Cford%2Ctoyota
but my requirement is to be like this:
firstName=test&lastName=test&homeZip=44551&carInterested=honda&carInterested=ford&carInterested=toyota
here is my code:
$scope.signUp = function() {
$scope.formData.carInterested= $scope.selection
console.log ($scope.formData);
$http({
method : 'POST',
url : '/sonmeUr/../',
transformRequest: transformRequestAsFormPost,
data : $scope.formData
})
.success(function(data) {
console.log(data);
});
}
and in my service I have this:
.factory( "transformRequestAsFormPost", function() {
function transformRequest( data, getHeaders ) {
var headers = getHeaders();
headers[ "Content-type" ] = "application/x-www-form-urlencoded; charset=utf-8";
return( serializeData( data ) );
}
return( transformRequest );
function serializeData( data ) {
if ( ! angular.isObject( data ) ) {
return( ( data == null ) ? "" : data.toString() );
}
var buffer = [];
for ( var model in data ) {
if ( ! data.hasOwnProperty( model ) ) {
continue;
}
var value = data[ model ];
buffer.push(
encodeURIComponent( model ) +
"=" +
encodeURIComponent( ( value == null ) ? "" : value )
);
}
var source = buffer
.join( "&" )
.replace( /%20/g, "+" )
;
return( source );
}
}
);
I am trying to insert the data but getting fatal error i am seding from script ajax call .Please help me some one.Thanks in advance.Am using this for Wordpress plugin development
include_once($_SERVER['DOCUMENT_ROOT'].'/wordpress/wp-config.php' );
global $wpdb;
$table ='wp_mnggallery';
if(isset($_POST['img'])){
$img = $_POST['img'];
$back_image = $_POST['back_img'];
$url = $_POST['url'];
$data = array(
'id' => "",
'images' => "$img",
'back_image' => "$back_image",
'url'=>"$url"
);
$number_images = count($img);
//Inserting the data
$q = $wpdb->insert($table ,$data);
echo $img.' is updated succefully <br>';
}
Ajax call for this code sending from another page it was :
<script>
$('#submit').submit(function(event){
event.preventDefault();
var img = $('#img').val();
var backimage = $('#back_img').val();
if(img!=''&backimage!=''){
$.ajax({
type: "POST",
url: '<?php echo plugins_url(); ?>/mngimageeffects/post.php',
data: $('#submit').serialize(),
success: function( response ) {
$('#error').html( response );
$('#mng_img').append('<div class="col-md-4"><img src="'+img+'"width="100%"/></div><div class="col-md-2"><button class="btn btn-primary delete" id="delete">Upload</button></div>');
//delete = delete + 1;
$('#img').val('');
$('#back_img').val('');
$('#url').val('');
}
});
}else{
alert('Please Enter The Frent Image and Back Images Urls: ');
}
});
</script>
To use AJAX in Wordpress plugins
jQuery('#submit').submit(function(event){
event.preventDefault();
var img = jQuery('#img').val();
var backimage = jQuery('#back_img').val();
var url = jQuery('#url').val();
var data = {
action: 'submit_data',
img: img,
back_img: backimage,
url : url,
};
if(img!=''&backimage!=''){
jQuery.ajax({
type: "POST",
url: ajaxurl, // if its front end else use else ajaxurl
data:data,
dataType: 'html',
success: function( response ) {
alert(response+'sdfs')
jQuery('#error').html( response );
jQuery('#mng_img').append('<div class="col-md-4"><img src="'+img+'"width="100%"/></div><div class="col-md-2"><button class="btn btn-primary delete" id="delete">Upload</button></div>'); //delete = delete + 1;
jQuery('#img').val(''); jQuery('#back_img').val(''); jQuery('#url').val('');
},
error : function(data){
alert('Error while deleting.');
return false;
}
});
}
else{ alert('Please Enter The Frent Image and Back Images Urls: '); }
});
and in the PHP side,
add_action( 'wp_ajax_my_action', 'submit_data' ); // excutes for users that are logged in.
add_action( 'wp_ajax_nopriv_submit_data', 'submit_data' ); //executes for users that are not logged in.
function submit_data(){
global $wpdb;
$table ='wp_mnggallery';
if(isset($_POST['img'])){
$img = $_POST['img'];
$back_image = $_POST['back_img'];
$url = $_POST['url'];
$data = array(
'id' => "",
'images' => "$img",
'back_image' => "$back_image",
'url'=>"$url"
);
$number_images = count($img);
//Inserting the data
$q = $wpdb->insert($table ,$data);
echo $img.' is updated succefully <br>';
wp_die();
}
}
The url should be url: admin_url( 'admin-ajax.php' ), if its front end else use ajaxurl it will automatically include the necessary files
check
You shouldn't include the config file but wp-load.php when you want to use WordPress functions outside of WordPress
define( 'SHORTINIT', true );
require( '/path/to/wp-load.php' );
// use $wpdb after this