I am trying to upload image by ajax. I am using Croppic Master but when I upload the image, it gives me token miss match exception. How to pass token in the below code?
<div class="col-lg-4 ">
<div id="cropContaineroutput">
</div>
<input type="text" id="cropOutput" style="width:100%; padding:5px 4%; margin:20px auto; display:block; border: 1px solid #CCC;" />
JS
var croppicContaineroutputOptions = {
uploadUrl: '<?php echo url()?>/users/cover',
cropUrl: 'img_crop_to_file.php',
outputUrlId: 'cropOutput',
modal: false,
loaderHtml: '<div class="loader bubblingG"><span id="bubblingG_1"></span><span id="bubblingG_2"></span><span id="bubblingG_3"></span></div> ',
onBeforeImgUpload: function () {
console.log('onBeforeImgUpload')
},
onAfterImgUpload: function () {
console.log('onAfterImgUpload')
},
onImgDrag: function () {
console.log('onImgDrag')
},
onImgZoom: function () {
console.log('onImgZoom')
},
onBeforeImgCrop: function () {
console.log('onBeforeImgCrop')
},
onAfterImgCrop: function () {
console.log('onAfterImgCrop')
},
onReset: function () {
console.log('onReset')
},
onError: function (errormessage) {
console.log('onError:' + errormessage)
}
}
var cropContaineroutput = new Croppic('cropContaineroutput', croppicContaineroutputOptions);
I had the same problem with ajax request and the trick bellow solved the problem.
Add the token in your template:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then in your javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Another way to include the token into your AJAX calls:
/** inside your blade **
<script>
var token = '{{csrf_token()}}'
$.ajax('url/to/api', {
....
data: {
....
'_token' : token
}
}
</script>
Essentially, as long as your request has the CSRF token within a field called _tokenit should work.
Related
I am trying to take amount from the html tags and store the amount into database but the about here
ajax code is not working and data is not stored in the database. And how to know if ajax code is redirected it's control to the laravel controller
#include('layouts.students.header')
<meta name="csrf-token" content="{{csrf_token()}}">
<body>
<div class="col">
<p class="text-right" style="font-size: 18px;">
<i class="fa fa-rupee"></i><strong
class="amount">299</strong>
</p>
</div>
<div class="form-group text-right">
<button class="btn btn-warning btn-block btn-lg
buy_now">Proceed</button>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('button').click(function(event){
e.preventDefault();
var amount = $('.amount').html();
$.ajax({
url : '{{route('razorpay')}}',
method : 'POST',
dataType : 'jason',
data : {amount :amount * 100},
success : function (Response) {
console.log(Response);
}
});
});
});
</script>
</body>
</html>
controller :
public function dopayment(Request $request)
{
$data = $request->all();
$result = Payment::insert($data);
echo "inserted";
}
In ajax method can you use dataType : 'json', instead of jason
this is my Axios component
<template>
<div>
<div class="comment">
<div class="body">
<p>{{fulluser.name}}</p>
</div>
<img class="image" :src="userimg" alt="" width="50px" height="50px">
</div>
</div>
</template>
<script>
import axiosRetry from 'axios-retry';
export default {
name: "commentcomponent",
props:
[
"comment"
],
data()
{
return{
fulluser:null
}
},
computed:
{
userimg()
{
return "/images/"+this.fulluser.image;
}
},
created() {
// axiosRetry(axios, { retries: 5 });
axios.get("/comment/userimage/"+this.comment.id)
.then(res=>
{
this.fulluser=res.data;
console.log(this.fulluser.id)
})
},
methods:
{
userimg()
{
return "/images/"+this.fulluser.image;
}
}
}
</script>
when I open the browser it works correctly but when I inspect it give me this error
app.js:44975 [Vue warn]: Error in render: "TypeError: Cannot read property 'name' of null"
but it works in the browser and it gives me all images and names
how can I fix this?
Calling axios is asynchronous. That means the component is rendered before initializing fulluser value.
So you need to consider when fulluser is null even though it may be a short period.
<p>{{fulluser && fulluser.name || ''}}</p>
Or
data()
{
return{
fulluser: {
name: ''
}
}
},
how do I use the value of console.log to change an image without reloading a page image in my css dynamically?
function reply_click(clicked_id){
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
console.log('attached');
$('#openButton').on('click', function(data) {
console.log('clicked');
$.ajax({
type: "POST",
url: "/MYUrl",
data: { _token: $('meta[name="csrf-token"]').attr('content') }
})
.done(function(data){
console.log(data);
})
.fail(function(data){
console.log('Error:', data);
});
});
});
}
I put the image I want to update
from my blade.php
<div class="inputbutton">
<span class="text">TEXT</span>
<input type="submit" class="btTxt submit" value="" id="TEXT" onclick="reply_click(this.id)">
</div>
my css file
div.inputbutton input {
background: url('/img/myimg.png') no-repeat;
cursor: pointer;
width: 100px;
height: 130px;
border: none;
background-size: 100%;
}
You need a way of identifying which image you want to change, e.g. with an id tag. If there was <img id="image1" src="old.jpg"> then you would add the following line of code.
.done(function(data){
console.log(data);
$('#image1').attr('src',data);
})
EDIT: You need to be sure that data returns a valid image URI, which you could do either by either a) using jquery-validate to check the syntax is correct or b) checking the file actually exists e.g. by making a test AJAX call to the new image address.
EDIT 2: Now you’ve shown you’re actually trying to change a bg image it should be:
$('.inputbutton input').css("background-image", "url("+data+")");
I have a search field with the same name and id inside my categories page and inside my products page.The autocomplete suggestions seems to work fine , however once I click on requested product inside the search field, it's stays on the same page and not redirecting me to the view.I want my view to show only products. This is my code so far:
After update
My routes:
<?php
Route::get('products/{id}', 'AutoCompleteController#show');
Route::get('autocomplete', array('as' => 'autocomplete', 'uses' => 'AutoCompleteController#show'));
Route::get('searchajax', array('as' => 'searchajax', 'uses' => 'AutoCompleteController#autoComplete'));
My AutoCompleteController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\MainController;
use App\Product;
class AutoCompleteController extends MainController
{
public function show(Product $product)
{
return view('content.products', ['product' => $product]);
}
public function autoComplete(Request $request)
{
$query = $request->get('term', '');
$products = Product::where('title', 'LIKE', '%' . $query . '%')->get();
$data = [];
foreach ($products as $product) {
$data[] = array('label' => $product->title, 'value' => $product->id);
}
if (count($data)) {
return $data;
} else {
return ['value' => 'No Result Found', 'id' => ''];
}
}
}
My view in products.blade.php and categories.blade.php for my autocomplete search is the same:
#extends('master')
#section('content')
<link href="http://demo.expertphp.in/css/jquery.ui.autocomplete.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="row">
<form class="navbar-form text-center " form method="GET" action=" ">
<input id="search_text" placeholder=" Search products" name="search_text" type="text" value=""
style="width: 400px; height: 35px; border-radius: 5px ; padding-left: 12px;"><br><br>
<input class="btn btn-default " type="submit" value=" Search">
</form>
</div>
<script>
$(document).ready(function () {
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
window.location = '{{ url('shop/{category_url}')}}' + ui.item.id
} // not sure if this is the correct way , please advise
});
});
</script>
#endsection
If you seems the issue with JS conflict, try below code:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
Added missing ui css too. Let me know the result.
There are a few problems:
An autocomplete response should include label and value pairs, you are returning value and id. See the jQuery UI source docs.
Your Javascript is missing the select event handler, which specifies what happens when one of the suggestions is selected. So right now clicking one will just fill the clicked value in the input field. See the jQueryUI autocomplete select docs.
Maybe you want to be able to view product ID 1 when you browse to /products/1. First you need to set up a route for that:
Route::get('products/{id}', 'AutoCompleteController#index');
Then in your controller, first fix the autocomplete response to return the right format:
foreach ($products as $product) {
$data[]=array('label'=>$product->title,'value'=>$product->id);
}
Next, still in the controller, update the method for showing your product (BTW this should probably be called show, index would usually be a list of products:
use App\Product;
class AutoCompleteController extends MainController {
// This assumes you have a Product model
public function index(Product $product) {
return view('content.products', ['product' => $product]);
}
And your Javascript:
$("#search_text").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response(data);
}
});
},
minLength: 3,
select: function( event, ui ) {
// Your autoComplete response returns the ID in the 'value' field
window.location = 'http://yoursite.com/products/' + ui.item.value
}
});
I want to delete some data from database using ajax.. I've done the following steps to run..But while I was trying to delete it's shows following Error:
Failed to load resource: the server responded with a status of 404
(Not Found)
Here is my route:
Route::post('/delete/{id}',[
'uses'=>'ItemController#delete',
'as' => 'delete'
]);
Here is the controller:
public function delete($id)
{
Item::find($id)->delete();
return Redirect::back();
}
And here is my view page:
<html>
<head>
<title> Item List</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<h3> List Of Courses </h3></br>
<table class="table table-striped table-bordered dataTable" id="example">
<thead>
<tr>
<td>Serial No</td>
<td>Title</td>
<td>Description</td>
<td>Action</td>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($items as $row)
<tr>
<td>{{$i}}</td>
<td>{{$row->title }}</td>
<td>{{$row->description}}</td>
<td>
<button type="button" onclick="deleteItem({{ $row->id }})" id="Reco" class="btn btn-danger">Delete</button>
</td>
</tr>
<?php $i++; ?>
#endforeach
</tbody>
</table>
</div>
<script>
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: '/delete/'+id,
success: function(result) {
console.log(result);
}
});
}
</script>
</body>
</html>
If anyone find the error I've done, hope you'll help me to find it out.
Generally passing parameter while deleting is not a good idea. since we can delete the data through url e.g /delete/4 while you may want to delete only after clicking the delete button.
$.ajax({
type: "POST",
url: "{{url('/delete)}}",
data:{id:id}
success: function(result) {
console.log(result);
}
});
route:
Route::post('/delete',[
'uses'=>'ItemController#delete',
'as' => 'delete'
]);
and, the controller
public function delete(Request $request)
{
$id=$request->id;
Item::where(['id'=>$id])->delete();
return Redirect::back();
}
Try this code:
function deleteItem(id) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url:"{{url('delete')}}",
data:{id:id},
success: function(result) {
location.reload();
}
});
}
try this code
function deleteItem(id) {
var _token = $("input[name='_token']").val();
$.ajax({
type: "POST",
url: '/task/'+id,
data: '_method=DELETE&_token=' + _token,
success: function (result) {
console.log(result);
}
});
}
Try this:
$.ajax({
type: "POST",
url: url('/delete'), // The correct way to call ajax function in laravel
data:{
id: id
},
success: function(result) {
console.log(result);
}
});
You can set a method destroy in your controller which laravel automatically uses for deleting. It accepts id.
public function destroy($id){
Item::find($id)->delete();
echo 'Deleted Successfully.';
}
for ajax just send a method delete with your token.
jQuery.ajax({
url:'your-controller-route/id',
type: 'post',
data: {_method: 'delete', _token :token},
success:function(msg){
// do stuff
}
});