Upload Image with AJAX using blade - ajax

I trying to upload image using ajax in Laravel 5. I am using following code but nothing happends:
image.blade.php
{{Form::open(array('action' => 'ImageController#store','files'=>true,'id'=>'upload_form'))}}
Title: {{Form::text('title')}}
Image: {{Form::file('image')}}
{{Form::submit('submit',['id' => 'btnAddProduct'])}}
{{Form::close()}}
#include('flash::message')
ImageController.php
public function store(Request $request)
{
$destinationpath = public_path() . '/img/';
$image=$request->input('image');
$filename=$request->file('image')->getClientOriginalName();
$request->file('image')->move( $destinationpath,$filename );
return Response::json(['success' => true, 'file' => asset($destinationpath.$filename)]);
}
Ajax code:
<script>
$(document).ready(function() {
$('#submitButtonId').on('click', function() {
$.ajsubmitButtonIdax({
url:'/imgC/store',
data:new FormData($("#upload_form")[0]),
dataType:'json',
async:false,
type:'post',
processData: false,
contentType: false,
success:function(response){
console.log(response);
},
});
});
});
</script>
Route.php:
Route::resource('imgC', 'ImageController');
What I am doing wrong?

Related

Laravel : can't read data from my Ajax jQuery code in my controller

i'm sending the section id in my ajax function,but i can't receive this data in my controller function.need your help please.
This is my jQuery:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
},
success: function(){
alert(section);
},
error: function(){
alert("error");
}
});
$.post("{{URL::to('/ajax')}} ",function(data){
$('#groupe').empty().html(data);
});
});
});
Web:
Route::post('ajax' , 'SeanceController#ajaxfct');
My function in the controller:
public function ajaxfct(Request $request){
$id = $request->section;
$groupes = \DB::table('groupes')
->where('section_id','=',$id)
->get();
return view('seance.groupe')->with([
'groupes' => $groupes
]);
}
The code is close to working perfectly, the following setup passes the data correctly:
HTML:
<select id="getGroupe">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
}
}).done(function( msg ) {
console.log('response: ', msg)
});
});
});
</script>
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SeanceController
{
public function ajaxfct(Request $request)
{
return ['received' => $request->section];
}
}
Route:
Route::post('/ajax', 'SeanceController#ajaxfct');

Random TokenMismatchException Laravel Handler

How do I resend the ajax request from getting TokenMismatchException?
Currently, this is my code.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->refresh();
}
This is my ajax request
$.ajax({
url: '/getEventsForRefCode',
type: 'POST',
async: false,
data: {
reference_code: reference_code
},
dataType: 'JSON',
success: function (data) {
}
I didn't pass any token because I already have these
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
]) !!};
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Upload images via adjusted form and dropzone and codeigniter

Im trying to upload images via dropzone/codeigniter. Unfortantly I dont get the post data to the controller and then to the modal. obviously it's not ajax where i can insert data in order to get it.
Here is part of the form:
<div class="dropzone" id="my-dropzone" name="mainFileUploader">
<div class="fallback">
<input name="file" type="file" multiple />
</div>
</div>
Here is the script:
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?=admin_url()?>invoice_items/upload_image",
data: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function () {
this.on("addedfile", function (file) {
console.log(file);
});
}
});
Here is the controller
public function upload_image(){
if ($this->input->post()) {
$this->invoice_items_model->add_image($this->input->post());
}
}
Here is the modal
public function add_image($data){
$dat = array(
'rel_name' => $data['name'],
'rel_type' => 'cms_items',
'dateadded' => date('Y-m-d H:i:s')
);
$this->db->insert('tblfiles', $dat);
}
For the one that need an answer:
var myDropzone = new Dropzone("#my-dropzone", {
url: "<?=admin_url()?>invoice_items/upload_image",
files: this,
method: "post",
addRemoveLinks:true,
acceptedFiles: '.jpg,.jpeg,.JPEG,.JPG,.png,.PNG',
init: function (data) {
this.on("sucess",function(file, xhr, formData){
});
},
dictDefaultMessage: "<?=_l('drop_files_here_to_upload')?>",
dictRemoveFile : "<?=_l('remove_file')?>"
});

Type Error: 1 is undefined in jQuery.DataTables.min.js

