Displaying a flash message using Laravel - php

I am trying to have some sort of a pop up screen or flash message using Laravel, currently I have set up a route and which is triggerd using Ajax call, which is submitting a field to a Controller method to verify if a certain user has any violations, when clicking the button "check for violation" nothing is happening and I am not getting any flash messages in my page.
here is my view:
#if(Session::has('success'))
<script type="text/javascript">
swal({
title:'Info!',
text:"{{Session::get('success')}}",
timer:5000,
type:'info'
}).then((value) => {
location.reload();
}).catch(swal.noop);
</script>
#endif
<form action="{{ route('assignees.store') }}" enctype="multipart/form-data" method="POST">
#csrf
<div class="row">
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<strong>Customer ID:</strong>
<input class="form-control" type="text" name="custidno" id='cust' required autocomplete="off" onkeypress="myFunction()" placeholder="Customer ID" >
<button onclick="CheckViolation()"class="btn-info"type="button">Check for Violation</button>
</div>
</div>
JS Code
function CheckViolation()
{
var customerid= document.getElementById("cust").value;
var url = "{{ url('violationcheck') }}";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.open("GET", url + "?" +"custidno=" + customerid, true);
xhttp.send();
}
and that's my route:
Route::get('violationcheck', 'ViolationController#violationcheck')->name('violationcheck');
and that's my basic controller method
public function violationcheck(Request $request)
{
$custidno = customer::select("id")
->where('name',$request->custidno)
->first();
$checked = DB::table('violations')
->select('severity',DB::raw('count(*) as total'))
->where("customer_id",$custidno->id)
->where("status",1)
->groupBy('severity')
->first();
if(empty($checked))
{
$msg="No Violation found";
}else{
$msg="Violation found";
}
return redirect()->route('assignees.create')->with("success",$msg);
}
what am I doing wrong?

Try this one:
#if (session('info'))
<div class="alert alert-info">
{{ session('info') }}
</div>
#endif
Read more about Redirecting With Flashed Session Data

Related

How to add a comment to a page using ajax

