User Agent Ignore Controller - codeigniter

I have set a error message where if is redirected to this login controller then shows this message below. Using the user_agent library which I have auto loaded.
if ($this->agent->referrer()) {
$this->error['warning'] = '<i class="fa fa-exclamation-triangle"></i> No activity within' .' '.gmdate("H:i:s", config_item('sess_expiration')).' '. 'seconds; please log in again';
} else {
$this->error['warning'] = "";
}
Question: I would like to know if possible to ignore message if redirected from my logout controller.

Try something like:
if ($this->agent->referrer() && $this->agent->referrer() !== 'http://example.com/logout') {
$this->error['warning'] = '<i class="fa fa-exclamation-triangle"></i> No activity within' .' '.gmdate("H:i:s", config_item('sess_expiration')).' '. 'seconds; please log in again';
} else {
$this->error['warning'] = "";
}
This should work, it can be optimized a little but this give you the idea. The if statement should evaluate to true on all referrers except from ones that come from whatever the url is of your logout page.
Does this make sense?

Related

Cloning item. The GET method is not supported for this route. Supported methods: POST

I'm trying to clone a model but when I try to I get the error in the title. This is what I'm doing
Button in vue.js
<a class="btn-link-clone action-button" :href="'survey/clone/'+scope.row.id">
<i class="fas fa-clone col-margin"></i>
</a>
Route in web.php
Route::post('survey/clone/{id}', 'SurveyController#cloneSurvey');
CloneSurvey in SurveyController
public function cloneSurvey($id)
{
$survey = Survey::findOrFail($id);
DB::beginTransaction();
$now = Carbon::now();
$activePeriod = Period::whereDate('start_date', '<=', $now)
->whereDate('end_date', '>=', $now)->get();
$clone = new Survey();
$clone->fill($survey->toArray());
$clone->name .= ' Clonado';
$clone->save();
$eval = Evaluation::findOrFail($clone->id);
if (empty($eval)) {
$eval = new Evaluation();
}
$eval->survey_id = $clone->id;
if (!empty($activePeriod)) {
$eval->init_date = $activePeriod->start_date;
$eval->end_date = $activePeriod->end_date;
}
$report = $activePeriod->end_date;
$date = strtotime($report);
$date = strtotime('+ 1 week', $date);
$eval->report_date = $date;
$eval->save();
$questions = $survey->surveyQuestions()->get()->pluck('survey_question_id')->toArray();
if (count($questions) > 0) {
$clone->surveyQuestions()->sync($questions);
}
DB::commit();
return back();
}
What is making this happen?
I've also tried this
button in vue.js
<div class="btn-link-clone action-button"
#click="clone(scope.row)">
<i class="fas fa-clone col-margin"></i>
</div>
method in vue.js
clone(row) {
this.$http.post('survey/clone/' + row.id)
.then(
() => {
this.surveys = this.$page.surveys;
},
(res) => {}
)
},
with the route the same and I get a 419 (unknown status)
You need your Route to use the get method rather than the post method. Like so:
Route::get('survey/clone/{id}', 'SurveyController#cloneSurvey');
When a user clicks on a link, that is almost always a GET request.
EDIT:
Based on the comments, I agree that changes should not be done via a get request anyway. This example should be a POST request.
Your Vue component:
<template>
...
<form>
<button
class="btn-link-clone action-button"
#click.prevent="submit(scope.row.id)"
>
<i class="fas fa-clone col-margin"></i>
</button>
</form>
...
</template>
<script>
export default {
...
methods: {
submit (id) {
// use whatever http request library you choose to execute POST HTTP request.
}
}
...
</script>
Alternatively, you could use #submit.prevent on the form tag instead of the #click.prevent on the button.
Then, as long as scope.row.id was defined on the frontend, you can use:
Route::post('survey/clone/{id}', 'SurveyController#cloneSurvey');
The GET method is not supported for this route. Supported methods: POST
You are making a GET request to a Route that only supports the POST method.
Either your vue app is making a ajax request to your server with missing headers or form incorrect form action.
You may also be passing something like a GET parameter as part of your request
i.e. http://my-app/api/example?var1=asdasdasdas

Laravel - How to send data from a checkbox button to a controller using Ajax

I am trying to have a toggle button (checkbox) changing some data in my MySQL database. I essentially want to to have a nice admin site in which I can unlock users to certain features on the site with a nice on/off switch.
Everything seems to be set up correctly, but my controller doesn't react or get triggered at all.
Right now, I have a working toggle button in my view triggering a javascript function. In that javascript function, I have already set up data that I want to transmit over to my controller.
I have also set up Ajax in my Javascript. Apparently Ajax has this part in its code (see my code if you need to know what I mean) where it says "success" or "error". Before entering the {{csrf_token()}} token, I always ended up in the error section. However, now I always enter the "success" section when toggling my button.
Now to my problem:
Although Ajax confirms a success, literally nothing happens within my controller. I have no idea how to change this as there is no error code whatsoever, either.
This is my button
<input id = "company_{{$company->id}}" data-id="{{$company->id}}" onchange=myFunction({{$company->id}}) value = {{$company->permissionlevel}} class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $company->permissionlevel ? 'checked' : '' }}>
This is my javascript (the relevant part)
var test = 12; // A random variable for this example
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: 'home/update', // This is the url we gave in the route
data: {'test' : test, _token: '{{csrf_token()}}'}, // a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response);
//alert("Ajax success");
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
//alert("Ajax error");
}
});
This is my controller function (just to see what happens)
public function update (Request $request)
{
//echo "This is a test";
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
return $data;
}
Route
Route::post('/home/update', 'HomeController#update');
Expected result:
Controller throws something at me. Currently all I want is to see if my controller reacts to the button press or if I can request the data Ajax is supposed to send over.
Actual result:
Nothing happens on my controller's side
I have found a solution by myself. I essentially added this code to my controller:
public function update (Request $request, $id, User $user)
{
$newPermLevel = $request->input('value');
$override = (int) $newPermLevel;
\DB::table('users')->where('id',$id)->update(array(
'permissionlevel'=>$override,
));
}
However, I need to add these small lines at the beginning of my controller right behind the namespace:
use Illuminate\Http\Request;
use App\User;
Just for completion, I will leave the other necessary code here as well for anybody in the need to update his database with a toggle / switch button
Here's my route
Route::post('/home/update/{id}', 'HomeController#update');
Here's my HTML
based on the current state of a button, I make an if statement (using blade engine) either creating a turned off or turned on switch. The button has a value, which essentially is the current database entry (in my case it is either 1 or 0 that I want to jump up and forth with)
#if ($company->permissionlevel == 0)
<div class="col-sm-5">
<label class="switch">
<input id = "company_{{$company->id}}" data-id="{{$company->id}}" onchange=myFunction({{$company->id}}) value = {{$company->permissionlevel}} class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $company->permissionlevel ? 'checked' : '' }}>
<span class="slider round"></span>
</label>
</div>
#endif #if ($company->permissionlevel == 1)
<div class="col-sm-5">
<label class="switch">
<input id = "company_{{$company->id}}" data-id="{{$company->id}}" onchange=myFunction({{$company->id}}) value = {{$company->permissionlevel}} class="toggle-class" type="checkbox" data-onstyle="success" data-offstyle="danger" data-toggle="toggle" data-on="Active" data-off="InActive" {{ $company->permissionlevel ? 'checked' : '' }}>
<span class="slider round"></span>
</label>
</div>
#endif
At last, my Javascript making use of Ajax. The code essentially check if the value of out switch is currently on 0 (then switch it to 1) or on 1 (then switch it to 0). Additionally, I define a variable to grab the current user's (company's ID), so that the controller later on knows to which user I refer.
<script>
function myFunction(id) {
var value = document.getElementById("company_" + id).value;
if (value == 1){
document.getElementById("company_" + id).value = 0;
//alert(document.getElementById("company_" + id).value);
}
if (value == 0){
document.getElementById("company_" + id).value = 1;
//alert(document.getElementById("company_" + id).value);
}
var company_id = id;
var newPermLevel = document.getElementById("company_" + id).value;
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: 'home/update/'+company_id, // This is the url we gave in the route
data: {
'company_id' : company_id,
'value' : newPermLevel,
_token: '{{csrf_token()}}',
},
// a JSON object to send back
success: function(response){ // What to do if we succeed
console.log(response);
//alert("Ajax success");
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
//alert("Ajax error");
}
});
}
</script>
Consider this question closed, but thanks for reading along. I hope anybody googling desperately for a similar solution can make use of my code. Not all heroes wear capes :)

