Ajax Pagination Laravel 5.1 - php

I'm trying to make a pagination with ajax and laravel 5, but I can not do the ajax works even with simple tests:
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
$.ajax({
type: "GET",
url: 'testeserver.php',
//url:"raphael.dev/testeserver.php",
dataType: 'json', // Notice! JSONP <-- P (lowercase)
success:function(json){
alert("Success"+json);
},
error:function(){
alert("Error");
}
});
});
});
In this example I try one have a return on json ,
<?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>
but only with the error alert , in fact I'm trying with these following cases :
BlogController:
public function index(Request $request){
$artigos = Artigo::where('publicado_em', '<=', Carbon::now())
->orderBy('publicado_em', 'desc')
->paginate(config('blog.artigos_por_pagina'));
if ($request->ajax()) {
return Response::json(view('Blog.artigos', compact('artigos'))->render());
}
return view('Blog.index', compact('artigos'));
}
routes.php
post('/', 'BlogController#index');
get('/', 'BlogController#index');
get('/{slug}', 'BlogController#show');
jquery
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
$.ajax({
type: "POST",
url: 'page=' + page,
dataType: 'json',
success:function(json){
alert("Success"+json);
},
error:function(){
alert("Error");
}
});
});
});

Just found the solution, changed my jquery code to :
$(document).on('ready',function(){
$('.pager a').on('click', function (e) {
var page = $(this).attr('href').split('page=')[1];
e.preventDefault();
var url = '?page=' + page;
$.post( url, function(data) {
alert( "success"+data );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
And found a error in my BlogController :
in
if ($request->ajax()) {
return Response::json(view('Blog.artigos', compact('artigos'))->render());
}
the Facade Response was not declared, so just added
Use Request;
at the top,
but i still dont understand why the $ajax() dosent work, just the $get and $post

Laravel protects your application with CSRF tokens. When utilising Ajax you need to be sure to send across the CSRF token, otherwise Laravel will not process the request to protect your app.
$.ajax({
url: 'test',
type: "post",
data: {'_token': $('input[name=_token]').val()},
success: function (data) {
alert('the joys');
},
complete: function (data) {
}
});
Notice the $('input[name=_token]').val() - that will send your CSRF token. You will of course need to create a hidden input with the CSRF token in your view.
More information can be found here!

Related

laravel , ajax not working in production mode The requested URL /appointment/45/edit was not found on this server

I try to update data using ajax and laravel it working in local but in production, it's given me an error (The requested URL /appointment/45/edit was not found on this server)
I am using ajax, laravel 5.7
$(document).on('click', '.edit', function() {
id = $(this).attr('id');
$.ajax({
url: "/appointment/" + id + "/edit",
dataType: "json",
success: function(html) {
$('#name').val(html.data.name);
$('#appdate').val(html.data.appdate);
$('.modal-title').text("Edit Appointment");
$('#action_button').val("Edit");
$('#action').val("Edit");
$('#modal-default').modal('show');
}
})
});
route
Route::resource('appointment','AppointmentController');
controller
public function edit($id)
{
if(request()->ajax())
{
$data = Appointment::findOrFail($id);
return response()->json(['data' => $data]);
}
}
The requested URL /appointment/45/edit was not found on this server
I try to update data using ajax and laravel it working in local but in production, it's giving me an error (The requested URL /appointment/45/edit was not found on this server)
In ajax call use named route like
url:'{{route('route.name')}}'
And also add ajax call type
type:'post' or type:'get'
In js:
$(document).on('click', '.edit', function() {
var baseurl = window.location.protocol + "//" + window.location.host;
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
id = $(this).attr('id');
$.ajax({
url: baseurl + "/appointment/" + id + "/edit",
type: 'get',
dataType: "json",
cache: false,
success: function(response) {
$('#name').val(response.data.name);
$('#appdate').val(response.data.appdate);
$('.modal-title').text("Edit Appointment");
$('#action_button').val("Edit");
$('#action').val("Edit");
$('#modal-default').modal('show');
}
})
});
In route file (web.php)
Route::resource('appointment','AppointmentController');
In controller:
public function edit($id)
{
$data = Appointment::findOrFail($id);
return response()->json(['data' => $data]);
}

Pass data from ajax to laravel 5.1 Controller in order to save to mysql?

I need to pass data from jquery (version 1.9.1) to my Controller (Laravel 5.1) and then save it to mysql.
How to do that and pass the variable slot? It didn't work so far. For any further details, please asked me.
jquery:
$(".tic").click(function(){
var slot = $(this).attr('id');
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { _token: {{ csrf_token() }}, moves: slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
Controller:
public function addhistory(Request $request)
{
$history = new History();
$history->game_id = Game::orderBy('id', 'desc')->first()->id;
$history->moves = $request->moves;
$history->save();
return redirect()->back();
}
Routes:
Route::post('/addhistory', 'GameController#addhistory');
Errors in console:
(index):198 Uncaught ReferenceError: HAmcYRScL9puItnUGbd2kHx.... is not defined
at HTMLAnchorElement.<anonymous> ((index):198)
at HTMLAnchorElement.dispatch (191.js:3)
at HTMLAnchorElement.v.handle (191.js:3)
191.js file is the jquery version of 1.9.1
You can use this code, it may works
$(".tick").click(function (event) {
event.preventDefault();
$('.loading').show();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert("Data has been saved successfully.");
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
Try this code-
$(".tic").click(function(){
var slot = $(this).attr('id');
var token= $("input[name='_token']").val();
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { '_token': token, 'moves': slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
And in your controller you don't need return redirect because the request is asynchronous. So I am returning true. Make sure you include History model at the top of your controller
public function addhistory(Request $request)
{
$game_id=Game::orderBy('id', 'desc')->first()->id;
History::create([
'game_id'=>$game_id,
'moves'=>$request->moves
]);
return true;
}

How to pass the value using ajax to the controller in laravel

Here is my ajax
$(document).ready(function()
{
$( ".iCheck-helper" ).on( "click", function(){
var value_to_send = $('.i-check:checked').map(function() {
//alert(this.value);
return this.value;
}).get().join(', ');
});
});
Here,its my URL '/hotel/hotelresults/'.folder_name/function_name and the my Controller Name is HotelController
How should I get the ""return this.value"" using ajax to the controller.
Can Someone help me.
Try this:
$.ajax({
type: "POST",
url: "hotel/hotelresults",
data: {
key : value
},
success: function (data) {
alert(data)
}
});
Route:
Route::post('hotel/hotelresults', 'YourController#YourMethod');
In YourController:
public function YourMethod(Request $request)
{
//
return $request->key; //or return Input::get('key');
}
Please read more
docs
Thank you so much #rome 웃
I Tried like this..
$(document).ready(function()
{
$( ".iCheck-helper" ).on( "click", function(){
console.log($('.i-check:checked').map(function() {
// alert(this.value);
var value = this.value;
$.ajax({
// alert();
type: "POST",
url: "hotelresults",
data: {
key : value
},
success: function (data) {
// alert(data);
}
});
}).get().join(', '));
});
});
And in Route:
Route::get('hotel/hotelresults', 'HotelController#postHotelresults');
And in my Controller:
public function postHotelresults(Request $request)
{
//
return $request->key; //or return Input::get('key');
}
Because of giving the URL as "url: "hotel/hotelresults"," It seems to be an error in my console

ajax url won't call php file

I am trying to update the user input ratings through ajax call. This one alert(performance_rating) returned the user input ratings properly. But, I have a problem with my url. it won't call user_ratings.php. I don't know why? I have tried alert function in user_ratings.php page. But, it won't alert.
I have the user_ratings.php file in siteurl.com/include/pages/user_ratings.php
How do I call my php file properly?
ajax request
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});
If you are sending your ajax request from localhost to your domain, then you have to use full site url in your ajax call as follows
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://domain.com/include/pages/user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});
first its better you do this
define("URL", "http://siteurl.com/");
Then in the ajax url section write
url: '<?php echo URL ;?>includes/pages/user_ratings.php',
Put your FQDN (e.g. www.yoururl.com) before the user_ratings.php in your jQuery Ajax call. So change to this:
$(function () {
$('#form').on('submit', function (e) {
performance_rating = $('input:radio[name=rating]:checked').val();
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://www.yoururl.com/user_ratings.php',
data: {
rating: performance_rating
},
success: function() {
alert(performance_rating);
}
});
});
});

Ajax submit with Spry Validate

I am trying to have my form validate before the ajax runs but can't seem to get the coding right for this to happen.
if i seperate them i can post using ajax with no validation or validation but it posts the default way
here is my current code i am trying
$(document).ready(function(){
// ajax code start
$('#form').on('submit', function (e){
e.preventDefault();
if (spry.widget.form.validate('#form') == true)
{
$.ajax({
type: "POST",
url: "localProxy.php",
data: $('#form').serialize(),
success: function (response) {
document.location = '/thank-you';
// do something!
},
error: function () {
alert('There was a problem!'); // handle error
}
});
};
});
});
figured it out
$(document).ready(function(){
// ajax code start
$('#form').on('submit', function (e){
e.preventDefault();
Spry.Widget.Form.onSubmit = function(e, form)
{
if (Spry.Widget.Form.validate(form) == false) {
return false;
}
{
$.ajax({
type: "POST",
url: "localProxy2.php",
data: $('#consult').serialize(),
success: function (response) {
document.location = '/thank-you';
// do something!
},
error: function () {
alert('There was a problem!'); // handle error
}
});
};
};
});
});

Categories