I am trying to allow the user to make a comment in an article but somehow, so that my page is not reloaded, I have to use ajax and I don't have much knowledge about it. This is how my comment section looks like:
<div class="usrcmmnt_list">
#foreach($comments as $comment)
<div class="usrcmmnt flex_box">
<div class="usrcmmnt_pic">
<img src="{{ $comment->user['profile_image'] }}">
</div>
<div class="usrcmmnt_area">
<p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
<div class="usrcmmnt_box">
<p class="usrcmmnt_text">{{$comment['content']}}</p>
<p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
</div>
</div>
</div>
#endforeach
</div>
<div class="comment_write">
<textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
<p class="usrcmmnt_text" id="textarea_warning"></p>
<span class="alert"></span>
<button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
</div>
</div>
In my script part, I have this one but it only copies the existing comments. This is just for my testing:
$('.comment_write button').on('click', function(e){
e.preventDefault();
var tmp = document.createElement('div');
$(tmp).load('myurl', function(data){
// usrcmmnt_list
var tmp2 = document.createElement('div');
$(tmp2).html(data);
var list = $(tmp2).find('.usrcmmnt_list');
$(".usrcmmnt_list").append(list);
});
});
How can I attain my goal using ajax?
There are multiple approaches for this, one of them:
you could move your comments loop (#foreach) into a partial
create an endpoint to save the user comment and return the new comments partial as html
update the DOM
1. Create a new partial \resources\views\partials\comments.blade.php and include it into your comments section:
#if ($comments)
#foreach($comments as $comment)
<div class="usrcmmnt flex_box">
<div class="usrcmmnt_pic">
<img src="{{ $comment->user['profile_image'] }}">
</div>
<div class="usrcmmnt_area">
<p class="usrcmmnt_name">{{ $comment->user['name'] }}</p>
<div class="usrcmmnt_box">
<p class="usrcmmnt_text">{{$comment['content']}}</p>
<p class="usrcmmnt_time"><img src="{{ url('/img/icon_time.png') }}">{{ date("m/d H:m", strtotime($comment->created_at)) }}</p>
</div>
</div>
</div>
#endforeach
#else
No comments
#endif
2. Your comments section should look like this:
<div class="usrcmmnt_list">
<div id="comments-list">
#include('partials.comments')
</div>
<div class="comment_write">
<form method="post" action="{{ route('save.comment') }}" id="saveCommentForm">
<textarea placeholder="Write a comment" name="comment" id="comment" maxLength="255"></textarea>
<p class="usrcmmnt_text" id="textarea_warning"></p>
<span class="alert"></span>
<button class="btn btn_orange btn_m_2" id="saveComment" type="submit">Post comment</button>
</form>
</div>
</div>
3. Create your save comment method in CommentsController (which you will use to save the user comment via your ajax call):
public function save(Request $request)
{
/* we assume that your ajax save route is named comment.save */
/* you might need the postId if you save the comments for a post */
$comment = $request->input('comment');
$user = auth()->user();
$comment = Comment::create([
'user_id'=> $user->id,
'content'=> $comment
]);
$comments = Comment::with('user')->all();
return view('comments.blade');
}
4. Your ajax call:
$(document).ready(function(){
$('#saveCommentForm').on('submit', function(event) {
event.preventDefault(); // prevent the form from submiting
var $form = $(this),
url = $form.attr('action');
$.ajax({
url: url,
method: 'POST',
data: $form.serialize(),
success: function(response) {
$('#comments-list').html(response); //update the dom
},
error: function() {
alert('An error occurred. Please try again later.');
}
});
});
});
I hope this will help you get started.
You must try something like this.
$(document).on('click', '#saveComment', function(){
if($('#comment').val()==''){
alert('Please write a Comment First!');
}
else{
var comment = $('#comment').val();
$.ajax({
type: 'POST',
url: '<your url goes here>',
data: {"comment": comment},
success: function(){
// update comment listing.
},
});
}
});
However here is the complete tutorial you can follow. https://www.sourcecodester.com/tutorials/php/11819/laravel-comment-post-using-ajax.html

Showing success message in php using ajax

Iam Working on a project using OO php and i want to display success message when submit is clicked
I've searched all on the web but the solutions am getting are not working for me!!
I tried using both jquery and ajax but i keep on getting the same error
Here is my html
<form method="post" id="postForm" class="form-horizontal" action = "index.php">
<div class="form-group">
<label for="Title" class="control-label col-sm-3">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post"/>
</div>
</div>
<div class="form-group">
<label for="Title" class="control-label col-sm-3">Body</label>
<div class="col-sm-9">
<Textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
</div>
</div>
<button type="submit" class="btn btn-default" name="submit">submit</button><br/>
<div class="text-center">
<span id="success" class="text-success"></span>
<span id="wanings" class="text-danger"></span>
</div>
</form>
This is my jquery script file inserted into the same page index.php
<script>
$(document).ready(function(){
$('#postForm').submit(function(event){
event.preventDefault();
var $form = $(this),
var title = $('#title').val();
var body = $('#body').val();
var url = $form.attr('action');
var method = $form.attr('method');
if(title == '' || body == ''){
$('#warnings').html('All Fields are Required');
}else{
$('#warnings').html('');
$.ajax({
url: url,
method:method,
data:{title: title, body:body},
success:function(data){
$('#postForm').trigger('reset');
$('#success').fadeIn().html(data);
setTimeout(function function_name() {
$('#success').fadeOut('slow');
}, 3000);
}
});
}
});
});
</script>
And the Php is just above the Html also in the same page. Its supposed to get the post title and insert it into the database but echo the message that data has been successfully added if submit is clicked.
Here is the Snippet
<?php
require 'classes/Database.php';
$database = new Database;
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
if($post['submit']){
$title = $post['title'];
$body = $post['body'];
$database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
$database->bind(':title', $title);
$database->bind(':body', $body);
$database->execute();
if($database->lastInsertId()){
echo "<h1>Post added Successfully To the Database</h1>";
}
}
?>
When i run the page in the browser, it displays the whole html in the div.
instead of a message set and then it throws the following error in the console.
Could any of you be knowing why it can't show the message? thanks
As you notice by the image, all the text is green, this is because you are rendering the response within that text-success span. Not ideal.
Instead of responding with HTML respond with JSON, and do your checks within the javascript to determine whether it was successful or a warning.
Some other issues:
You're not sending up submit so it will always skip passed the if statement.
So try something like:
$(document).ready(function() {
$('#postForm').submit(function(event) {
event.preventDefault();
var $form = $(this);
var title = $('#title').val();
var body = $('#body').val();
var url = $form.attr('action');
var method = $form.attr('method');
if (title == '' || body == '') {
$('#warnings').html('All Fields are Required');
if (title == '') {
$('#title').closest('.form-group').find('.help-block').html('Title is a required field')
}
if (body == '') {
$('#body').closest('.form-group').find('.help-block').html('Body is a required field')
}
} else {
$('#warnings').html('');
$form.find('.help-block').html('')
$.ajax({
url: url,
method: method,
data: {
title: title,
body: body
},
success: function(response) {
// got errors from server
if (response.status === 'error') {
if (response.errors.title) {
$('#title').closest('.form-group').find('.help-block').html(response.errors.title)
}
if (response.errors.body) {
$('#body').closest('.form-group').find('.help-block').html(response.errors.body)
}
if (response.errors.global) {
$('#warnings').html(response.errors.global)
}
}
// all good, assign message to success
else {
$('#success').fadeIn().html(response.msg);
setTimeout(function() {
$('#success').fadeOut('slow');
}, 3000);
$('#postForm').trigger('reset');
}
}
});
}
});
});
<form method="post" id="postForm" class="form-horizontal" action="index.php">
<div class="form-group">
<label for="title" class="control-label col-sm-3">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="title" id="title" placeholder="Enter Title of your Post" />
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label for="body" class="control-label col-sm-3">Body</label>
<div class="col-sm-9">
<textarea type="text" class="form-control" name="body" id="body" placeholder="Enter Body of your Post"></textarea>
</div>
<span class="help-block"></span>
</div>
<button type="submit" class="btn btn-default">submit</button><br/>
<div class="text-center">
<span id="success" class="text-success"></span>
<span id="warnings" class="text-danger"></span>
</div>
</form>
PHP code, basically validate and return as JSON.
<?php
require 'classes/Database.php';
$database = new Database;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
$response = [];
$errors = [];
// validate inputs
if (empty($post['title'])) {
$errors['title'] = 'Title is a required field';
}
if (empty($post['body'])) {
$errors['body'] = 'Body is a required field';
}
// errors is empty so its all good
if (empty($errors)) {
//
$database->query('INSERT INTO posts (title, body) VALUES(:title, :body)');
$database->bind(':title', $post['title']);
$database->bind(':body', $post['body']);
$database->execute();
if ($database->lastInsertId()) {
$response = [
'status' => 'success',
'msg' => 'Post added successfully added'
];
} else {
$response = [
'status' => 'error',
'errors' => [
'global' => 'Failed to insert post, contact support'
]
];
}
} else {
$response = [
'status' => 'error',
'errors' => $errors
];
}
exit(json_encode($response));
}
// guessing after this is your rendering of that form
You need to check if($_POST) instead of if($post['submit']) because in your case its not going into if condition and echo out your result. Also after echo add "exit" statement so that form will not be printed in division.

