Passing POST data from ionic framework to CodeIgniter Rest API - php

From last two days i'm try to post the data from my Ionic app to CodeIgniter rest api using $http. But my post data goes empty. I refere some link. But failed to seolve. Below is my code.
My ionic view
<div class="list">
<label class="item item-input item-md-label" placeholder="Username" highlight-color="balanced" type="text">
<input class="md-input" type="text" ng-model="user.name">
<span class="input-label">Username</span>
<div class="hightlight hightlight-calm"></div>
</label>
<label class="item item-input item-md-label" placeholder="Password" highlight-color="energized" type="password">
<input class="md-input" type="password" ng-model="user.password">
<span class="input-label">Password</span>
<div class="hightlight hightlight-calm"></div>
</label>
</div>
<div class="padding">
<button ng-click="doLogin(user)" class="button button-full button-assertive ink">Login</button>
</div>
Ionic Controller code :
.controller('LoginCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk, $http, baseUrl) {
$scope.$parent.clearFabs();
$timeout(function() {
$scope.$parent.hideHeader();
}, 0);
ionicMaterialInk.displayEffect();
$scope.doLogin = function(user) {
$http({
method : "POST",
url : "http://localhost/vas_api/index.php/api/User/index/"+user.name
}).then(function mySucces(response) {
console.log(response)
});
}
})
CodeIgniter controller code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
require APPPATH . '/libraries/REST_Controller.php';
use Restserver\Libraries\REST_Controller;
class User extends REST_Controller {
public function index_post() {
if(!$this->input->post('name')) {
$this->response(null, 400);
}
$data = array(
'name' => $this->input->post('name')
);
$id = $this->User_model->insertUser($this->input->post('name'));
if(!is_null($id)) {
$this->response(array('response' => $id), 200);
} else {
$this->response(array('response', 'Null values'), 400);
}
}
}
Codeigniter model code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class User_model extends CI_Model {
function insertUser($data) {
$this->db->insert('user',array('name' => $data));
$userId = $this->db->insert_id();
return $userId;
}
}
?>
Please help me to solve this issue. I'm using advance CodeIgniter version 3 Thanks in advance

Please use following approach
$http({
method : "POST",
url : "http://localhost/vas_api/index.php/api/User/index/",
data:{ name:user.name }
}).then(function(response) {
console.log(response)
});

Related

Json_encode array function Error

