I can not solve this problem
$ _SESSION ['usernam'] is wrong on purpose to go to the else
Middleware.php
<?php
$auth = function ($response, $request, $next) {
if (isset($_SESSION['usernam']) and is_array($_SESSION['username'])) {
$response = $next($response, $request);
//$response = $response->withStatus(401)->write('403.phtml');
} else {
$response = $response->withStatus(401)->withHeader('Location', '403.phtml');
}
return $response;
};
Error:
Details
Type: Error
Message: Call to undefined method Slim\Http\Request::withStatus()
File: C:\Users\Geovane\Documents\Dropbox\www\tennis\src\middleware.php
Line: 9
Trace
routes.php
$app->map(['GET', 'POST'], '/login', function ($request, $response, $args) {
//var_dump($_SERVER); exit;
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$data = json_decode(filter_input(INPUT_POST, 'data'));
} else {
$data = 'data';
}
$table = $this->db->table('_users');
$login = $table->where([
'username' => $data->username,
'password' => $data->password
])->get();
if($login->count()){
$_SESSION['username'] = (array)$login->first();
return json_encode('ok');
} else {
return false;
}
});
app.js
$(function() {
$('#log-in').click(function(){
var data = {'username': $('#username').val(), 'password': $('#password').val()};
data = JSON.stringify(data);
$.ajax({
type : 'POST',
url : 'login',
dataType : 'json',
data : {data:data},
success: function(data){
if (data == 'ok'){
window.location.replace("athletes");
} else {
new PNotify({
title: 'Ooops!',
text: 'Username ou Password incorretos.',
type: 'danger',
styling: 'bootstrap3'
});
};
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
new PNotify({
title: 'Oh No!',
text: 'Erro! Por favor, contate o administrador.',
type: 'warning',
styling: 'bootstrap3'
});
}
});
});
});
The order of the parameters is wrong, its request response next.
Change
function ($response, $request, $next) {
to this:
function ($request, $response, $next) {
Related
I have this ajax function that requests this route to login, but I want the redirection to be directly on the controller if the login is successful.
My ajax request:
$('#btn_login').on('click', function () {
var name = $('#name').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url : "login",
dataType: "JSON",
data: {
name,
pass
},
success: function (data) { },
error: function (data) {
alert('Login Error ');
}
});
return false;
});
My route.php:
Route::post('/login', 'LoginController#authenticate');
My LoginCOntrol.php:
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'pass');
$email = $credentials['email'];
$password = $credentials['pass'];
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return view('login.homepage')
}else{
return redirect()->back();
}
}
Try on ajax:
success: function (data) {location.href=data.url;},
And on Controller
Change
return view('login.homepage')
to
return response()->json(['url'=>route('homepage')]);
Hope this will answer your question.
I send a store request to my laravel application through AJAX. The controller function works properly, but either I cannot get a success message in my ajax function, or the function on success is not working.
Ajax code:
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left : offset_left
},
success: function(msg){
console.log("done");
}
});
Controller's store function:
public function store(Request $request)
{
echo $request;
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json('msg' => 'no auth');
}
}
Try to pass data in ajax using this way.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left: offset_left
},
success: function(msg) {
console.log("done");
}
});
Try below code for store method:
public function store(Request $request)
{
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json(['msg' => 'no auth']);
}
}
I have a table with title and done and id fields,
Now the problem is that when I click on the add button, the data is not stored in the table and the data is not displayed, if you test this code and create a task model with gii, you will see that add button does not work that is when you type a name and click on add button, the task will not be added
Fields related to this model: id, title, done
I have the following code:
todo.js in the assets file
var todo = {
taskTemplate: null,
refs: {},
options: {},
reload: function(){
$.ajax({
url: todo.options.taskEndpoint,
type: 'get',
dataType: 'json',
success: function(response) {
$.each(response.data, function(index, value){
todo.refs.tasks.append(todo.taskTemplate(value));
});
},
error: todo.onFailure
});
},
onFailure: function(xhr){
var data = $.parseJSON(xhr.responseText);
todo.refs.status.text('');
$.each(data.errors, function(index, value){
todo.refs.status.append('<p>'+value+'</p>');
});
},
onAdd: function(e){
e.preventDefault();
var form = this;
$.ajax({
url: todo.options.taskEndpoint,
type: 'post',
data: $(form).serialize(),
dataType: 'json',
success: function(response) {
todo.refs.tasks.append(
todo.taskTemplate(response.data));
form.reset();
},
error: todo.onFailure
});
},
onDelete: function(e) {
e.preventDefault();var id = $(this).parents('.task').attr('data-id');
$.ajax({
url: todo.options.taskEndpoint,
type: 'delete',
data: {
id: id
},
dataType: 'json',
success: function() {
$('.task[data-id='+id+']').remove();
},
error: todo.onFailure
});
},
onChange: function(e) {
e.preventDefault();
var data = {
id: $(this).parents('.task').attr('data-id'),
Task: {}
};
if(this.type==='checkbox') {
data.Task.done = + this.checked;
}
else if(this.type==='text') {
data.Task.title = $(this).val();
}
$.ajax({
url: todo.options.taskEndpoint,
type: 'put',
data: data,
dataType: 'json',
success: function(response) {
$('.task[data-id='+response.data.id+']')
.before(todo.taskTemplate(response.data))
.remove();
},
error: todo.onFailure
});
},
initLoader: function() {
var loadingText = 'Loading...';
$(document).ajaxSend(function(){
todo.refs.status.text(loadingText);}).ajaxStop(function(){
if(todo.refs.status.text()===loadingText) {
todo.refs.status.fadeOut(500, function(){
todo.refs.status.text('').show();
});
}
});
},
bindEvents: function() {
todo.refs.taskForm.submit(todo.onAdd);
todo.refs.tasks.on('click', '.delete', todo.onDelete);
todo.refs.tasks.on('change', 'input', todo.onChange);
},
initRefs: function() {
todo.refs.page = $('.todo-index');
todo.refs.tasks = todo.refs.page.find('.tasks');
todo.refs.status = todo.refs.page.find('.status');
todo.refs.taskForm = todo.refs.page.find('.new-taskform');
},
init: function(options){
todo.options = options;
todo.taskTemplate = doT.template($('#template-task').html());
todo.initRefs();
todo.initLoader();
todo.bindEvents();
todo.reload();
}
};
controller
<?php
class TodoController extends Controller
{
public function actionIndex()
{
$task = new Task();
$this->render('index', array(
'task' => $task,
));
}
public function actionTask()
{
$req = Yii::app()->request;
if($req->isPostRequest) {
$this->handlePost($req->getPost('id'),
$req->getPost('Task'));
}
elseif($req->isPutRequest) {
$this->handlePut($req->getPut('Task'));
}
elseif($req->isDeleteRequest) {
$this->handleDelete($req->getDelete('id'));
}
else {
$this->handleGet($req->getParam('id'));
}
}
private function handleGet($id)
{
if($id) {
$task = $this->loadModel($id);
$this->sendResponse($task->attributes);
}
else {
$data = array();
$tasks = Task::model()->findAll(array('order' => 'id'));
foreach($tasks as $task) {
$data[] = $task->attributes;
}
$this->sendResponse($data);
}
}
private function handlePut($data)
{
$task = new Task();
$this->saveTask($task, $data);
}
private function handlePost($id, $data)
{
$task = $this->loadModel($id);
$this->saveTask($task, $data);
}
private function saveTask($task, $data)
{
if(!is_array($data)){
$this->sendResponse(array(), 400, array('No data
provided.'));
}
// $task->setAttributes($data);
$task->attributes = $data;
if($task->save()) {
$this->sendResponse($task->attributes);
} else {
$errors = array();
foreach($task->errors as $fieldErrors) {
foreach($fieldErrors as $error) {
$errors[] = $error;
}
}
$this->sendResponse(array(), 400, $errors);
}
}
private function handleDelete($id)
{
$task = $this->loadModel($id);
if($task->delete()) {
$this->sendResponse('OK');
}
else {
$this->sendResponse(array(), 500, array('Unable to
delete task.'));
}
}
private function loadModel($id)
{
$task = Task::model()->findByPk($id);
if(!$task) {
$this->sendResponse(array(), 404, array('Task not
found.'));
}
return $task;
}
private function sendResponse($data, $responseCode = 200,
$errors = array())
{
$messages = array(
200 => 'OK',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Internal Server Error',
);
if(in_array($responseCode, array_keys($messages))) {
header("HTTP/1.0 $responseCode ".$messages[$responseCode],
true, $responseCode);
}
echo json_encode(array(
'errors' => $errors,
'data' => $data,
));
Yii::app()->end();
}
}
?>
view
<?php
Yii::app()->clientScript->registerPackage('todo');
$options = json_encode(array(
'taskEndpoint' => $this->createUrl('todo/task'),
));
Yii::app()->clientScript->registerScript('todo', "todo.
init($options);", CClientScript::POS_READY);
?>
<div class="todo-index">
<div class="status"></div>
<div class="tasks"></div>
<div class="new-task">
<?php echo CHtml::beginForm('todo/task')?>
<?php echo CHtml::activeTextField($task, 'title')?>
<?php echo CHtml::submitButton('Add')?>
<?php echo CHtml::endForm()?>
</div>
</div>
<script id="template-task" type="text/x-dot-template">
<div class="task{{? it.done==1}} done{{?}}" data-id="{{!it.
id}}">
<input type="checkbox"{{? it.done==1}}checked {{?}}/>
<input type="text" value="{{!it.title}}" />
Remove
</div>
</script>
Can anyone help ?
I'm using ajax in my ZF2 Application and I have a problem with Ajax. My code is this:
Ajax:
$('.checkbox-published').on('click', function () {
var id_entity = "";
var ischecked = $(this).is(":checked");
var path = $(this).attr('url');
id_entity = $(this).val();
alert(path);
$.ajax({
url: path,
type: 'POST',
datatype: 'json',
data: {'id_entity': $(this).val(), 'ischecked': ischecked},
success: function (data, status) {
alert("Succes + info: " + data.message);
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (xhr.status == 404) {
alert('Requested page not found. [404]');
} else if (xhr.status == 500) {
alert('Server Error [500].');
} else if (errorThrown === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (errorThrown === 'timeout') {
alert('Time out error.');
} else if (errorThrown === 'abort') {
alert('Ajax request aborted.');
} else {
alert('There was some error. Try again.');
}
},
});
});
And my controller:
public function publishAjaxAction()
{
$result = array('status' => 'error', 'message' => 'There was some error. Try again.');
$request = $this->getRequest();
if ($request->isXmlHttpRequest()) {
$locale = $this->locale();
$data['id_entity'] = $request->getPost('id_entity');
$data['ischecked'] = $request->getPost('ischecked');
$result['message'] = "Animo que funciona!" . $data['id_entity'] . "->" . $data['ischecked'];
$dataToTable = array(
'id' => $data['id_entity'],
'locale' => $locale,
'ischecked' => $data['ischecked'],
);
$this->getCenterTable()->publishEntity($dataToTable);
}
return new JsonModel($result);
}
It don't retunrs any data. If it works it will return a message with there was some error. But what I have in my response is undefined. I don't know how to solve it.
Any help would be perfect.
I am working with Laravel 4 and I want to perform validation with Ajax. I have 2 main problems:
1. The URL at Ajax is static, which means that if I have my app online I should put the URL for online and locally doesn't works
2. my route is insur_docs/{id} how should be URL for this?
jQuery('form#insur_docs_update').submit(function()
{
jQuery.ajax({
url: "http://localhost:8080/insur_docs/{id}", //my url I don't know how to put it
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
})
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
jQuery.each(arr, function(index, value)
{
if (value.length !== 0)
{
$("#validation-div").addClass('alert alert-danger');
document.getElementById("validation-div").innerHTML += '<span class="glyphicon glyphicon-warning-sign"></span>' + value + '<br/>';
}
});
jQuery('#ajax-loading').hide();
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
routes.php
Route::get('insur_docs/{id}', 'Insur_DocController#edit');
controller
public function update($id) {
Input::flash();
$data = [
"errors" => null
];
$rules = array(
"ownership_cert" => "required",
"authoriz" => "required",
"drive_permis" => "required",
"sgs" => "required",
"tpl" => "required",
"kasko" => "required",
"inter_permis" => "required",
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->passes()) {
$car_id = DB::select('select car_id from insur_docs where id = ?', array($id));
$data = InsurDoc::find($id);
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->save();
return Redirect::to('car/' . $car_id[0]->car_id);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => $validation->errors()->toArray()
);
return Response::json($response_values);
}
}
}
Use laravel's url generator helper to create your form's action:
<form action="{{ URL::action('Insur_DocController#edit', $id) }}" method="post">
You can access it in your javascript:
jQuery('form#insur_docs_update').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
});
}
EDIT
You're second problem is that you're redirecting in response to the ajax call, and that does not redirect the page. You'll need to return the url and do the redirect in javascript like this.
Controller:
return Response::json(["redirect_to" => 'car/' . $car_id[0]->car_id]);
JS (just the relevant part):
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
// your code
} else {
window.location = data.redirect_to;
}
})
var myUrlExtension = "whatever.php"
and inside the ajax
url: "http://localhost:8080/insur_docs/" + myUrlExtension