laravel api ajax form wont submit

This is my first api project. Can you help me with my code please?
I can't see the problem.
Here is my controller.
public function store(Request $request)
{
//
$valid=Validator::make($request->all(),[
'text'=>'required',
'body'=>'required'
]);
if($valid->fails()){
return response()->json(['message'=>$valid->messages()]);
}else{
$item= Item::create([
'text'=>$request->input('text'),
'body'=>$request->input('body')
]);
return response()->json($item);
}
}
and here is my form.Is there anything wrong in the form?
<form id="form">
<div class="form-group">
<label>Text :</label>
<input type="text" id="text" class="form-control col-sm-4">
</div>
<div class="form-group">
<label>Body :</label>
<textarea id="body" class="form-control col-sm-4"></textarea>
</div>
<div class="form-action">
<input type="submit" class="btn btn-primary" value="submit">
</div>
</form>
and the ajax code between the show function is working but I don't know where the problem is ?.
$('#form').on('submit', function (e) {
e.preventDefault();//prevent the form to submit to file
let text = $('#text').val();
let body = $('#body').val();
addItems(text, body);
});
function addItems(text, body) {
var item = {
text: text,
body: body
};
$.ajax({
method: 'POST',
url: 'http://localhost:8000/api/items',
data: item,
success: function (item) {
alert('done the item number' + item.id + ' has been added!!');
location.reload();
},
error: function () {
alert('error')
}
})
}
Thanks for helping!
if your front-end source separated from back-end source, then add cross-Origin Resource Sharing
package to your laravel project.
if its on your laravel view then add csrf token to meta tag -
<meta name="csrf-token" content="{{ csrf_token() }}">
and send it with your ajax request { _token : document.querySelector('meta[name="csrf-token"]').content}
The problem is that you're sending the form without sending the cross site request forgery token.
Add the directive #csrf to your view
Then send it has Hasan wrote ;)