I have make an matrix for boxing products in to different boxed based on that assumption:
I am using PHP as an server side language and jQuery Ajax for transmitting the data.
Front end code: <input id="no_of_post" name="no_of_post" type="text" class="form-control" onChange="return test()">
<div class="col-sm-3">
<label for="lastname">Weight Box</label><br>
<input id="weight_box" name="weight_box" type="text" class="form-control">
</div>
<div class="col-sm-3">
<label for="lastname">Plate Box</label><br>
<input id="plate_box" name="plate_box" type="text" class="form-control">
</div>
<div class="col-sm-3">
<label for="lastname">Two Pipe Box</label><br>
<input id="two_pipe_box" name="two_pipe_box" type="text" class="form-control">
</div>
<div class="col-sm-3">
<label for="lastname">Four Pipe Box</label><br>
<input id="four_pipe_box" name="four_pipe_box" type="text" class="form-control" onChange="return test()">
</div>
<div class="col-sm-3">
<label for="lastname">No. Of Box</label><br>
<input id="no_of_box" name="no_of_box" type="text" class="form-control">
</div>
<script type="text/javascript">
function test(){
var no_of_post=$('#no_of_post').val();
$.ajax({
type: "POST",
url: '<?php echo base_url()?>Test/test1',
data: {no_of_post:no_of_post},
//data: $('#enqCapture').serialize(),
success: function(resp) {
// toastr.success('Success - Dispatch Detail Prepared');
$("#weight_box").val(resp[1]);
$("#plate_box").val(resp[3]);
$("#two_pipe_box").val(resp[5]);
$("#four_pipe_box").val(resp[7]);
$("#no_of_box").val(resp[9]);
console.log(resp);
},
error: function (jqXHR, exception) {
toastr.error('Error - Something wrong try again.');
}
});
return false;
}
</script>
And My Controller code is:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Test extends MY_Controller{
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->model('Enquiry_model');
$this->load->model('Quotation_model');
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('User');
$this->load->model('Main_model');
$this->load->model('Master_model');
$this->is_logged_in();
}
public function index(){
$data['user_data']=$this->is_logged_in();
$this->load->view('admin1/quotation/test',$data);
}
public function test1(){
$no_of_post=$this->input->post('no_of_post');
//$no_of_post."<br>";
$weight_box=0;
$plate_box=0;
$two_pipe_box=0;
$four_pipe_box=0;
if($no_of_post==1){
$weight_box=1;
$two_pipe_box=1;
$total_box=floor($weight_box+$two_pipe_box);
}else{
$weight_box=round($no_of_post/2);
$plate_box=ceil(($no_of_post/5));
$four_pipe_box=$no_of_post/4;
if (strpos($four_pipe_box,'.') !== false) {
$four_pipe_box1=floor($four_pipe_box);
$fraction=$four_pipe_box-$four_pipe_box1;
if($fraction>=.60){
$four_pipe_box=ceil($no_of_post/4);
$total_box=floor($weight_box+$plate_box+$four_pipe_box);
}else{
$four_pipe_box=floor($no_of_post/4);
$two_pipe_box=1;
$total_box=floor($weight_box+$plate_box+$four_pipe_box+$two_pipe_box);
}
}else{
$four_pipe_box=ceil($no_of_post/4);
$total_box=floor($weight_box+$plate_box+$four_pipe_box);
}
}
$arr= array($weight_box,$plate_box,$two_pipe_box,$four_pipe_box,$total_box);
/*$arr[0]=$weight_box;
$arr[1]=$plate_box;
$arr[2]=$two_pipe_box;
$arr[3]=$four_pipe_box;
$arr[4]=$total_box;*/
//$arr[0] = "Mark Reed";
//$arr[1] = "34";
//$arr[2] = "Australia";
//echo json_encode($arr);
echo json_encode(array_values($arr));
//exit();
}
}
?>
But it is return wrong result in text box.
Use:
dataType : 'json',
encode : true
After:
data: {no_of_post:no_of_post},
Because you are returning json encoded data from the controler.

Recieve JSON data in CodeIgniter PHP framework from React - AJAX

I have my React app running on localhost:3000
My CodeIgniter API running on localhost:8000
I'm trying to send an AJAX post request and pass data in JSON format but don't know how to receive it in my controller... Here is what I have
REACT
import React, { Component } from 'react';
import Request from 'superagent';
class App extends Component {
constructor(){
super()
this.state = {
email: '',
password: ''
}
}
updateEmail(e){
this.setState({
email: e.target.value
})
}
updatePassword(e){
this.setState({
password: e.target.value
})
}
createUser(e){
var query = 'star';
e.preventDefault()
console.log(this.state.email)
var url = `http://localhost:8888/CI-React-API/React_api/create`;
Request.post(url)
.set('Content-Type', 'application/json')
.send({ email: 'test' })
.then((response) => {
console.log(response)
});
}
render() {
return (
<div className="App">
<div className="App-header">
<form onSubmit={this.createUser.bind(this)}>
<input type="text"
name="email"
onChange={this.updateEmail.bind(this)}
value={this.state.email}
placeholder="email"/>
<br/>
<input type="text"
name="password"
value={this.state.password}
onChange={this.updatePassword.bind(this)}
placeholder="password"/>
<br/>
<input type="submit" value="submit"/>
</form>
</div>
</div>
);
}
}
export default App;
CodeIgniter
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class React_api extends CI_Controller {
public function create()
{
$obj=json_decode(file_get_contents('php://input'), true);
// $email = $this->input->post('email');
// echo $email;
var_dump(file_get_contents('php://input'));
die;
// IDEA $this->load->view('welcome_message');
}
}
Change url
var url = `http://localhost:8888/CI-React-API/React_api/create`;
to
var url = 'http://localhost:8888/react_api/create';
OR
var url = '<?php echo base_url("react_api/create");?>';
And load url helper in controller as below:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class React_api extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper('url');
}
public function create()
{
$email = $this->input->post('email');
echo $email;
$obj=json_decode(file_get_contents('php://input'), true);
var_dump(file_get_contents('php://input'));
die;
// IDEA $this->load->view('welcome_message');
}
}

