Internal Server error during file uploading in laravel5.3 - php

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

Related

Validate if value in input field is an Instagram URL in blade.php

I am using blade.php in my development, and I have a concern in validating if the input is a valid instagram url. I have tried doing this:
<form class="search_form" id="apply" action=" method="post">
#csrf
<label>
<input type="url" pattern="https?://.+" required id="instagram" value="" placeholder="Instagram Post URL (Paste Here)">
</label>
<div class="flex_box">
<button class="btn pink applyfnsh_btn" type="button" id="save">Confirm</button>
</div>
</form>
UPDATE this modal is displayed after validation
<div class="applyfnsh_modal">
<div class="applyfnsh_box">
<div class="modal_close">
<img src="../../assets/images/close.png" alt="close">
</div>
<p>Success</p>
</div>
</div>
modal.js
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
location is here
<script src="{{ url('/assets/js/modal.js') }}"></script>
And by the way, I'm using ajax in saving data to db so that page is not refreshed.
<script>
$(document).on("click", "#save", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url : $("#instagram").val(), user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
});
</script>
This isn't working and even processes the data when the button is clicked even if the input is not a url or empty.
Is there a way to do it without making a function?
here it is :
$(document).on("click", "#save", function() {
var instagramLink = $('#instagramLink').val();
var pattern = new RegExp('https://www.instagram.com/p/(.+?)', 'g');
if((instagramLink != undefined || instagramLink != '') && instagramLink.match(pattern)){
alert(instagramLink + 'is valid');
/*
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: '/contest/apply/{{ $contest->id }}',
data: {url :instagramLink, user_id: 1, contest_id: {{ $contest->id }} },
success: function(store) {
},
error: function() {
}
});
*/
}else{
alert('Please Enter Valid Instagram Link');
$('#instagramLink').val('');
// show modal
$('.applyfnsh_modal').modal('open');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<form class="search_form" id="apply" action="" method="post">
<label>
<input type="url" required id="instagramLink" value="" placeholder="Instagram Post URL (Paste Here)" class="form-control"/>
</label>
<div class="flex_box">
<button class="btn btn-primary" type="button" id="save">Confirm</button>
</div>
</form>
</body>
</html>
update-2 : remove your existing scripts :
$(".applyfnsh_btn").on("click", function(){
$(".apply_modal").toggleClass("open");
$(".applyfnsh_modal").toggleClass("open");
});
$(".applyfnsh_modal").on('click touchend', function(event) {
if (!$(event.target).closest('.applyfnsh_box').length) {
$(".applyfnsh_modal").toggleClass("open");
$("body").toggleClass("open");
}
});
display modal using this way when it is required to display :
to OPEN MODAL : $('.applyfnsh_modal').addClass('open');
to CLOSE MODAL : $('.applyfnsh_modal').removeClass('open');
so
if (validation successfull){
// submit form using AJAX
}else{
$('.applyfnsh_modal').addClass('open');
}
also create one function to close modal :
$(document).on('click','.modal_close',function(){
$('.applyfnsh_modal').removeClass('open');
});

Ajax from submit is not working in codeigntier with out page refresh

guys, I am trying to submit my form using ajax but I don't know exactly what happened it's not posting the values to my table in the database, This is the first time I am using ajax for form submit can anyone help me what mistake I have done.
Here is my view code:
<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro|Open+Sans+Condensed:300|Raleway' rel='stylesheet' type='text/css'>
<script type='text/javascript' src="<?php echo base_url(); ?>assets/theme1/js/jquery-2.1.3.min.js"></script>
<!-- <script type="text/javascript"> -->
<script type = "text/javascript">
// Ajax post
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
var organisation_name = $("input#organisation_name").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Organisation/createOrg",
dataType: 'json',
data: { organisation_name: organisation_name },
success: function(res) {
if (res) {
// Show Entered Value
jQuery("div#result").show();
jQuery("div#value").html(res.organisation_name);
}
}
});
});
});
</script>
<div class="modal fade" id="createGroup" tabindex="-1" role="dialog" aria-labelledby="createGroup" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content" id="modal-content">
<form action="" id="user-groups-create" class="form-horizontal" method="post">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Create a New Organisation</h4>
</div>
<div class="modal-body" id="modal-body">
<div class="form-group">
<label for="group_name" class="col-sm-4 control-label">New Organisation Name : </label>
<div class="col-md-8">
<input type="text" id="organisation_name" name="organisation_name" class="form-control" placeholder="Organisation Name" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" value="submit" class="btn btn-primary submit" id="submit">Create Organisation</button>
</div>
</form>
</div>
</div>
</div>
Here is my controller's method createOrg:
public function createOrg() {
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('organisation_name', 'organisation_name', 'required|min_length[5]|max_length[15]');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error', 'Organisation name need to be more than 3 characters and less than 15.');
redirect('Organisation', $error);
} else {
//Setting values for tabel columns
$data = array(
'organisation_name' => $this->input->post('organisation_name')
);
//Transfering data to Model
$this->Org_model->orgInsert($data);
$this->session->set_flashdata('success', 'Organisation created.');
//Loading View
redirect('Organisation');
}
}
Here is my Model's method orgInsert:
function orgInsert($data) {
// Inserting in Table(organisation)
$this->db->insert('organisation', $data);
}
Can anyone help me what mistake I have done and I have checked my code properly I didn't find exactly where I have done a mistake and I want my modal popup should be there after submitting it until a user clicks on the close button. when I try to keep alert after jQuery.ajax({ it is not coming alert.. and I can able to get the value from var organisation_name in alert...
Thanks in advance.
Hope this will work you :
$('#user-groups-create').on('submit',function(e){
var organisation_name = $("#organisation_name").val();
$.ajax({
type: "POST",
url: "<?=site_url('Organisation/createOrg');?>",
dataType: 'json',
data: {'organisation_name': organisation_name},
success: function(res) {
if (res)
{
alert(res);
window.location.href = "<?=site_url('Organisation');?>";
$("div#result").show();
$("div#value").html(res.organisation_name);
}
},
});
e.preventDefault();
});
Your controller's method createOrg should be like this :
public function createOrg()
{
$data = array(
'organisation_name' => $this->input->post('organisation_name')
);
//Transfering data to Model
$this->Org_model->orgInsert($data);
$this->session->set_flashdata('success', 'Organisation created.');
echo json_encode($data);
exit;
}
}
Working by changing the script to like this
<script type="text/javascript">
// Ajax post
$(document).ready(function() {
$('form').submit(function(e){
e.preventDefault();
var organisation_name = $("input#organisation_name").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "Organisation/createOrg",
dataType: "html",
data: {organisation_name: organisation_name},
success: function(data) {
alert('success');
}
});
});
});
</script>

