How can I dynamically post my message in CodeIgniter? - javascript

I just want to tell the user either with AngularJS or AJAX or JQuery, or whatever is easiest, that the username and email are already registered.
I already have AngularJS implemented for other checks, just not those that need php.
Here is my php function:
public function user_exists() {
$username = $this->db->escape($this->input->post('username'));
$data = array(
'username' => $username,
'email' => $this->db->escape($this->input->post('email')),
'password' => crypt($this->db->escape($this->input->
post('password'))),
'user_id' => md5('I really like pie, '. $username)
);
$does_user_exist = "SELECT COUNT(`user_id`) FROM `users` WHERE
`username` = " . $data['username'] . " || `email` = " .
$data['email'] . "";
$query = $this->db->query($does_user_exist);
if($query->num_rows() > 0) {
return true;
}
}
Please and thank you.

Why you use $data array in method? To check exists user or not you need use MVC architecture and something like this code.
For model:
class User_Model extends CI_Model
{
public function is_exists($username, $email)
{
$this->db->select('user_id');
$this->db->where(array(
'username' => $username,
'email' => $email
));
$this->db->limit(1);
return $this->db->get('users')->row('user_id');
}
}
This code for controller:
class User extends CI_Controller
{
public function is_exists()
{
$email = $this->input->post('email');
$username = $this->input->post('username');
$this->load->model('user_model');
if(!$this->user_model->is_exists($username, $email))
{
$result = array('status' => 200, 'message' => 'Username and email are free');
}
else
{
$result = array('status' => 400, 'reason' => 'User already exists');
}
echo json_encode($result);
}
}
Ajax query:
$.ajax({
url: 'user/is_exists',
type: 'POST',
dataType: 'JSON',
data: {username: username, email: email},
success: function(data, status, jqXHR){
if(data.status == 200){
alert(data.message);
}
else{
alert(data.reason);
}
}
});
username and email js variables you need get from your regisration form.
Also you can use Ion Auth or Tank Auth extensions

When the user clicks the submit button on the registration form submit it using $.post() in jQuery. The action attribute of the form should map to the appropriate controller/method. The method you call can return a JSON encoded message to display in the browser.
It could look something like this:
$(function() {
$('#registration', 'input[type="submit"]').on('click', function(event) {
event.preventDefault();
var action = $(this).closest('form').attr('action');
var form = $(this).closest('form').serialize();
$.post(action, form, function(data) {
alert(data.message);
});
});
});
In the above example the ID of the form is #registration. The JS var 'data' is the JSON object returned by your PHP method and 'message' is a property of that object containing a message to display to the user.

Related

How to check existing data with jquery validation library with codeigniter 4 when csrf is set to auto?

I have a form that I'm trying to validate with jquery validation plugin and codeigniter 4, I have enabled csrf that set to auto generate for every request. I'm able get validation status on first request but when I try another request I get error 403, and when I set second param to json_encode() I get error 500. I want to be able to update csrf after each request on ajax call.
//My router
$routes->post('check-category', 'Admin\Category::check_category');
//my controller
//check if category name exist
public function check_category()
{
$name = $this->request->getPost('name');
$query = $this->db->table('categories')
->where(['cat_name' => $name])
->get()
->getResult();
$status = true;
if(count($query) > 1){
$status = false;
}else{
$status = true;
}
$data['csrf'] = csrf_hash();
echo json_encode($status, $data);
}
// javascript
$('#create_category').validate({
onkeyup: false,
rules: {
name: {
remote: {
url: 'check-category',
type: "post",
data:{
csrf_hash_name: function(){
return $('input[name="csrf_hash_name"]').val();
}
},
complete: function(data){
$('input[name="csrf_hash_name"]').val(data.csrf);
}
}
}
},
messages: {
name: {remote: "This category exists."}
},
submitHandler: function(form) { return false; }
});
Thanks in advance.
the structure of the php function json_encode() looks like this:
json_encode ( mixed $value , int $flags = 0 , int $depth = 512 ) : string|false
and returns:
a string containing the JSON representation of the supplied value.
in your controller function check_category() you are sending $status, while $data is setting an invalid flag:
echo json_encode($status, $data); // wrong
change $status = true; into $data['status'] = true;
and just echo both, status and the csrf hash
echo json_encode($data); // correct
After so much struggle I finally found the solution of my problem. Now I'm able to update csrf token with the dataFilter object and get rid off error 403 during ajax call.
Here is what I have done to my controller even I broked Mvc principle by getting data from db direct to the controller.
I know it could not the best way for what I have done, Please correct me if any suggestion I'll appreciate. Thanks!
//my controller method
public function check_category()
{
$name = $this->request->getPost('name');
$query = $this->db->table('categories')->where(['cat_name' => $name])->countAllResults();
$valid = true;
if($query > 0){
$valid = false;
}else{
$valid = true;
}
$csrf = csrf_hash();
return $this->response->setJSON(['valid'=>$valid, 'csrf'=>$csrf]);
}
// my javascript
$('#create_category').validate({
onkeyup: false,
rules: {
name: {
required: true,
remote: {
url: 'check-category',
type: 'post',
dataType:'json',
dataFilter: function(data){
let obj = eval('('+data+')');
$('input[name="csrf_hash_name"]').val(obj.csrf);
return obj.valid;
},
data:{ csrf_hash_name: function(){ return $('input[name="csrf_hash_name"]').val(); } }
}
}
},
messages: {
name: {
required: "Enter a Category.",
remote: "{0} This category exists."
}
},
submitHandler: function(form) {
return false;
}
});

