Where is wrong with below code? I can get the JSON result directly through any browser, it just don't want to show up in the dropdown list
I am just trying to populate from mysql database to combobox in ionic framework.
UPDATED SCRIPT
Still get empty in the dropdown list. Anyone?
addlist.html
<ion-header-bar align-title="center" class="bar-stable">
<h1 class="title">Add Lists</h1>
</ion-header-bar>
<ion-view>
<div class="list has-header padding">
<label class="item item-input item-select">
<div class="input-label">
Category
</div>
<div ng-controller="AddListCategoryCtrl">
<select ng-model="category" ng-options="x.category for x in data">
<option ng-repeat="x in data" value="{{x.id}}">{{x.category}}</option>
</select>
</div>
</label>
</div>
</ion-view>
controllers.js
angular.module('ionicApp.controllers', [])
.controller('AddListCategoryCtrl', function($scope, $http) {
var xhr = $http({
method: 'post',
url: 'http://www.mywebsite.com/api/listCat.php'
});
xhr.success(function(data){
$scope.data = data.data;
});
});
listCat.php
<?php
include 'db.php';
getById();
function getById() {
$sql = "SELECT id,category FROM tbl_category ORDER BY tbl_category.id";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->execute();
$category = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"category": ' . json_encode($category) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
?>
Related
I have successfully received the JSON object from an API, which is evident from a console.log code. Now, I want to display the various elements in that JSON file. For example, the JSON contains elements like "name" and "url". How do I display these individually, in an h1 HTML element, after clicking the submit button and fetching the JSON file. I'm a newbie and sorry if this is an obvious question, I'm kinda stuck and need help. Thank you in advance!
My HTML Code is:
<body ng-app="myApp">
<div ng-controller="UserCtrl">
Search : <input type="text" placeholder="Search Employees"
ng-model="formData.searchText"/> <br/><br/>
<button ng-click="getByID()">Submit</button>
{{response.data.name}}
</body>
The JS is:
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', function($scope, $http) {
var id = "my secret key comes here";
$scope.formData = {};
$scope.searchText;
$scope.getByID = function() {
$http.get("https://rest.bandsintown.com/artists/" + $scope.formData.searchText + "?app_id="+id)
.then(response => {
console.log(response.data.name)
})
}
});
Thank you so much in advance!
You need to use a variable to assign it with the response data and then use it in html. For example to display name from response.data.name:
<body ng-app="myApp">
<div ng-controller="UserCtrl as vm">
Search : <input type="text" placeholder="Search Employees"
ng-model="vm.searchText"/> <br/><br/>
<button ng-click="vm.getByID()">Submit</button>
<h1>{{ vm.name }}</h1>
</body>
In controller:
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', function($http) {
let vm = this;
var id = "my secret key comes here";
vm.searchText;
vm.name;
vm.getByID = function() {
$http.get("https://rest.bandsintown.com/artists/" + vm.searchText + "?app_id="+id)
.then(response => {
console.log(response.data.name);
vm.name = response.data.name;
})
}
});
Put the data on $scope:
$scope.getByID = function() {
var url = "https://rest.bandsintown.com/artists/" + $scope.formData.searchText;
var params = { app_id: id };
var config = { params: params };
$http.get(url, config)
.then(response => {
console.log(response.data.name)
$scope.data = response.data;
})
}
Then use the ng-repeat directive:
<body ng-app="myApp">
<div ng-controller="UserCtrl">
Search : <input type="text" placeholder="Search Employees"
ng-model="formData.searchText"/> <br/><br/>
<button ng-click="getByID()">Submit</button>
{{data.name}}<br>
<div ng-repeat="(key, value) in data">
{{key}}: {{value}}
</div>
</div>
</body>
For more information, see
AngularJS ng-repeat Directive API Reference
In my Laravel-5.8, I passed data from controller to view using JSON.
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first();
if(empty($child))
{
abort(404);
}
$maxscore2 = 1;
$maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore,
'maxscore2' => $maxscore2
]);
}
Route
Route::get('get/findScore','Appraisal\AppraisalGoalsController#findScore')
->name('get.scores.all');
View
<form action="{{route('appraisal.appraisal_goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option hidden value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<input type="text" id="max_score" value="max_score" class="form-control" >
</form>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#goal_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
console.log("Its Change !");
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
console.log(data.maxscore);
console.log(data.maxscore2);
$('#max_score').val(data.maxscore);
},
error:function(){
}
});
});
});
</script>
When I click on the dropdown on change, I got these:
Console:
textbox:
I need the direct value to be displayed on the text and not the JSON object as shown in the diagram. For example, only the 75 in the textbox.
How do I get this resolved?
Thank you.
You're seeing this result because maxscore is an object. You can either reference maxscore.max_score from JavaScript when adding to the element, or you can alternatively look at your eloquent code. You can likely replace the ->find() with calls to ->where() and ->first() as you did with $child
You can access the inner elements using something like this, or at least have an idea , and then you can print the elemet you need from the array...
var selectedValue = max_score.options[max_score.selectedIndex].innerHTML;
var arreglo = selectedValue.split(' ');
var arreglo1 = arreglo[0];
i have a table name stores and i have controller name is StoresController.php and model name is Stores.php and have a add.ctp file inside Stores folder but i an unable to insert data from form.here is my add.ctp file
<div class="row form-main">
<div class="panel panel-default">
<div class="panel-body">
<?php echo $this->Form->create('Store', array('class'=>"contact-
form"));
?>
<div class="form-group">
<div class="col-sm-6">
<?php
echo $this->Form->input('name',array('required'=>false,'class'=>"form-
control", 'placeholder'=>"Enter Name","label"=>false));
?>
</div>
<div class="col-sm-6">
<?php
echo $this->Form-
>input('address1',array('required'=>false,'class'=>"form-control",
'placeholder'=>"Enter Address1","label"=>false));
?>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="submit" value="Submit" class="btn
btn-success">
<button type="submit" class="btn btn-info">Cancel</button>
</div>
</div>
<?php echo $this->Form->end(); ?>
here is my StoresController.php
<?php
App::uses('AppController', 'Controller');
class StoresController extends AppController {
var $uses = array();
var $component = array("Common");
public $paginate = array();
public function add(){
$this->layout = 'user_layout';
$user_id = $this->UserAuth->getUserId();
$owner_id = $this->Common->getOwnerId($user_id);
if ($this->request->is('post')) {
$this->Store->create();
if ($this->Store->save($this->request->data)) {
$this->Flash->success(__('User has been Added'));
return $this->redirect(array('action' => 'add'));
} $this->Flash->error(__('Unable to add your post.'));
}
}
}
?>
and i am getting error Call to a member function create() on a non-object in controller
you should be using:
$this->Form->create('Store');
public function add(){
$this->layout = 'user_layout';
$user_id = $this->UserAuth->getUserId();
$owner_id = $this->Common->getOwnerId($user_id);
if ($this->request->is('post')) {
$this->Store->create('Store');
if ($this->Store->save($this->request->data)) {
$this->Flash->success(__('User has been Added'));
return $this->redirect(array('action' => 'add'));
} $this->Flash->error(__('Unable to add your post.'));
}
}
Yes, I solved the problem. There was a minor problem. I forgot the following line in the controller:
var $uses = array('Store');
I have a angular-ui modal, that is controlled with below controller:
var emailModal = angular.module('myApp.emailModal', ['ui.bootstrap', 'ui.bootstrap.tpls']);
emailModal.controller('ModalCtrl', ['$scope', '$uibModal', function ($scope, $uibModal) {
$scope.open = function () {
var modalInstance = $uibModal.open({
templateUrl: 'components/emailModal/emailModalView.html',
backdrop: true,
controller: 'modalInstanceCtrl'
});
}
}]);
emailModal.controller('modalInstanceCtrl', function ($scope, $uibModalInstance, $http) {
//create blank object to handle form data.
$scope.user = {};
//calling our submit function.
$scope.submitForm = function() {
//posting data to php file
$http({
method: 'POST',
url: 'components/emailModal/emailInsert.php',
data: $scope.user, //forms user object
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(data) {
if (data.errors) {
//showing errors.
$scope.errorEmail = data.errors.email;
} else {
$scope.message = data.message;
}
});
};
});
This is the actual modal view:
<form name="userForm" ng-submit="submitForm()">
<div class="modal-header">
<h3 class="modal-title">Register</h3>
</div>
<div class="modal-body">
<div class="form-group">
<label>E-Mail Address</label>
<input type="email" name="email" class="form-control" ng-model="user.email" placeholder="Email address" />
<span ng-show="errorEmail">{{errorEmail}}</span>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
Modal loads with no problem, bute once clicked to submit, nothing happens. I get no error once so ever in the console. What am I doing wrong? This is my PHP file, as well:
$errors = array();
$data = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
// checking for blank values.
if (empty($_POST['email']))
$errors['email'] = 'E-Mail erforderlich.';
if (!empty($errors)) {
$data['errors'] = $errors;
} else {
$data['message'] = 'The data should now be inserted into database!';
}
// response back.
echo json_encode($data);
?>
EDIT 1.
The event is triggered in Dev Tools - Network.
This is what I get:
Request URL: http://localhost:63342/url-to/emailInsert.php
Request method: POST
Remote address: 127.0.0.1:63342
Status code: 200 OK
Version HTTP/1.1
The page is not reloading on submit, at all, there is no error in Dev Tools - Console. It gives a OK status even though the email has not been ineserted into input, therefore it should print an error, which it doesn't do.
Any help is greatly appreciated.
I cant seem to login using these codes. Its not fetching the username and password on my database. Can you help me can i work with this? When login button clicked, it will validate if the username exist on the admin table and will check if the password is correct and status is Active. if so, it will go to the main page. if not it will stay on this page and display the error message. Please help
In Controller
function login()
{
//set validations
$this->form_validation->set_rules("username", "username", "trim|required|xss_clean");
$this->form_validation->set_rules("password", "password", "trim|required|xss_clean|callback_check_database");
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login_view');
//$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username or password!</div>');
}
else
{
//Go to private area
redirect('index','refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$user = $this->input->post('username');
//query the database
$result = $this->main_model->get_user($username, $password);
$this->display($result);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => $row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', '<div class="alert alert-danger text-center">Invalid username or password!</div>');
return false;
}
}
In model
function get_user($username, $password)
{
$sql = "select * from admin where username = '" . $username . "' and password = '" . md5($password) . "' and status = 'Active' limit 1";
$query = $this->db->query($sql);
if($query->num_rows() == 1)
{
return $query->result();
}
else
{
return false;
}
}
In View
<?php
$attributes = array("class"=>"login-form","id"=>"main","name"=>"main");
echo form_open("main/login", $attributes);?>
<body class="login-img3-body">
<div class="container">
<div class="login-wrap">
<p class="login-img">Login</p>
<div class="input-group">
<span class="input-group-addon"><i class="icon_profile"></i></span>
<input id="username" name="username" type="text" class="form-control" placeholder="Username" value="<?php echo set_value('username'); ?>" autofocus>
<span class="text-danger"><?php echo form_error('username'); ?></span>
</div>
<div class="input-group">
<span class="input-group-addon"><i class="icon_key_alt"></i></span>
<input id="password" name="password" type="password" class="form-control" placeholder="Password" value="<?php echo set_value('password'); ?>">
<span class="text-danger"><?php echo form_error('password'); ?></span>
</div>
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
<span class="pull-right"> Forgot Password?</span>
</label>
<button class="btn btn-primary btn-lg btn-block" id="btn_login" value="Login" type="submit">Login</button>
</div>
</form>
</div>
<?php echo form_close(); ?>
Make sure you load the helper
in __construct()
function __construct() {
parent::__construct();
$this->load->helper('form');
}
In Model
function get_user($username, $password)
{
$query = $this->db->query("select * from admin where username = '$username' and password = 'md5($password)' and status = 'Active' limit 1");
$result = $query->result_array();
$count = count($result);
if($count == 1)
{
return $result;
}
else
{
return false;
}
}
To submit form use this
echo form_submit('mysubmit', 'Submit Post!', 'class="btn btn-primary btn-lg btn-block"');