CartController Method
public function update(Request $request, $id)
{
$product = Product::find($id);
$data['cart_item_id'] = $product->$id;
$data['cart_item_name'] = $product->name;
$data['cart_item_price'] = $product->price;
\Gloudemans\Shoppingcart\Facades\Cart::add($data['cart_item_id'], $data['cart_item_name'], 1, $data['cart_item_price']);
return Response::json(['success' => true, 'data' => $data]);
}
script:
<script type="text/javascript">
$('.item_add').click(function (event) {
event.preventDefault();
var data = $('.item_add').serializeArray();
$.ajax({
url: $(this).attr('href'),
data: data,
type: 'GET',
dataType: 'JSON',
success: function (html) {
alert('Hello')
}
});
return false;
});
</script>
view:
<a href="{{route('cart.update',$productItem->id)}}" class="item_add">
When Im watching network-request-response I get nothing, why don't I get data which i return from controller?
I checked your code and it works.
I can suggest you have forgotten to run "gulp" for your javascripts after you added ajax method in it (this is the only reason why you see nothing in "network-request-response"). Because, if ajax works then there would be a response (with or without error).
Related
From View Page I am calling Ajax to my Controller, from my Controller I want to create a html data so I am passing my array to View file to create a HTML data.
I don't know why when I try to do console nothing gets return, can anyone tell me where I am going wrong
CallingAjaxFromViewFile
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
alert(data);
data = JSON.parse(data);
console.log(data.html);
$('#gymimages').html(data.html);
}
});
}
}
myControllerFile
public function AjaxCurrentPastFutureData($data, $status){
$title = "HDTuto.com";
$html = view('admin.events.ajaxdataview')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
NowmyViewFile From Where I append HTML Data
<h1><i>{{ $title }} </i></h1>
Can anyone tell me where I am going wrong?
** Use this**
function AjaxgetCheckInChekOutUser(status){
var url = "{{ url('admin/events/ajaxData') }}";
var token = $('#token').val();
if(status){
$.ajax({
url: url,
type: 'POST',
data: {'status': status,'_token':token},
success: function (data) {
$('#gymimages').html(data.html);
}
});
Also update your Controller function
public function AjaxCurrentPastFutureData(Request $request){
$title = "HDTuto.com";
$html = view('my')->with(compact('title'))->render();
//pr($html);
$response = response()->json(['success' => true, 'html' => $html]);
return $response;
}
I am trying to code a simple search functionality for learning purposes, but I am failing to make it work.
What I want for now is simply to pass some data(to a controller function) in a blade view with ajax and then display this data in another view via the same controller function.
What I currently have is this :
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$data = $request->data;
return view('search-results')->with('data',$data);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1>{{$data}}</h1>
#endsection
And finally the ajax :
var data = "success";
$.ajax({
url: 'search-results',
type: "get",
data: {data : data},
success: function(response){
if(data == "success")
console.log(response);
}
});
Can someone help me make this work? I am not sure what am I doing wrong...
You should return JsonResponse object to easy use data in JavaScript
Action:
public function search(Request $request){
$data = $request->data;
return new JsonResponse(compact('data'));
}
JavaScript:
$.ajax({
url: "/search",
type: "get",
data: {data : data},
success: function(response){
console.log(response);
}
});
Routes :
Route::get('/search-results', 'HomeController#search')->name('search');
search in HomeController :
public function search(Request $request){
$result = [];
$result['data'] = $request->data;
return response()->json($result);
}
the search-results view
#extends('layouts.app')
#section('content')
<h1 class="header"></h1>
#endsection
Ajax call :
var data = "success";
$.ajax({
url: "{{ route('search') }}",
type: "get",
data: {'data' : data},
success: function(response){
if(response.data == "success")
console.log(response.data);
$('.header').text(response.data);
}
});
Hope it's help you!!!
An AJAX call is asynchronous therefore you can make a call and return the results in a separate form. If you want to show your results in a separate form, i advise that you submit the form and then return the view with your data return view('search-results')->with('data',$data); or if you stick to an an ajax call, you return a response which will be sent to the form where the data was submitted from return response()->json(["data" => $data]);
I have a shopping cart which is stored in session and I want to refresh the session without reloading the page
I have tried this:
View:
Add to cart
<script>
$(document).ready(function() {
$('#product').click(function(event) {
event.preventDefault();
let url = "{{ route('add-to-cart') }}";
let id = $(this).data('id');
$.ajax({
url: url,
type: 'POST',
data: {product_id: id, _token: "{{ Session::token() }}"}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
});
});
Route:
Route::post('/add-to-cart', 'ProductsController#addToCart')->name('add-to-cart');
ProductsController:
public function addToCart(Request $request)
{
if ($request::ajax()) {
$id = $request->product_id;
$product = Product::find($id);
if (Session::has('products')) {
$products = Session::get('products');
$products[] = $product;
Session::put('products', $products);
}
else {
$products = array($product);
Session::put('products', $products);
}
return response()->json();
}
}
And when I click add to cart it gives 500 (Internal Server Error) in the console
You're accessing the ajax() method statically (using ::), when you should be using -> instead:
if ($request->ajax()) {
Using the Laravel log file
As mentioned in the comments, Laravel is probably telling you this in storage/logs/laravel.log, complete with a long call-stack trace (the lines that you mentioned, beginning with "#38" and "#39"). Just scroll up to before "#1" and you'll find your culprit.
Laravel doesn't allow without passing X-CSRF-TOKEN,
following is my working example hope it helps you.
Route :
Route::post('block-user','UserController#BlockUser');
Now you need to add ajax setup before your ajax call so in
blade.php :
Add this in header
<meta name="csrf-token" content="{{ csrf_token() }}" />
My script like :
<script>
//Ajax setup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Ajax call
$(".blockuser").bootstrapSwitch();
$('.blockuser').on('switchChange.bootstrapSwitch', function () {
var userid = $('#userid').val();
$.ajax({
url:'/block-user',
data:{user_id : userid},
type:'post',
success: function(data){
alert(data);
}
});
});
</script>
Controller :
public function BlockUser(Request $request)
{
$userid = $request->get('user_id');
//perform operation
}
I'm trying to pass a long Html string from a view to a controller using an ajax call, so I can pass it further to another view.
Markup:
<a id="openPDF">Save as PDF</a>
JS:
$('#openPDF').click(function(){
var htmlText = $( "div.modal" ).html(); //grab the html
var dataToSend = JSON.stringify("{strData : '" + htmlText + "' }");
console.log(dataToSend ); // contains the json
$.ajax({
url: "/dashboard/pdf",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!" + type.responseText); }
});
});
Controller:
public function pdf(){
$data['htmlString'] = json_decode($this->input->post('strData'));
$this->load->view('pdf', $data);
}
My ajax call doesn't work because when a click the #openPDF button i get the alert error:
ERROR! NULL
What am I doing wrong?
Are you setting your headers properly before writing the output?
Controller:
public function pdf() {
$data['htmlString'] = json_decode($this->input->post('strData'));
$viewString = $this->load->view('pdf', $data, true); // this returns view as string rather than outputting it
header('Content-Type: application/json');
echo json_encode(['viewString' => $viewString]);
}
In client-side js, you can pass this success function to $.ajax()
success: function (response) {
if ('undefined' !== typeof response.viewString) {
// append view to concerned element
$('#viewTarget').append(response.viewString);
} else {
console.log('response did not contain viewString');
}
},
I hope this helps.
Also:
Navigate directly to the url (the one you are sending an ajax request for) in your browser and see if you get a valid json output.
I have in my controller a function to make a search filter.
The search parameter is obtained from a select field of my twig template.
The selected option is passed to the controller to see where results are with that value.
The query result is returned in JSON format.
Controller:
public function categoryAction(Request $request)
{
$category = $request->request->get('category');
$contentCategory = $em->getRepository('MyAppBundle:Content')->findByCategory($category);
$filterContent = new JsonResponse();
$filterContent->setData([
'categoryResult' => $contentCategory
]);
return $filterContent;
}
Twig template:
$('#selectCategory').change(function() {
var optionSelect = $(this).val();
$.ajax({
url: '{{path('playlist_category') }}',
data: '&category='+optionSelect,
type: 'POST',
success: function(filterContent) {
},
error: function(e){
console.log(e.responseText);
}
});
});
How I can display the result returned in JSON in my function 'success'?
You should change your JS code to the following. I would rather user $.post than $.ajax. And don't forget to pass json as fourth arg.
$('#selectCategory').on('change', function () {
var optionSelect = $(this).val();
$.post("{{path('playlist_category') }}", {category: optionSelect}, function (res) {
console.log(res);
}, 'json');
});