I am trying to concatenate a variable to my url link in ajax. The variable $news is the one that handles the notification id.
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var $news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients/", $news)}}', //returning an error undefined variable news
data: {newsID : $news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});
In my web.php, it's route is inside a route group.
Route::group(['middleware' => 'auth:admin'], function () {
Route::prefix('admin')->group(function() {
Route::get('/recipients/{news}', 'Admin\NewsController#recipients');
});
});
So how can I make this work? By the way, my ajax is inside a blade.php file.
$news doesnt exist to blade because it executes on the time server is rendering the page. So your javascript hasn't been executed yet. To make this work, change you js code to this:
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients")}}' + '/' + news,
data: {newsID : news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});
Related
I'm sending the html form using ajax to laravel controller but it showing the error that MethodNotAllowedHttpException in RouteCollection.php line 251.
here is my ajax codes.
<script type="text/javascript">
function Login(){
var data = $("#login-form").serialize();
$.ajaxSetup({
headers: {
'X-XSRF-Token': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
type:"POST",
url:"userAuth",
data:data,
success: function(response)
{
console.log(response);
},
error:function(response)
{
console.log(response);
}
});
}
</script>
controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LoginController extends Controller
{
public function userAuth(Request $request)
{
$name = $request->username;
die($name);
}
}
?>
web.php codes
Route::post('/userAuth', 'LoginController#userAuth');
please let me know what I'm doing wrong thank and regards.
Request URL with the base URL & csrf token
<script type="text/javascript">
function Login(){
var data = $("#login-form").serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
$.ajax({
type:"POST",
url: baseUrl+"/userAuth",
data:data,
success: function(response)
{
console.log(response);
},
error:function(response)
{
console.log(response);
}
});
}
</script>
in your api.php file put your route
Route::post('/userAuth', 'LoginController#userAuth');
your web.php file has a middleware for CSRF protection. You can disable it but not recommended
I want to use ajax with selectize to load bdd results onchange.
I need to use post because I must send data to my url.
My function looks like this :
select_etages.load(function(callback) {
xhr && xhr.abort();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
data : { bat : value },
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
In my web.php I've got this :
Route::post('/lots/add/etages', ['as' => 'lots.add_post.select', 'uses' => 'Copro\LotController#select2']);
And my controller :
public function select(Request $request)
{
return "test";
}
But when I tried to use it, I've got an "419 unknown status". I can see that it's a post ajax and my data but I've got no error message :
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
If I change to get it's working but not post.
Anyone know why I can't use post ??
Thank for your help.
Maybe you just rewrite the "select2" name end of the route to "select"?
I think you need to remove $.ajaxSetup function in callback function. Code might look like this.
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
select_etages.load(function(callback) {
xhr && xhr.abort();
var data = { id:value }
xhr = $.ajax({
type: 'post',
dataType: 'json',
data: JSON.stringify(data),
url: 'add/etages',
success: function(results) {
callback(results);
},
error: function() {
callback();
}
})
});
});
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!
I've been stuck with a 500 (internal server error) for a long time and I don't know why. I need to pass these codes later.
Blade
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$('#addChirp').submit(function() {
var msg = $('#message').val();
console.log(msg);
var dataString = "message="+msg;
console.log(dataString);
$.ajax({
type: "POST",
url: "post",
data: dataString,
success: function(data) {
console.log(data);
$('#showData').html(data);
},
error: function(data) {
alert("fail");
}
});
});
});
Routes
Route::post('post', function() {
if(Request::ajax()) {
return var_dump(Response::json(Request::all()));
}
});
Try calling Request and Response as a global facade following
Route::post('post', function() {
if(\Request::ajax()) {
return var_dump(\Response::json(\Request::all()));
}
});
If that does not work can you please update your question with full ajax response so problem can be narrowed down?
I think you havn't added any meta value in your head tag of html like
<meta name="csrf_token" content="{{ csrf_token() }}" />
If csrf tag exist than try modify your jax call.
X-CSRF-TOKEN': $('input[name="_token"]').value()
Or, you can manually fetch and pass the value of the _token hidden field in each of your AJAX calls
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);
}
});
});
});