Send $_POST and $_FILES together using AJAX data field so that PHP can grab the value?

I have the following form which has
a text field
date field
a file browser.
I am using AJAX to send the $_POST data values to another PHP file to insert into a MySQL database. But I want to move the $_FILES too.
In the $.ajax field, there is data: whereby I can assign those data to be transferred to another PHP file.
I am able to do it with the text field and date fields. How to do it for the $_FILES? My codes are as below
AJAX
<script>
$("#submit").click(function() {
var prjId = $('#prjId').val();
var updatedDate = $('#updatedDate').val();
$.ajax({
type: 'POST',
url: "process.php",
data: {prjId: prjId,updatedDate: updatedDate},
success: function(response) {('#resulting').html(response);}
});
});
</script>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/png" href="images/version-control.png">
<meta charset="utf-8">
<link href='https://fonts.googleapis.com/css?family=Raleway:400,300,700,900' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<body>
<div class="container" id="contactform">
<form method="post" enctype="multipart/form-data">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Project ID</label>
<div class="col-sm-7"><?php if(isset($_POST['prjId'])){echo '
<input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId" value="'.$_POST['prjId'].'">';}else{echo'
<input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId">';}?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Updated Date</label>
<div class="col-sm-7"><?php if(isset($_POST['udatedDate'])){echo '
<input type="date" class="form-control" name = "updatedDate" id="updatedDate" value="'.$_POST['udatedDate'].'">';}else{echo '
<input type="date" class="form-control" name = "updatedDate" id="updatedDate">';}?>
</div>
</div>
<fieldset class="form-group ">
<label class="btn btn-default tempPerm" id="techLabelText">
<input class="tempPerm" style="" type="file" name="file" id="techInputBoxValue" />
</label>
</fieldset>
</form>
<div class="cover">
<div id="result"></div>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
</div>
</body>
</html>
PHP
<?php include ("../db.php");?>
<?php
$prjId = $_POST['prjId'];
$updatedDate = $_POST['updatedDate'];
if(isset($prjId)){
$sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
mysqli_query($conn, $sql);
}
?>
The code below automatically includes all fields from the form without manually adding them using the append function.
Also added $(document).ready(function() for fail safe. So the javascript code only takes effect when the whole document is ready.
You can try tinker with these working template.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var FD = new FormData($('form')[0]);
$.ajax({
type: 'POST',
url: "process.php",
processData: false,
contentType: false,
data: FD,
success: function(response) {
$('#resulting').html(response);
}
});
});
});
</script>
process.php
<?php include ("../db.php");?>
<?php
$prjId = $_POST['prjId'];
$updatedDate = $_POST['updatedDate'];
if(isset($_POST['prjId'])){
$target_dir = "uploads/";
$target_file = $target_dir.basename($_FILES["file"]["name"]);
$save_file = basename($target_file); // this holds the filename to save.
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$is_uploaded = move_uploaded_file($_FILES["file"]["tmp_name"], $target_file));
// Modify this query string to add the file uploaded as well.
// Change the query string to use prepared statements for failure safe and for security reasons.
$sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
mysqli_query($conn, $sql);
}
?>
^ Added a simple file upload handler.
You can use formdata to send your files along with your request like this:
<script >
$("#submit").click(function() {
var formData = new FormData();
var prjid = $('#prjId').val();
var updatedDate = $('#updatedDate').val();
formData.append( 'file', input.files[0]);
formData.append('prjId', prjid);
formData.append('updatedDate', updatedDate);
$.ajax({
type: 'POST',
url: "process.php",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(response) {
$('#resulting').html(response);
}
});
});
</script>
If you submit form using ajax it will not pass $_FILES
you have to create object for that using FormData
note : please add enctype="multipart/form-data in form tag
<form id="upload" enctype="multipart/form-data">
please refer : jQuery AJAX file upload PHP
Thanks