cakephp ajax function issue

I have 2 functions in "events" (index, event_ajax)controller in my cakephp(2.5) web site. I'm trying to load HTML block to 'index.ctp' page by calling to 'event_ajax' function using ajax. When I call to this function it shows nothing. Look at 'net' tab in firebug it shows internal server error and 'net'->'Response' tab I can see whole layout is loaded.
I'm little confuse about in this scenario, can any one give a little explanation for following questions??? thanks in advance :)
Is it possible to call actions in same controller using ajax function ??
How 'Response' tab shows layout when '$this->layout' is set to NULL ??
when type url 'example.com/events/event_ajax', output data still '$this->autoRender=false'. how can this happen ??
this is my 'event_ajax' action.
public function event_ajax($x=1) {
$this->layout = NULL;
$this->autoRender = false ;
$contName = $this->Page->conName($x);
$latestContEvents = $this->Page->latestContEvent($x);
$internal = '';
if (!empty($latestContEvents)){
foreach ($latestContEvents AS $latestContEvent){
$internal .= '<li class="pull-left"> <div class="content-wrapper">'..... //do something
}
else {
$internal = '<p> No events found for this continent</p>';
}
$ContEvents = '<div class="carousel events-location-carousel">'.$internal.'</div> ';
return $ContEvents;
// return json_encode($ContEvents);
}
Try with
$this->layout = 'ajax';

How to logout from site?

How to logout from all pages of view, when I click on logout link I just from only one page when I am trying to logout from another page its not work.
My controller code is:
public function do_login()
{
$this->user = $this->input->post('user_email',TRUE);
$this->pass = $this->input->post('user_pass',TRUE);
$this->pass=md5(sha1(sha1($this->pass)));
$u = new User();
$login_data = array('email' => $this->user, 'password' => $this->pass);
$u->where($login_data)->get();
if(!empty($u->id) && $u->id > 0 )
{
$_SESSION['user_id'] = $u->id;
$_SESSION['user_name']= $u->username;
$_SESSION['fullname']= $u->fullname;
$_SESSION['is_verefied'] = $u->active;
$_SESSION['user_email']= $u->email;
$u->lastlogin = time();
$u->save();
setcookie("logged", 1, time()+86400);
if(empty($_POST['referer']))
{
if(empty($_GET['referer']))
{
$url = "./";
}
else
{
$url = $_GET['referer'];
}
}
else
{
$url = $_POST['referer'];
}
redirect($url);
}
else
{
$this->template->set_layout('inner');
$this->template->build('login_view',$this->data);
}
}
public function logout()
{
setcookie("logged", 0, time()+86400);
$_COOKIE["logged"] = '';
$_SESSION['user_id'] = '';
$_SESSION['user_name']= '';
$_SESSION['fullname']= '';
$_SESSION['is_verefied'] = '';
$_SESSION['user_email']= '';
redirect('./home/index/logout');
}
When I logout from site, and click back from browser the user information session its not deleted.
The back button of your browser might get you to cached version of you page, cached from back when you were logged it. Also, I suggest you use CodeIgniter's sessions.
To make sure you're doing everything right.
Destroy the session:
$this->session->sess_destroy();
Clear the cookie, make sure you use the same domain as when you set it up, and that the time is set to past:
setcookie('logged', '', time()-3600); // minus one hour
This script will log the user out of all pages that have a session started on them. You know a page uses sessions if this code is at the top of the code for that page:
<?php session_start(); ?>
Logging out of a website is simply clearing any session data and then destroying it.
Try the following in your logout.php:
<?php
session_start();
// what were doing here is checking for any cookies used by the session.
//If there are any, we are going to delete the data with it.
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
//now lets unset the session and destroy it
session_unset();
session_destroy();
// for the redirect, we simple use the php header to send the redirect url to the browser
header("Location: login");
Make sure when using the header function that there is no output, caused by blank spaces or html. As a logout page, there should be no output anyways since navigating to the logout page should log the user out and immediately redirect.
I use this script on all my sites and it works great. Anywhere I want the logout link to appear, I just link to the page as such:
Logout
Just make a file called logout.php and put this code into it.
Hope this helps you!

Codeigniter Flash Data After Submitting Form?

I have a question regarding form validation with Codeigniter and Flash Data. My form is located deep inside a URL string so I figured the best way to display error message on the page is with CI flash data. I'm having a difficult time figuring out how to actually display the error message. I'm not sure where I'm going wrong. Where am I going wrong? Thanks everyone.
public function form_validate_cars()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("value", "<b>Value</b>", "trim|required|is_numeric|xss_clean");
$this->form_validation->set_rules("exterior_color", "<b>Exterior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("interior_color", "<b>Interior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("mileage","<b>Mileage</b>","trim|required|is_numeric|xss_clean");
if ($this->form_validation->run() == FALSE)
{
// if person does not fill in correct info, they get resubmitted back to the form.
// redirect('site/item/2332');
// echo 'Hello World!';
$msg = "Please fill out proper data";
$this->session->set_flashdata('test', $msg);
// echo 'Please fill out needed ifnormation!';
}
else
{
$this->load->model('model_data');
$this->model_data->add_new_value();
redirect('/site/thanks');
}
}
My View
echo form_open('site/form_validate_cars');
print_r($this->session->flashdata('test'));
echo validation_errors();
my form continues below .......
Right after $this->session->set_flashdata('test', $msg); make redirect to desired url.
in view
if ($this->session->flashdata('result') != ''):
echo $this->session->flashdata('result');
endif;
better way without session
public function form_validate_cars()
{
$this->load->library('form_validation');
$this->form_validation->set_rules("value", "<b>Value</b>", "trim|required|is_numeric|xss_clean");
$this->form_validation->set_rules("exterior_color", "<b>Exterior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("interior_color", "<b>Interior Color</b>", "trim|required|xss_clean");
$this->form_validation->set_rules("mileage","<b>Mileage</b>","trim|required|is_numeric|xss_clean");
if ($this->form_validation->run() == FALSE)
{
// if person does not fill in correct info, they get resubmitted back to the form.
// redirect('site/item/2332');
// echo 'Hello World!';
$data['error'] = "Please fill out proper data";
$this->load->view('desired_view', $data);
} else {
$this->load->model('model_data');
$this->model_data->add_new_value();
redirect('/site/thanks');
}
}
and in view
echo (isset($error)) ? $error : "";
After you assigned the flashdata, redirect back to the form with redirect(). This will then pick up the flashdata, make sure to check if it's filled though.

Resources