I am having trouble retrieving data from Controller using ajax
this is my code
the trigger
<select id="course_select" name="course_select" class="form-control" required autofocus value="{{old('course_select')}}" onchange="getCourse()">
The my ajax section
function getCourse(){
var id=document.getElementById('course_select').value;
alert(id);
$.ajax({
type:'get',
url:'getCourseLessons/'+id,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
and my controller
public function getCourseLessons($id){
$lessons = DB::table('lessons')->select('id','Lesson_name')->where('course_id','=',$id)->get();
return response()->json(array('lessons'=>$lessons));
}
Results console.log(data)
console.log(data)
ReferenceError: data is not defined[Learn More]
My Routes.
Route::get('/getcourselessons/{id}','AdminController#getCourseLessons');
I will appreciate all the help i can get.
First of all please check the route you used in Route/Web.php it should be like this
Route::get('getCourseLessons/{id}','YourController#getCourseLessons');
Check the controller.
public function getCourseLessons($id){
$lessons = \DB::table('lessons')->select('id','Lesson_name')->where('course_id',$id)->get();
return response()->json(array('lessons'=>$lessons));
}
As per your ajax code is ook but you can try this also.
function getCourse(){
var id=$('#course_select').val();
alert(id);
$.ajax({
type:'get',
url:'{{url('getCourseLessons')}}/'+id,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
<select id="course_select" name="course_select" class="form-control" onchange="getCourse()">
<option>hi</option>
<option>hello</option>
</select>
It seems that there is problem in your select as the above code will output
check the following
value="{{old('course_select')}}"
and one more thing I can't see CSRF
Add somewhere in your script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
1- cheek your route
Route::get('/getCourseLessons/{id}','YourController#getCourseLessons');
2- change your Ajax attributes
function getCourse(){
var id=document.getElementById('course_select').value;
alert(id);
$.ajax({
url: '{{ url("getCourseLessons") }}',
type:'get',
datatype:'json',
data: {
"id": id,
"_token": "{{ csrf_token() }}"
},
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
try this bro change you url or route
function getCourse(){
var id=document.getElementById('course_select').value;
var url = '{{ url('getCourseLessons/')}}/'+id;
alert(id);
$.ajax({
type:'get',
url:url,
datatype:'json',
success:function(data){
console.log(data);
alert(data.lessons);
}
});
}
change your route
Route::get('getcourselessons/{id}','AdminController#getCourseLessons');
Related
In my laravel package the route does not working it is showing following incorrect route in debugger
Request URL: http://localhost:8000/%7B%7B%20route('contact')%20%7D%7D
However my route is as following
Route::group(['namespace' => 'ayazdev\Contact\Http\Controllers'], function(){
Route::get('contact', 'ContactController#index')->name('contact');
Route::post('contact', 'ContactController#send')->name('sendForm');
});
And following is where I am calling the route
$(function(){
$("#contact-form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "{{ route('contact') }}",
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
});
if above detail does not enough to understand then you can kindly check it on github.
Can someone kindly guide me why it is now working, I will appreciate. Thanks
The curly braces are part of the Laravel Blade views, but you are using this in a JavaScript file. This code is not parsed by Laravel, so you cannot use php functions here.
If you want to get named routes in your JavaScript code, you will have to render them into a JavaScript variable or use a package like Ziggy to get route functionality in JavaScript.
As noted by Jerodev the curly braces are from Laravel Blade and you are probably using it in a Javascript file. Either you can move it to a blade file as such:
<script>
$(function(){
$("#contact-form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "{{ route('contact') }}",
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
});
</script>
Or if you prefer to keep it in a separate file you can have a tag with just the information about that route and get it via jQuery as you are doing:
// at the blade file add
<div id="routeToContact" data-route="{{ route('contact') }}">
// At the javascript file you can do the following
var route = $("#routeToContact").data('route');
$("#contact-form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: route,
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
As a personal taste I would chose the second method to keep everything organized but as my mom always said: "choose what your heart beats for"
You are using a Blade syntax in a simple Javascript file.
Try to do the following:
$(function(){
$("#contact-form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "<?= route('contact'); ?>",
data: form.serialize(),
success: function(data)
{
alert(data);
}
});
e.preventDefault();
});
});
That way, you use PHP itself to get the address of the desired route.
See more about this sintax in: https://secure.php.net/manual/pt_BR/ini.core.php#ini.short-open-tag
I am getting error in my AJAX response.
I am trying to view a specific patient details while clicking 'view' button from 'All Patient' table using AJAX request.
But getting error in response like below image
But I returned an 'id' from my controller.
AJAX
$(".view_prescription").click(function(){
var id = $(this).val();
var token = $('input[name=_token]').val();
$.ajax({
type:'GET',
url:'/view-prescription',
data:{
_token : "{{ csrf_token() }}",
id: id
},
success:function(data) {
alert(data);
}
});
});
Route
Route::get('/view-prescription','PrescriptionController#view_prescription');
Controller
public function view_prescription(Request $request)
{
$id = $request->id;
return $id;
}
I understand that it's a slight mistake. But I can't figure that. Anybody help please
I have solved the issue.
just change url from '/view-prescription' to "{{url('/view-prescription')}}" and comment our 'token'.
$(".view_prescription").click(function(){
var id = $(this).val();
//var token = $('input[name=_token]').val();
$.ajax({
type:'GET',
url:"{{url('/view-prescription')}}",
data:{
_token : "{{ csrf_token() }}",
id: id
},
success:function(data) {
alert(data);
}
});
});
Can someone please show a Laravel 5.7 post ajax example with a full-working minimum example in a blade template? I know there are some resources in the web, but I miss a concise, straight-forward minimum example.
You can do something like this,
web.php
Route::post('/admin/order/{id}', 'OrderController#edit')->name('admin.order.edit');
blade.php
$(document).on('click', '.delete-button', function (e) {
e.preventDefault();
var orderId = 1
$.ajax({
type: 'post',
url: '/admin/order/' + orderId,
data: {
'_token': $('input[name=_token]').val(),
'data_one': 'dataone',
},
success: function () {
toastr.success('Order Has Been Deleted Successfully.');
},
error: function(XMLHttpRequest) {
toastr.error('Something Went Wrong !');
}
});
});
$.ajax({
url: 'http://some.working/url',
type: "POST",
data: $('#formContainer').serialize(),
success: function (response) {
console.log('Success', response);
},
error: function (response) {
console.log('Error', response);
}
});
The data can be produced in many ways for example
1. Using serialize() method as shown in the above example.
2. Using FormData():
for example
var data = new FormData($('#formContainer'));
In both of the above example, one thing compulsory is that your form
must contain csrf field. which can be provided using any of the
following methods:
<input type="hidden" name="_token" value="{{ csrf_token() }}" >
or
{{ csrf_field() }}
or even more simply by just using
#csrf
in some where in your form.
In case you are not using any form, you can create the data object by
yourself like this
var data = {
_token: '{{ csrf_token() }}',
data1: 'Value1',
data2: 'Value2',
data3: 'Value2'
}
Define a Web Route
Route::get('currencies/fiat/changeStatus','FiatCurrencyController#changeStatus')->name("currencies.fiat.chanageStatus");
Call this function on click onclick="changeStatus(1,0)"
function changeStatus(id,status){
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
/* the route pointing to the post function */
url: '/currencies/fiat/changeStatus',
type: 'GET',
/* send the csrf-token and the input to the controller */
data: {_token: CSRF_TOKEN,cid:id,status:status},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(data);
}
});
}
That's it all Done.
$(document).ready(function(){
/* In laravel you have to pass this CSRF in meta for ajax request */
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
/* change in website layout base on click */
$('#user_view').on('click',function (e){
e.preventDefault();
$('.loading_screen').show();
var val = $(this).data('id');
$.ajax({
url: base_path + 'user/changeview/'+val,
type: "POST",
success: function (data) {
var obj = jQuery.parseJSON(data);
if (obj.SUCC_FLAG == 0){
window.location.href = site_url;}
else{
/* for console error message. */
console.log(obj.MSG);}
$('.loading_screen').hide();
},
error: function () {
alert("server error");
}
});
});
});
Hey it's a working code and i hope this will works for you.
I have a simple code but is not working. I want to create a more complex function but I just need the basic structure.
HTML
<span class="cleanreport">Delete Record</span>
Javascript:
$( ".cleanreport" ).click(function() {
var token = "test";
$.ajax({
data: {"data": token},
type: "post",
url: "clean.php",
success: function (data) {
console.log(data);
$('.test').html(data);
}
});
});
PHP clean.php
$data = $_POST['data'];
echo $data;
What I am doing wrong?
This should work for you:
var token = "test";
$.ajax({
type: 'POST',
url: "clean.php",
data: {id: token},
dataType: "json",
success: function(response) {
// some debug could be here
},
error: function(a,b,c) {
// some debug could be here
}
});
If not, please debug success and error parameters using console.log().
Based on jquery documentation setting type is an alias for method so this could not be a problem in you case for sure.
$( ".cleanreport" ).click(function() {
var token = "test";
$.post('clean.php",
{
data: token
},
function (data,status) {
//console.log(data);
$('.test').html(data);
});
});
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