$this-db-update work but Database not change

I am currently working on a program that uses php jquery and bootstrap, the update function, there is a an error so that database does not change but the script is running normally, Maybe somebody able to help me where is my mistake? thank you
My controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Subbidang extends CI_Controller {
public function index()
{
$this->load->model('model_subbidang');
$this->model_security->getsecurity();
$isi['content'] = 'Subbidang/tampilan_datasubbidang';
$isi['judul'] = 'Master';
$isi['sub_judul'] = 'Sub Bidang';
$isi['data'] = $this->db->get('tsubbidang');
$this->load->view('tampilan_home',$isi);
}
public function tambah()
{
$this->load->model('model_subbidang');
$this->model_security->getsecurity();
$isi['content'] = 'Subbidang/form_tambahsubbidang';
$isi['judul'] = 'Master';
$isi['sub_judul'] = 'Sub Bidang';
$this->load->view('tampilan_home',$isi);
}
public function simpan()
{
$this->model_security->getsecurity();
$this->load->model('model_subbidang');
$key['IDSubBidang'] = $this->input->post('kode');
$data['IDSubBidang'] = $this->input->post('kode');
$data['IDBidang'] = $this->input->post('bidang');
$data['NamaSubBidang'] = $this->input->post('subbidang');
$query = $this->db->get_where('tsubbidang',$key);
if ($query->num_rows()>0)
{
$this->db->update('tsubbidang',$key,$data);
//echo "Data Berhasil Diubah";
echo "Update";
}
else
{
$this->db->insert('tsubbidang',$data);
//xecho "Data Berhasil Disimpan";
echo 'Insert';
}
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
My View
<script type="text/javascript">
$(document).ready(function(){
$("#simpan").click(function(){
var string = $("#my-form").serialize();
//alert(string);
$.ajax({
type : 'POST',
url : '<?php echo site_url();?>/subbidang/simpan',
data : string,
success : function(data){
alert(data);
}
});
});
});
</script>
<form class="form-horizontal" name="my-form" id="my-form">
<div class="control-group">
<label class="control-label"bidang</label>
<div class="controls">
<select name="bidang" id="bidang">
<option value="">-Pilih-</option>
<?php
$bidang = $this->db->get('tbidang');
foreach ($bidang->result() as $row) {
?>
<option value="<?php echo $row->IDBidang;?>"><?php echo $row->Bidang;?> </option>
<?php };?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label">Kode Sub Bidang</label>
<div class="controls">
<input type="text" name="kode" id="kode" palceholder="kode" class="span3">
</div>
</div>
<div class="control-group">
<label class="control-label">Sub Bidang</label>
<div class="controls">
<input type="text" name="subbidang" id="subbidang" palceholder="Sub Bidang" class="span3">
</div>
</div>
<div class="controls">
<button type="button" name="simpan" id="simpan" class="btn btn-primary btn-small"> Simpan</button>
</div>
My Model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Model_subbidang extends CI_model {
public function gettampildatasubbidang($key)
{
$this->db->where('IDBidang',$key);
$query = $this->db->get('tbidang');
if($query->num_rows()>0)
{
foreach ($query -> result() as $row) {
$hasil = $row->Bidang;
}
}
else
{
$hasi='';
}
return $hasil;
}
public function getlistsubbidang()
{
return $this->db->get('tbidang');
}
public function getdata($key)
{
$this->db->where('IDBidang',$key);
$hasil = $this->db->get('tBidang');
return $hasil;
}
public function getupdate($key,$data)
{
$this->db->where('IDBidang',$key);
$this->db->update('tBidang',$data);
}
public function getinsert($key,$data)
{
$this->db->insert('tBidang',$data);
}A
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
The echo work fine but the database doesnt change. The Insert function also work fine
You need to pass right data to update function
change
$this->db->update('tsubbidang',$key,$data);
to
$this->db->where('IDBidang', $key);
$this->db->update('tsubbidang',$data);
and Everything will be fine.
and one more thing is that you must do functionality related to database in your model not directly in controller, it is not according to the MVC structure. it destort it. and if you done everything seperetly then it is easy to understand and clear to everyone who code after you on the same.

CodeIgniter Ajax is not working

CodeIgniter Ajax is not working for me.
This is what I have tried so far.
v_login.php
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('#username').val(),
password : $('#password').val(),
ajax : '1'
};
$.ajax({
url: "<?php echo site_url('c_login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#message').html(msg);
}
});
return false;
});
});
</script>
<div class="container">
<div class="jumbotron">
<?php
$attributes = array('class' => 'form-signin');
echo form_open('c_login', $attributes); ?>
<h2 class="form-signin-heading">VMS Login System</h2>
<input type="username" name="username" id="username" class="form-control" placeholder="Username" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" required>
<input class="btn btn-primary" type="submit" id="submit" value="Login">
<input class="btn btn-primary" type="reset" value="Cancel">
<?php echo form_close(); ?>
<div id="message">
</div>
</div>
</div>
C_login.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class C_login extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->helper('url');
}
function index() {
$this->load->view('include/header');
$this->load->view('v_login');
$this->load->view('include/footer');
}
function ajax_check() {
if($this->input->post('ajax') == '1') {
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user == '1') {
echo 'login successful';
} else {
echo 'unknown user';
}
}
}
}
}
/* End of file c_login.php */
/* Location: ./application/controllers/c_login.php */
m_access.php
<?
class M_access extends CI_Model {
public function check_user($username,$password) {
$this->query = $this->db->select('COUNT(*)')->from('users')->where(array('username'=>$username,'password'=>$password))->limit(1)->get();
return $this->query->row_array();
}
}
I don't know what's wrong, I have already set up config.php and routes. But it's not working at all. Any ideas? Help is much appreciated. Thanks.
After a long chat with OP the solution is this
Your model
class M_access extends CI_Model {
public function check_user($username,$password) {
$args = array(
'username' => $username,
'password' => $password
);
$query = $this->db->select('*')->from('users')->where($args)->get();
if($query->num_rows()) {
return $query->row_array();
}
return false;
}
}
In your controller, use
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'), $this->input->post('password'));
if($user) {
// right user
}
else {
// wrong user
}
Don't need to send ajax:1 because jQuery sends a request header to server, like this
X-Requested-With': 'XMLHttpRequest'
and in CodeIgniter you may check for ajax request using
if($this->input->is_ajax_request()){
// it's an ajax request
}
Also, you asked for a gif loader to shw, so this could be used as
$('#submit').click(function() {
var form_data = { ...};
// show the gif loader
$.ajax({
...
data: form_data,
success: function(msg) {
// hide the gif loeader
$('#message').html(msg);
}
});
});
Update : For inserting an image you may check this fiddle example, like
$('#submit').click(function(e){
e.preventDefault();
var loader = $('<img/>', {
'src':'url_of_the_image',
'id':'ajax_loader'
});
loader.insertAfter($(this));
});
and to remove the image in your success callback, you may use
$('#ajax_loader').remove();
error 404 due to the calling path because file name with "C" and you calling it with "c", rather than that
in my opinion you need to have a deeper look at codeigniter form validation helper
before you try the ajax call
once you did it server side perfectly & if you still want to validate using ajax , make another function as a webservice only for this purpose along the orignal server side validation function , it'd be something like that
function ajax_check(){
$username_check=true;
//your code goes here to check if username unique or not and result assigned to $username_check
if(!$username_check){
echo json_encode('fail');
return;
}
echo json_encode('success');
}