I am using DataTables with CodeIgniter following this tutorial.
While I am loading my view, I am getting error in console as:
Type Error: 1 is undefined in jquery.dataTables.min.js 49:323
My Controller code is:
public function index()
{
if($this->session->userdata('logged_in'))
{
$this->load->library('table');
$tmpl = array('table_open' => '<table id="doc_table"">');
$this->table->set_template($tmpl);
$this->table->set_heading('TMT_PK_Key', 'Name');
$this->load->view('doctor');
}
else
{
redirect('home');
}
}
function getDocData()
{
$this->load->library('Datatables');
$this->datatables
->select('TMT_PK_Key, Name')
->from('Doctor_Basic');
//->join('Doctor_Email', 'Doctor_Basic.TMT_PK_key = Doctor_Email.TMT_PK_key')
//->select('Email')
//->join('Doctor_Mobile', 'Doctor_Basic.TMT_PK_key = Doctor_Mobile.TMT_PK_key')
//->select('Mobile');
echo $this->datatables->generate();
}
}
My views code(some code is omitted like js call):
<html>
<body>
<?php echo $this->table->generate(); ?>
</body>
</html>
JS
jQuery(document).ready(function () {
var oTable = jQuery('#doc_table').dataTable({
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": '/ci/doctor/getDocData',
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"iDisplayStart ": 100,
"oLanguage": {
"sProcessing": "<img src='/ci/images/loading.gif'>"
},
'fnServerData': function (sSource, aoData, fnCallback) {
jQuery.ajax
({
'dataType': 'json',
'type': 'POSt',
'url': sSource,
'data': aoData,
'success': fnCallback
});
},
});
});
Data returned (inspect element=>Network=>Response):
draw:0
recordsTotal:1331
recordsFiltered:1331
data:Array
0:Object
TMT_PK_Key:"TMTPK"
Name:"ABC"
I tried looking in forums but couldn't find the solution.
Any help will be highly appreciated.
I got it solved by updating the DataTables to 1.10.5 from the Here

Cakephp: multiply jquery binds conflict

I have a page on which i have placed several jquery sliders, some checkboxes and radio buttons.
I post is created on slidestop, change of checkboxes, change or radio buttons. This works great.
On this same page there is a table displayed with this information and in the buttons which are outbound links, i have placed id's which are posted to another controller to track the outbound clicks with their id's.
When the button is clicked a post with the id is done using jquery to this clicks controller.
This works great when the sliders, checkboxes, radio buttons aren't used. As soon as one of those elements are touched the post to this clicks controller on the buttons click doesnt work anymore.
This is what the javascript looks like:
<script type="text/javascript">
//<![CDATA[
$(document).ready(function () {
$(".btn").bind("click", function (event) {
$.ajax({
async: true,
data: "id=" + $(this).attr("id"),
dataType: "html",
type: "POST",
url: "\/clicks"
});
return false;
});
$("#saveForm").bind("slideStop", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
$(".checkbox").bind("change", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
$(".radio").bind("change", function (event) {
$.ajax({
async:true,
beforeSend:function (XMLHttpRequest) {
$("#loading").attr("style", " ")
},
complete:function (XMLHttpRequest, textStatus) {
$("#loading").attr("style", "display:none")
},
data:$("#saveForm").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#resultaat").html(data);
},
type:"POST",
url:"\/abonnements"
});
return false;
});
});
//]]>
</script>
I think it's caused by the multiple posts on the same page but i'm not sure. I have been trying to fix this the whole day but couldn't find a solution.
Update:
I found what is causing the other function to fail.
$this->Js->get('#saveForm')->event(
'slideStop',
$this->Js->request(
array('action' => 'index', 'controller' => 'abonnements'),
array(
'update' => '#resultaat',
'data' => $data,
'async' => true,
'dataExpression'=>true,
'method' => 'POST',
'before' => '$("#loading").attr("style", " ")',
'complete' => '$("#loading").attr("style", "display:none")'
))
);
The action for the .btn which is displayed in the #resultaat table is broken when the update is done by the slideStop action.
This is how the button looks like:
<td>
<?php echo $this->Html->link('Meer Info',
$link,
array('class' => 'btn btn-primary btn-block',
'target' => '_blank',
'id' => $abonnement['Abonnement']['id']
)
);
?>
</td>
The id is needed.
I have solved the issue by placing the jquery code for the button click on the element which is updated by the other jquery function. Somehow it lost the bind when the slider updated the element in which another bind is placed.

Resources