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');
}
}
Related
I have Created View, Controller Model and connect the database with the codeigniter project.
And i have already configures codeigniter with database.
But when i run the project It Gives me the Error as follow:-
Message: Call to undefined method CI_Loader::select()
My View is:-
login.php
<html>
<head>
<title>Login to Dhoami Enterprice</title>
<script src="<?php echo base_url();?>/assets/js/jquery-3.2.1.js"></script>
<script src="<?php echo base_url();?>/assets/js/sweetalert.min.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>/assets/css/sweetalert.css">
<head>
<body>
<form id="login_form" method="POST" >
<input type="text" name="u_name" placeholder="Enter E-mail">
<input type="text" name="u_pass" placeholder="Enter Password">
<button type="submit" name="login_submit">Login</button>
</form>
</body>
<script>
/* function login(){
var form_data = $('#login_form').serialize();
alert(form_data);
} */
$('#login_form').submit(function(e){
e.preventDefault();
var form_data = $('#login_form').serialize();
$.ajax({
type:'POST',
url:'<?php echo base_url();?>/login/login_ajax',
data:form_data,
success: function(){
},
error:function(xhr){
swal("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
});
</script>
</html>
Cotroller is:-
Login.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('Login_model');
}
public function index()
{
$this->load->view('login');
}
public function login_ajax(){
$user_email = $this->input->post('uname');
$user_password = $this->input->post('upass');
$user_password = hash('sha512', $user_password);
$where = array('email'=>$user_email,'password'=>$user_password);
$data['user_status'] = $this->Login_model->check_user($where);
print_r($data['user_status']);
}
}
ModelIs as Follow:-
Login_model.php
<?php
class Login_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->db = $this->load->database('default');
}
public function check_user($where){
$this->db->select('*');
$this->db->from('user');
$this->db->where($where);
$query = $this->db->get();
echo $this->db->last_query();
//return $query->result_array();
}
}
?>
According to CodeIgniter's source, the $this->load->database('default') call will return an instance of CI_Loader class unless you pass a second boolean poaremter.
So, basically, it should be
$this->db = $this->load->database('default', true);
P.S. you really should not use CodeIgniter in any new projects.
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)
});
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');
}
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.
I want to make live search using codeigniter and jquery and mysql
but when i type something the result's not showing
here is my model code :
<?php
class artikel_model extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function cari_artikel($q)
{
$this->db->select('judul,contain');
$this->db->like('judul', $q);
$this->db->or_like('contain', $q);
$query = $this->db->get('artikel');
return $query->result_array();
}
}
?>
and here is my controller code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('artikel_model');
}
public function index()
{
if(isset($_GET['q']) && $_GET['q']){
$q = $this->input->get('q');
$this->data['data']=$this->artikel_model->cari_artikel($q);
}
else{
$this->data['data']=array_fill_keys(array('judul', 'contain'), NULL);
}
$this->data['body']='dashboard';
$this->load->view('welcome_message',$this->data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
this is my view code
<?php $this->load->helper('html');?>
<div class="row">
<div class="span12 offset3">
<form class="form-inline" name="form1" method="get" action="">
Search : <input type="text" class=span5 name="q" id="q"/> <label for="mySubmit" class="btn btn-primary"><i class="icon-search icon-white"></i></label> <input id="mySubmit" type="submit" value="Go" class="hidden" />
</form>
</div>
</div>
<?php echo br(15); ?>
<div id="result"></div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
var allow = true;
$(document).ready(function(){
$("#q").keypress(function(e){
if(e.which == '13'){
e.preventDefault();
loadData();
}else if($(this).val().length >= 2){
loadData();
}
});
});
function loadData(){
if(allow){
allow = false;
$("#result").html('loading...');
$.ajax({
url:'http://localhost/helpdesk?q='+escape($("#q").val()),
success: function (data){
$("#result").html(data);
allow = true;
}
});
}
}
</script>
<?php
foreach($data as $row){ ?>
<h3><?php echo $row['judul']; ?></h3>
<?php } ?>
The live search is not working.
when i type something the output just "loading..."
and the result is not showing..
If i press enter, the result will show. but that is just the usual searching method. Not live searching.
Make a new function say "live_search" that will only return the result with the ajax search and not the "index" function. This new function will return the result with the HTML markup.
public function live_search(){
if($this->input->post(null)){
//put your search code here and just "echo" it out
}
}
$.ajax({
url:'http://localhost/domain/controller/live_search',
type : 'POST',
data : { 'q' : escape($("#q").val()) },
success: function (data){
$("#result").html(data);
allow = true;
}
});
Hope it helps you.