how to get value by jQuery+Codeigniter and show in input field?

I got some problem about receive value from server , and show the value in input .
Sometimes, if I want to show the value in page, I will use the POST method, then set the input'ID in controller and model, and use foreach() in page you want to show , therefore the work is done.
But, if I want to show the value in input'field, how I need to do for it ?
I write some code for this and try to use AJAX receive and show in input, it's not working,can everybody help me to solve this problem , please....... Σ(  ̄□ ̄;)
I try to create a new model and a new page for it, there is a very simple form, the code is below:
view:kungfu.php
<div style="width:250px;float:left;">
<form id="pr_form" action="<?php echo site_url();?>/static_data/kungfu_act" method="post">
NUM:<input id="num" name="num" type="text" class="field_set"><br>
NAME:<input id="name" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" name="kungfu" type="text" class="field_set"><br>
</div>
<div style="float:left;">
<span id="loading" style="display:none">Loading!!</span><br>
<span id="complete" style="display:none">Complete!!</span>
</div>
<div style="clear:both;height:50px;padding-top:10px">
<input id="query" name="query" class="btn" type="button" value="QUERY">
</div>
</form>
</div>
model:pr_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Pr_model extends CI_Model {
function __construct()
{
parent::__construct();
$this->load->helper('form');
$this->load->helper('html');
$this->load->database();
}
function pr_query()
{
$query=$this->db->get("kungfu_table");
return $query->result();
}
}
controller:static_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function kungfu()
{
$this->load->view('kungfu');
}
public function kungfu_query()
{
$this->load->model("pr_model");
$data = array(
"kungfu" =>$this->pr_model->pr_query()
);
echo json_encode($data);
}
}
if I want to show the value in normal page , I will use foreach() but I don't know how to show in input, I try to use getjson() , but no working . can somebody teach me ?
// 2013/11/30 re-edit
dear Suleman:
I try to write some code about .ajax() , but I still got problem , the other section was the same , but the controller had be change :
controller:static_data.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Static_data extends CI_Controller {
public function kungfu()
{
$this->load->view('kungfu');
}
public function kungfu_maxquery()
{
$this->load->model("pr_model");
$data = $this->pr_model->pr_maxquery();
$max=json_encode($data);
echo $max;
}
}
model:pr_model.php
function pr_maxquery()
{
$this->db->select_max("num");
$maxquery=$this->db->get("kungfu_table");
return $maxquery->result();
}
and I try to edit a js file for .ajax(),but the Chrome console tell me "Uncaught ReferenceError: maxnum is not defined " , can you tell me how to edit it ?
$("#newone").click(function(){
$("#num").val(function(){
max_response = $.ajax({
type:"POST",
url:"<?php echo base_url()?>/static_data/kungfu_maxquery",
cache:false,
data: "num:"+maxnum
});
max_response.done(function(){
return maxnum;
});
});
});
Make sure your model data is available in view, If available then need to alter your inpup fields:
NUM:<input id="num" value="<?php echo $data_for_first_input_filed; ?>" name="num" type="text" class="field_set"><br>
NAME:<input id="name" value="<?php echo $data_for_second_input_filed; ?>" name="name" type="text" class="field_set"><br>
LOCAL:<input id="local" value="<?php echo $data_for_third_input_filed; ?>" name="local" type="text" class="field_set"><br>
KUNGFU:<input id="kungfu" value="<?php echo $data_for_forth_input_filed; ?>" name="kungfu" type="text" class="field_set"><br>
If you want to append data through AJAX, then here is sample code:
$("#newone").click(function(){
$.ajax({
url: "<?php echo base_url()?>/static_data/kungfu_maxquery",
type: "POST",
data: {
'num':maxnum
},
cache: false,
success: function(data) {
console.log(data);
$("#num").val(data['filed_name_returned']);
$("#name").val(data['filed_name_returned']);
$("#local").val(data['filed_name_returned']);
$("#kungfu").val(data['filed_name_returned']);
}
});
});
AJAX request is not a cheap call, we can get all the data in one request and can set that available data in success function. I do't know your table structure that' why I have appended one line extra console.log(data); that will show your returned data in console.

Categories