I want to declare a global variable. Here are my actions
BaseController
protected $header_data;
public function __construct()
{
$this->header_data = HeaderData::all();
View::share('data', $this->header_data);
}
Next, in the Blog page controller, let's say I write this
$this->header_data;
And on the page itself in php.blade
<h1>{{ $data }}</h1>
But I get completely all the data from the model, and I only need a field data
[{"id":3,"url":"\/blog","data":"<title>Blog<\/title>\n<meta name=\"description\" content=\"Blog\" \/>","created_at":"2021-10-19T11:24:41.000000Z","updated_at":"2021-10-19T11:24:41.000000Z"}]
when I click on the like to update the data, I reload the page using
window.location.reload();
Can this somehow be done without reloading the page?
Yes, by not using window.location.reload();.
$.ajax({
url: href,
type: 'POST',
success: function () {
$(this).addClass('active');
},
error: function (jqXhr, status, error) {
alert(error);
},
});
Change your PHP so it doesn't return the complete page for POST requests to the /article/...?type=heart route.
In case of a "like" functionality, you practically only need feedback whether it has worked (the like was registered), or not (in which case you might want to display an error).
Your server could simply respond with status code 204 (No Content) in the success case.
Related
Ajax works well for pre-existing forms. But if I add a new form using it and submit it, then I get to the method page.
Added a new form, filled in the field and clicked Submit: http://joxi.ru/DmBOW4KUzep962
I get to the method page, instead of displaying the result in the console: http://joxi.ru/EA4P710TOekbOA
After reloading the page, everything works well.
What could be the matter, tell me please.
Front:
$('.add-answer-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: `/admin/courses/48/lessons/96/answerAdd`,
data: $(this).serialize(),
success: function (data) {
console.log('!!!!!', data);
}
});
});
Back:
public function answerAdd(Request $request, Course $course, Lesson $lesson, Test $test, Answer $answer){
$this->answer->fill($request->all())->save();
return response ()->json ($this);
}
I solved this issue as follows:
Instead of this:
$ ('.add-answer-form').on('submit', function (e) {
Added this:
$ ('#quest-add-form').on('submit', '.add-answer-form', function (e) {
This is suitable in cases where you need to work with the form that was added by Ajax.
I have been working on this for hours,and not getting anywhere. Essentially, my Ajax call appears to be working well. I am pulling in form data from a view. I can see the XHR data when I look into Chrome Network. I have a status 200, and "OK". However, no matter what I do, I can not get any data to show in my controller. I have tested my route by commenting it out and sure enough I get an error, so that is positive. Also the XHR data shows the correct url as well. But even just a simple dd($request) inside the controller gives me nothing, not even an empty []. I have tried every option and Googled this to death. What am I doing wrong - Thanks !
Abbreviated HTML
<form action="" method="POST" id="formData">
<fieldset>
{{ Form::hidden('customer_id',$customer[0]->id,['id'=>'customer_id'])}}
{{ Form::hidden('lastname1',$customer[0]->lastname1,['lastname1'=>'lastname1'])}}
{{ Form::hidden('reference',$quotation[0]->reference,['id'=>'reference'])}}
</fieldset>
</form>
AJAX
$("#editsubmit").on('click', function () {
event.preventDefault();
var formData =$("#formData").serialize();
var id = $("#reference").val();
$.ajax({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
contentType:'JSON',
processData: false,
url: '/save_edit/'+id,
data: {
"_method": 'POST',
"result": formData,
},
error: function () {
alert('there has been a system level error - please contact support')
}
});
});
Route
Route::post('/save_edit/{id}','QuotationController#save_quote_edited');
Controller
public function save_quote_edited(Request $request){
dd(json_decode($request->getContent(), true));
}
To process forms you should not be calling $request->getContent() you should be calling $request->all() to get all parameters, $request->get('foo') or $request->foo to get a single parameter, or $request->get(['foo','bar','baz') to get multiple parameters.
And for bonus points if you used Laravel's Form Request Validation you could call $request->validated() and get only the parameters which passed the validation checks.
Your route requires a parameter of "id" but you do not have that parameter in your controller method.
Route::post('/save_edit/{id}','QuotationController#save_quote_edited');
Try :
public function save_quote_edited(Request $request, $id){
*** insert code here ***
}
I wanted to submit a for using ajax call in laravel 5.
In view i wrote something like
$("#updateSubmit").on('submit',function(e){
e.preventDefault();
var csrfToken = $('meta[name="csrf-token"]').attr("content");
$.ajax({
method:'POST',
url: '/account/updateForm',
//dataType: 'json',
data: {accountId:'1111', _token: '{{csrf_token()}}'},
success: function( data )
{
alert(data)
return false;
}
},
error: function(error ){
alert("There is some error");
}
});
and on controller side
public function update(Request $data )
{
return Response()->json(['success' => true],200);
}
while in route for post method
Route::post('account/updateForm', 'AccountController#update')->name('account/updateForm');
its working till ajax. on Submission of ajax it goes to controller action.
but it does not retrun back as ajax comes back in normal form submisson.
it just go to controller and stops there with {"success":true} line.
I want ajax to come back to view form so that I can perform different dependent actions.
Do you mean that when you submit your form, you just have a white page with {"success": true} ?
If that's the case, maybe the error is on your javascript.
Maybe your jQuery selector is wrong, or maybe your js isn't compiled ?
I want to change a value based on the selected year and week with ajax.
This is my ajax function:
function changeBekeken() {
var year = $("#jaar-nr").val();
var week = $("#week-nr").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/planning/viewed",
type: "POST",
data: {
year_nr: year,
week_nr: week
},
dataType: "json",
success: function(data) {
alert(data);
}
});
}
$(document).ready(function(){
$("#week-nr").change(function(){
changeBekeken();
});
$("#jaar-nr").change(function(){
changeBekeken();
});
});
This is the route:
Route::post('/planning/viewed', 'PlanningController#viewed');
The data is send to a controller function:
public function viewed(Request $request) {
$check = DB::table('planning_files')
->where([
['user_id', Auth::user()->id],
['created_year', $request->input('year_nr')],
['week', $request->input('week_nr')],
])
->select('seen')
->first();
if($check) {
return json_encode($check, JSON_PRETTY_PRINT);
} else {
return json_encode(false);
}
}
However even when I use $request->all(); request is always empty. My function will always return false. Pretty much this exact same function works on another page, but I can't seem to get this one working.
I have tried adding some extra information to the ajax function, like content type and data type, but none seem to work.
Any tips?
Edit 1
These are the namespaces and classes I use in my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Auth;
use Storage;
Edit 2
When I copy the function to another page it works properly. It has something to do with the content on the page I use the ajax function on. Probably some conflict with the token. I will try to resolve this and post the answer for others if they might have the same problem in the future.
AJAX:
$.ajax({
type:"POST",
url: "{{url('/post/add')}}",
data: {
"_token": "{{ csrf_token() }}",
"id": id
},
success: function (data) {
var res = $.parseJSON(data);
if(res == true)
{
alert('hi');
}
}
});
Laravel Controller: I have checked for the ajax request in the controller.
public function add(Request $request)
{
if($request->ajax())
{
// codes
echo json_encode(TRUE);die;
}
}
but, I noticed that I do not require to check for ajax request? And without checking if the ajax request how am i getting the alert?
public function add(Request $request)
{
// codes
echo json_encode(TRUE);die
}
The check is simply one additional measure of a valid request. It is not necessary as you've noticed, but if you'd like to verify that the request is coming via an AJAX request as you'd expect - you may.
You should use $request->ajax() to determine if the request is the result of an AJAX call. If you're working only with AJAX requests in your method, you can omit this check.
It just depends on you. You can do different things based on if the request is AJAX request or not. For example returning JSON or a normal view.
If you want your routes to be accessed by only AJAX requests maybe you can protect those routes with a middleware. Check this answer for more information about that.