when i pass static data it will be store data successfull.when i pass dynamic it will not store data.how to pass dynamic data

when i passed static it will be succefull stored in data base. when i pass dynamic data it will not stored in database.in my view form id is signupform which have 5 fields.
here is my .js file
$(document).on("submit","#signupform",function(e){
e.preventDefault();
//var view_id=$("#id_hid").val();
//alert(view_id);
console.log($('#signupform').serialize());
var data = {'username' : 'username' , 'password' : 'password' , 'email' : 'email' , 'mobileno' : 'mobileno' , 'address' : 'address' };
data = $('#signupform').serialize() + '&' + $.param(data);
$.ajax({
type:"POST",
data:data,//$('#signupform').serialize(),
dataType: "JSON",
url:"../welcome/add",
success:function(data){
//var json=$.parseJSON(data);
//$('#signupform').html(response);
alert(data);
}
});
});
** Here is my controller file**
public function add(){
$data=array();
$postData=array();
//prepare post data
$postData = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'),
'mobileno' => $this->input->post('mobileno'),
'address' => $this->input->post('address')
);
//print_r($postData);
//insert post data
$insert = $this->home_model->insert_form($postData);
$data['msg']= "data insert successfully";
echo json_encode($data['msg']);
}
Here is my model file
function insert_form($data){
$insert=$this->db->insert('emp',$data);
if($insert){
return $this->db->insert_id();
} else {
return false;
}
echo json_encode($data);
}
If you want to post a string data, you can remove dataType: "JSON"
Or you can use this method
$(document).on('submit', '#signupform', function (e) {
e.preventDefault();
var data = {username: 'username', password: 'password', email: 'email', mobileno: 'mobileno', address: 'address'};
data = Object.assign({}, $('#signupform').serializeArray()[0], data);
console.log(data);
$.post('your backend url', data, function (result) {
console.log(result);
})
})
You don't need to define the data object. The serialize() method would do that for you. But, because you are making a POST you should use serializeArray() instead. serialize() is geared toward GET requests.
$(document).on("submit","#signupform",function(e){
var data;
e.preventDefault();
data = $('#signupform').serializeArray();
$.ajax({
type:"POST",
data:data,
dataType: "JSON",
url:"../welcome/add",
success:function(data){
//data is an object. If you want the text returned use data.msg
//$('#some-message-div').text(data.msg);
console.log(data); //an object with one property - 'msg'
}
});
});
The controller method can be simplified a lot. Because the field names exactly match the table column names there is no need to build the $postData array. The posted data already has that exact structure. $this->input->post() will return what you need.
public function add()
{
//insert post data
if($this->home_model->insert_form($this->input->post()))
{
$data['msg'] = "data insert successfully";
}
else
{
$data['msg'] = "insert failed";
}
echo json_encode($data);
}
The model can be much cleaner.
function insert_form($data)
{
if($this->db->insert('emp', $data))
{
return $this->db->insert_id();
}
//don't need else when the if condition calls return
return false;
}
The line echo json_encode($data); served no purpose. The way it was coded that line never executed - both the if and else blocks returned. Even if it did execute, it's the wrong thing for a model to do.

Laravel login, check if username and pwd are a match in my database