UserFrosting forms - Invalid or missing CSRF token

I am trying to submit a simple form in UserFrosting and as a test only display the success message, with no data modification. I followed the guidance from Lesson 2 but I ran into the CSRF issue:
UserFrosting returns the following error:
Invalid or missing CSRF token.
What am I missing? Up until this point UserFrosting was very easy to digest :(
The form:
<form class="form-horizontal" role="form" name="requestDescription" action="{{site.uri.public}}/soap/requests/desc/edit/{{ keyname }}" method="post">
<div class="form-group">
<label for="input_group" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" id="input_name" class="form-control" name="lgname" placeholder="{{ name }}">
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success text-center">Update</button>
</div>
</form>
with added script part to the bottom of the twig file:
<script>
$(document).ready(function() {
// Load the validator rules for this form
var validators = {{validators | raw}};
ufFormSubmit(
$("form[name='requestDescription']"),
validators,
$("#userfrosting-alerts"),
function(data, statusText, jqXHR) {
// Reload the page on success
window.location.reload(true);
}
);
});
</script>
Here are my two functions from the controller:
public function soapRequestDescriptionEditPage($keyname){
if (!$this->_app->user->checkAccess('uri_soap_requests')){
$this->_app->notFound();
}
$requestDetails = $this->soapRequestReadMeta($keyname);
$schema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/soap-request-description-edit.json");
$this->_app->jsValidator->setSchema($schema);
$this->_app->render('soap/soap-request-description-edit.twig', [
"name" => $requestDetails['name'],
"description" => $requestDetails['description'],
"keyname" => $keyname,
"validators" => $this->_app->jsValidator->rules()
]);
}
public function test(){
if (!$this->_app->user->checkAccess('uri_soap_requests')) {
$this->_app->notFound();
}
$post = $this->_app->request->post();
$ms = $this->_app->alerts;
$requestSchema = new \Fortress\RequestSchema($this->_app->config('schema.path') . "/forms/soap-request-description-edit.json");
$rf = new \Fortress\HTTPRequestFortress($ms, $requestSchema, $post);
$ms->addMessageTranslated("success", "Everyone's title has been updated!", $post);
$rf->sanitize();
if (!$rf->validate()) {
$this->_app->halt(400);
}
$data = $rf->data();
}
Entries from the index.php file:
$app->post('/soap/requests/desc/edit/:request_id/?', function () use ($app) {
$controller = new UF\SoapController($app);
return $controller->test();
});
$app->get('/soap/requests/desc/edit/:request_id/?', function ($request_id) use ($app) {
$controller = new UF\SoapController($app);
return $controller->soapRequestDescriptionEditPage($request_id);
});
Finally, the schema:
{
"lgname" : {
"validators" : {
"length" : {
"min" : 1,
"max" : 150,
"message" : "The new title must be between 1 and 150 characters long."
}
},
"sanitizers" : {
"raw" : ""
}
}
}
As of UserFrosting 4, you should explicitly add the hidden CSRF input fields to your form. There is a partial template forms/csrf.html.twig that contains these fields, which you can insert using Twig's include tag:
<form class="form-horizontal" role="form" name="requestDescription" action="{{site.uri.public}}/soap/requests/desc/edit/{{ keyname }}" method="post">
{% include "forms/csrf.html.twig" %}
<div class="form-group">
<label for="input_group" class="col-md-2 control-label">Name</label>
<div class="col-md-10">
<input type="text" id="input_name" class="form-control" name="lgname" placeholder="{{ name }}">
</div>
</div>
<div class="form-group text-center">
<button type="submit" class="btn btn-success text-center">Update</button>
</div>
</form>
For requests that are made without a form (for example, if it has been constructed purely in Javascript), you can grab the CSRF token name and value from the global site.csrf variable:
var userName = 'luke';
var fieldName = 'lgname';
var data = {
'value': fieldValue
};
data[site.csrf.keys.name] = site.csrf.name;
data[site.csrf.keys.value] = site.csrf.value;
var url = site.uri.public + '/api/users/u/' + userName + '/' + fieldName;
return $.ajax({
type: "PUT",
url: url,
data: data
}).done(function (response) {
window.location.reload();
});
It turned out that my code was fine. There were unrelated javascript errors on the page affecting UserFrosting form processing. Fixing these errors allowed UserFrosting to handle the form.
Note to self... make it a habit to look into the console for javascript errors :)

