Page is going blank after json response in laravel - php

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 :)

Related

Displaying a flash message using Laravel

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

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

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 ;)

Internal Server error during file uploading in laravel5.3

I am trying to upload a file in laravel.But every time i hit the submit button it gives me the internal server error in the console. I have checked the rote with a get request to check if the controller function is working properly and it works fine. Can any say what is the problem?
here is my code samples
route code
Route::post('/storefile','PublicationController#storeFile');
controller
public function storeFile(Request $request){
if($request->ajax()){
echo "got";
}
else echo "not ajax";
}
view
#extends('layouts.app')
#section('stylesheet')
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link type="text/css" href="/css/bootstrap-tagging.css" rel="stylesheet">
#endsection
#section('content')
<div class="validation-system">
<div class="validation-form">
<form id="test-form" action="/storepublication" method="post" enctype="multipart/form-data" >
{!! csrf_field() !!}
<div class="col-md-3 form-group1">
<label class="control-label">Upload Paper</label>
<input type="file" name="file" id="paper">
</div>
<div class="col-md-3 form-group1">
<input type="submit" id="submit" name="submit" class="btn btn-primary" value="Add">
</div>
</form>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
$("#test-form").submit(function (event) {
event.preventDefault();
var file_data = $('#paper').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "/storefile",
type: "post",
data: form_data,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
});
});
</script>
#endsection
Try to replace this
var file_data = $('#paper').prop('files')[0];
by this
var file_data = $('#paper').files[0];

Laravel 5: Ajax Post 500 (Internal Server Error)

I'm trying to submit data to the database via ajax. The submit article page works fine without ajax. I've added console.log() just to see if anything is going through, but instead I'm getting this error:
POST http://localhost/laravel-5/public/articles/create 500 (Internal Server Error)
What's wrong with my code? Is it the javascript or the controller?
EDIT: I'm getting this in laravel.log
exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53
Route
Route::resource('articles', 'ArticlesController');
Controller
public function store(Requests\ArticleRequest $request)
{
$article = new Article($request->all());
Auth::user()->articles()->save($article);
$response = array(
'status' => 'success',
'msg' => 'Article has been posted.',
);
return \Response::json($response);
}
jQuery
$(document).ready(function() {
$('#frm').on('submit', function (e) {
e.preventDefault();
var title = $('#title').val();
var body = $('#body').val();
var published_at = $('#published_at').val();
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles/create',
dataType: 'JSON',
data: {title: title, body: body, published_at: published_at},
success: function( data ) {
$("#ajaxResponse").append(data.msg);
console.log(data);
}
});
});
View
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<h1>Write a New Article</h1>
<hr>
{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
<p>
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title') !!}
</p>
<p>
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body') !!}
</p>
<p>
{!! Form::label('published_at', 'Date:') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
</p>
<p>
{!! Form::submit('Submit Article', ['id' => 'submit']) !!}
</p>
{!! Form::close() !!}
<h3 id="ajaxResponse"></h3>
#if($errors->any())
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="{{ URL::asset('assets/js/ArticleCreate.js') }}"></script>
});
When you make a request via POST to a resource controller, it automatically calls store method:
Verb Path Action Route Name
----------------------------------
POST /articles store articles.store
So, you just need to change ajax url to:
$.ajax({
type: "POST",
url: 'http://localhost/laravel-5/public/articles',
When you need to send the session token, you can add a global meta-tag like this is you website:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, just add the token via ajax's headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you are using Form::open() function (LaravelCollective) it adds a hidden input with the token as value with the name _token. So, you can remove the meta-tag and edit your ajax's headers like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('[name="_token"]').val()
}
});
That's what I got exception 'Illuminate\Session\TokenMismatchException' in C:\xampp\htdocs\laravel-5\vendor\laravel\framework\src\Illuminate\Foundation\Htt‌​p\Middleware\VerifyCsrfToken.php:53
You're hitting Laravel's CSRF protection.
http://laravel.com/docs/5.1/routing#csrf-protection
You need to pass the hidden _token field's value. This can be done automatically on all jQuery-initiated AJAX requests by doing this in your application's JS:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').value()
}
});
Or, you can manually fetch and pass the value of the _token hidden field in each of your AJAX calls.
I like to share this code to help someone to need ajax post and get with laravel
<<<<<<<<
POST
<<<<
<<look after #extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
#extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login4')}}',
type: "post",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
alert(data);
console.log(data);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::post('login4', function()
{
return 'Success! POST Ajax in laravel 5';
})->name('login4');
------------------0----------------------
------------------0----------------------
<<<<
Get
<<look after #extends<<
<<look beforeSend: function (xhr) <<
<<look use Illuminate\Http\Request in Routes<<
<<<------<<views\login\login.blade.php<<<<-----------<<<
#extends('cuerpito.web')
<meta name="csrf_token" content="{{ csrf_token() }}" />
#section('content')
<form action="#" id="logForm" method="post" class="form-horizontal">
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="email" id="email" name="email" class="form-control input-lg" placeholder="Ingresa tu Email." autocomplete="off">
</div>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<div class="input-group">
<input type="password" id="password" name="password" class="form-control input-lg" placeholder="Ingresa tu Contraseña." autocomplete="off">
</div>
</div>
</div>
<div class="form-group formSubmit">
<div class="col-xs-12">
<div class="input-group">
<button type="submit" name="feedbackSubmit" id="feedbackSubmit" class="btn btn-success btn-lg" style="display: block; margin-top: 10px;">Ingresar</button>
</div>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#feedbackSubmit").click(function () {
$.ajax({
url: '{{URL::route('login2')}}',
type: "get",
beforeSend: function (xhr) {
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
data: $("#logForm").serialize(),
success: function (data)
{
if (data) {
obj = JSON.stringify(data, null, " ");
var datito = JSON.parse(obj);
console.log(datito.response);
alert(datito.response);
} else {
console.log(data);
}//else
}//success
});//ajax
return false;
});//feedbacksubmit
});//document ready
</script>
-------------0----------------------
-------------0----------------------
<<<----<<app\Http\routes.php<<<<-----------<<<
<?php
use Illuminate\Http\Request;
Route::get('login2', 'WebController#login2')->name('login2');
-------------0----------------------
-------------0----------------------
<<<----<<Http\Controllers\WebController.php<<<<-----------<<<
public function login2(Request $datos) {
if ($datos->isMethod('get')) {
return response()->json(['response' => 'This is get method']);
}
return response()->json(['response' => 'This is post method']);
}
-------------0----------------------
-------------0----------------------
You can add your URLs to the VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification:
protected $except = [ "your url", "your url/abc" ];
Well if you are looking for the sure shot answer ,here it is :
This error particularly occurs if you are missing csrf_token() in your code
Here is what I did,
<h6>ITEMS ORDERED:CLICK HERE</h6>
<input type="hidden" id="token" value="{{ csrf_token() }}">
Now With Ajax
<script type="text/javascript">
function getcart(val) {
var alpha=val;
var token=document.getElementById('token').value;
$.ajax({
type:'post',
url:'/private/getcart',
data:{'alpha':alpha,'_token': token},//this _token should be as it is
success:function (result) {
alert(result);
}
});
}
</script>
In my laravel controller
public function getcart(Request $req)
{
return response ("its");
}

Categories