In my login form all I need
is just username and a password ,trying to use ajax to get data from sqlite .
.AJAX of my login.blade.php
$(document).ready(function(){
$("#login").click(function(){
$.ajax({
type: "GET",
url: "UserController.php",
data: { username: $("#username").val(), password: $("#password").val()},
success: function(data){
response = JSON.parse(data);
if(response[0]){
}
else{
alert(response[1]);
}
}
});
});
});
my User.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class User extends Model
{
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'phone','email', 'password','password_confirmation','librarian'
];
}
read method in UserController
//to read data from database to login
public function read(Request $request){
$results = DB::select('select * from users where id = :id', ['id' => 1]);
foreach ($users as $user) {
echo $user->username;
}
my web.php
Route::get('/login', function () {
return view('login');
});
Route::get('/signup',function(){
return view('signup');
});
Route::get('/bookscreate',function(){
return view('bookscreate');
});
Route::get('/','BookController#index');
Route::post('signup', 'UserController#store');
//Route::post('signup', 'UserController#read');
Route::resource('/books','BookController');
So my objective is to go to my database table check username and password if they match one of the DB id then allow user to login .
https://laravel.com/docs/5.5/authentication
read laravel authentication document because laravel have your requirement already built-in and it is very easy to implement. Thank you since i was not able to comment i had to post it as answer.

How to validate form data using form_validation in codeigniter submitted using ajax

I'm writting a code using CodeIgniter
ajax
var formData = {};
var url = $(form_id).attr("action");
$(form_id).find("input[name]").each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('select[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$(form_id).find('textarea[name]').each(function (index, node) {
formData[node.name] = node.value;
});
$.ajax({
type: "POST",
data: {
'formdata': formData
},
url: url,
dataType: 'json',
success: function(result) {
if (result.data) {
make_alert();
} else {
$('#error-msg').html(result.message);
}
},
error: function(result) {
// error code here
}
});
Which will sent a data formData to add function in controller
add function
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required',
array('required' => 'You must provide a %s.')
);
$this->form_validation->set_rules('email', 'Email', 'required');
and this part here receive the formData values
$post_data = $this->input->post('formdata');
$data = array (
'username' => $post_data['username'],
'email' => $post_data ['email'],
'password' => $post_data ['password']
);
and this part run the validation
if ($this->form_validation->run() == FALSE) {
$result['message'] = validation_errors();
} else {
$result['data'] = $this->ion_auth->register($data['identity'], $data['password'], $data['email'], $data['additional_data'], $data['group']);
}
which return json
echo json_encode($result);
before using ajax, the code run smoothly without problem, but when using ajax, the validator return a message saying fields should be required, meaning, it doesn't receive form data submitted.
this part,
$data = array (
'username' => $post_data['username'],
'email' => $post_data ['email'],
'password' => $post_data ['password']
);
when using var_dump() on $data show it received form data submitted using ajax.
My question is, how to validate this $data using form_validation?
You cant validate using form_validation library
You should validate manually usin if statement and you will set error message as you want

submit prevented by preventDefalut()

I am using ajax to make validation of login. I am having a problem with javascript e.preventeDefault(), when use it prevents submit and always shows validation empty field. When remove it is right but echo json data and doesnt shows validation messages inside dialog box, instead it redirects to url and echo the right json message. I think e.preventDefault prevents submit, is there any other way to put validation message inside dialog box insted of e.preventDefault() ?
$('#login_form').on('submit', function(e) {
e.preventDefault();
var username = $('#login_form input[name=sign_in_username]').val();
var password = $('#login_form input[name=sign_in_pass]').val();
$.ajax({
url: "login.php",
type: "POST",
data: {username: username,
password: password
},
dataType: 'json',
success: function(response) {
if(response.status){
$(this).unbind('submit').submit()
console.log(response);
window.location = response.url;
}
else{
$('#invalid_content').html(response.msg);
}
}
});
});
login.php
if (((!isset($_POST["sign_in_pass"]) || !isset($_POST["sign_in_username"]) ) || trim($_POST["sign_in_pass"]) == "" || trim($_POST["sign_in_username"]) == "")) {
echo json_encode(array('msg' => "Username or password are empty.", 'url' => "", 'status' => false));
exit();
}
$rows = query("SELECT * FROM customers WHERE username = ?", $_POST["sign_in_username"]);
// nese form eshte bere submit
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (count($rows) == 1) {
$row = $rows[0];
if (crypt($_POST["sign_in_pass"], $row["hash"]) == $row["hash"]) {
$_SESSION["id"] = $row["id"];
echo json_encode(array('msg' => "Success.", 'url' => "index.php", 'status' => true));
}
} else {
echo json_encode(array('msg' => "Username or password invalid.", 'url' => "", 'status' => false));
}
} else {
echo json_encode(array('msg' => "Username or password invalid.", 'url' => "", 'status' => false));
}
Your problem is not the e.preventDefault(). Your fields just don't match up, which is why they're empty.
Your data parameter should be: data: {sign_in_username: username, sign_in_password: password}.
The request your PHP script receives has the wrong field names in it.
In the future, for debugging purposes, on your PHP script, try var_dump($_POST);. This will give you an idea of what the request you received had in it.

Categories

Resources