Page is going blank after json response in laravel

Edit: Here's a little video of my problem: The video
I'm working on my socket based chat app in laravel 5.2. I was basing on this tutorial. Here's what I do and what's the problem:
I run my mysql server
I run redis-server
I run 'node server.js'
I run 'sudo php artisan serve --port=80'
I enter my site in the browser
I log in
I'm redirected to chat page
I enter an massage and send it
Page goes all white with '[]' being the only content
After running chat in two browsers and sending an message in one of them, the message appears properly on the other one. I'm running OS X ElCaptain.
Here's my routes file:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::auth();
// Route::get('/chat', 'ChatController#index');
Route::get('/home', 'HomeController#index');
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/chat', 'ChatController#index');
});
Route::post('sendmessage', 'ChatController#sendMessage');
Here's my ChatController:
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Request;
use LRedis;
class ChatController extends Controller {
public function __construct() {
// $this->middleware('guest');
}
public function index() {
return view('chat.index');
}
public function sendMessage() {
$redis = LRedis::connection();
$data = [
'message' => Request::input('message'),
'user' => Request::input('user')
];
$redis->publish('message', json_encode($data));
/*
Content-Type is set to text/html because otherwise there was an error
in JavaScript console.log:
Resource interpreted as script but transferred with MIME type application/json.
*/
return response()->json([])->header('Content-Type', 'text/html');
}
}
Here's my view:
#extends('layouts.app')
#section('title', 'CityChat')
#section('styles')
<link rel="stylesheet" href="{{ URL::asset('assets/css/chat/index.css') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
#endsection
#section('scripts')
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script src="{{ URL::asset('assets/js/chat/index.js') }}"></script>
#endsection
#section('content')
<div id="chat" class="ui container">
<div class="ui grid">
<div class="four wide column">
<div id="users" class="ui segment">
<div class="ui list">
(div.item>strong{username$})*50
</div>
</div>
</div>
<div class="twelve wide column">
<div id="messages" class="ui top attached segment">
</div>
<div class="ui bottom attached segment">
<form action="sendmessage" method="POST">
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
<input type="hidden" name="user" value="{{ Auth::user()->name }}" >
<div class="ui fluid transparent input">
<input class="msg" type="text" name="message" placeholder="Tu wpisz swoją wiadomość">
<button type="button" class="ui button send">Wyślij</button>
{{-- <input type="button" class="send-msg" name="send" value="Send"> --}}
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Of course jquery is implemented in layouts.app before the index.js, which is:
var socket = io.connect('http://localhost:8890');
socket.on('message', function(data) {
data = jQuery.parseJSON(data);
console.log(data.user);
$("#messages").append("<p><strong>" + data.user + ":</strong> " + data.message + "</p>");
});
$(".send").on('submit', function(e) {
e.preventDefault();
var token = $("input[name ='_token']").val();
var user = $("input[name ='user']").val();
var msg = $(".msg").val();
if (msg != '') {
$.ajax({
type: "POST",
url: '{!! URL::to("sendmessage") !!}',
dataType: "json",
data: {
'_token': token,
'message': msg,
'user': user
},
success: function(data) {
console.log(data);
console.log();
$(".msg").val('');
}
});
} else {
alert("Please Add Message.");
}
})
And here's the server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var redis = require('redis');
server.listen(8890);
io.on('connection', function(socket) {
console.log("client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, data) {
console.log("mew message add in queue " + data['message'] + " channel");
socket.emit(channel, data);
});
socket.on('disconnect', function() {
redisClient.quit();
});
});
I don't know what else could be helpful. I hope you will help me guys :)

Categories