Upload file with AJAX not working

i'm trying to recreate this guide from olanod answer but isn't working for me.
I want to upload a file using AJAX but i'm getting an empty $_POST:
<form enctype="multipart/form-data">
<input type="file" name="file">
<br>
<input type="text" name="as" value="asd">
<!--<button type='button' class="add_more">Add More Files</button>-->
<input type="button" value="Upload" />
</form>
and this is my script (copy paste from olanod answer ):
<script>
$(document).ready(function(){
/* $('.add_more').click(function(e){
e.preventDefault();
$(this).before("<input name='upfile[]' type='file'/><br>");
});*/
$(':button').on('click', function()
{
$.ajax({
// Your server script to process the upload
url: 'ajax.php',
type: 'POST',
// Form data
data: new FormData($('form')[0]),
// Tell jQuery not to process data or worry about content-type
// You *must* include these options!
cache: false,
contentType: false,
processData: false,
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) {
// For handling the progress of the upload
myXhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('progress').attr({
value: e.loaded,
max: e.total,
});
}
} , false);
}
return myXhr;
},
});
});
});
</script>
As i said, i'm tring to see what i'm taking and this is the result from my php file:
array(1) {
["as"]=>
string(3) "asd"
}
I returned a text field to be sure.
P.D: Sorry for my english. I hope you can understand me, i'm trying my best!
Check this one..
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax Image Upload</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="../js/jquery-3.1.1.min.js"></script>
<script src="../js/validator.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<span id="msg"></span>
<h2>Image Upload Form</h2>
<form data-toggle="validator" role="form" name="image-form" method="post" enctype="multipart/form-data" id="my-form" action="<?php $_SERVER['PHP_SELF']; ?>">
<div class="form-group">
<label for="image">Image:</label>
<input type="file" id="image" name="image[]" data-error="Upload Image" multiple required>
<div class="help-block with-errors"></div>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function (e) {
$("#my-form").on('submit', (function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
$("#my-form")[0].reset();
//alert(data);
$("#msg").html(data);
},
});
return false; //IE
}));
});
</script>
As #user2486 said,
You should use $_FILES not $_POST – user2486
He is right.
you can use this method to upload file
html-
<input type="file" class="btn btn-default" name="img2" id="img2" />
javascript-
var formData = new FormData();
formData.append('Photo', $('#img2')[0].files[0]);
$.ajax({
url: 'ImgUpload.php',
data: formData,
type: "POST",
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
}).done(function( msg ) {

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