Ajax call problems - php

I have some problems with my ajax call, I have a collection group and when I click on show link it should show me the collection's tasks.The problem is when I try to create new tasks for the current collection.I made 50% of the problem, because it creates the records in database, but something strange happen.
Form is already submitted even If I do not click the create button
After ajax call, it creates the records in database, but it does not append the newly created element, it shows me this:
Ajax call response
Here is my ajax script:
$(document).ready(function() {
// store task
$('#create-task').click(function (event) {
event.preventDefault();
$.ajax({
type: 'post',
dataType: 'json',
data: $('#create-task-form').serialize(),
success: function (data) {
$('#create-task-form').trigger('reset');
$('#createTaskModal').modal('hide');
$('.collections').append('<li>' + data.name + '</li>');
}
});
});
});
I did not set the url, because when I do that it shows me something like this, and I do not know why.
Duplicate collection/collection/id
Set the url
Routes:
// Collection routes
Route::prefix('collections')->middleware('auth')->group(function() {
Route::get('/', 'CollectionController#index')->name('collections.index');
Route::post('/', 'CollectionController#store')->name('collections.store');
Route::get('/{collection}', 'CollectionController#show')->name('collections.show');
Route::get('/{collection?}/edit', 'CollectionController#edit')->name('collections.edit');
Route::patch('/{collection?}', 'CollectionController#update')->name('collections.update');
Route::delete('/{collection?}', 'CollectionController#destroy')->name('collections.destroy');
Route::post('/{collection?}', 'CollectionController#storeTask')->name('tasks.store');
});
Controller
public function storeTask(Request $request)
{
$attributes = $request->validate([
'name' => 'required|min:3',
'description' => 'nullable|min:3',
'status' => 'required',
'due' => 'nullable|date'
]);
$attributes['collection_id'] = $request->collection;
$task = Task::create($attributes);
return Response::json($task);
}
PS: I can still create records, even the validation from back-end fails!

Based on your image your routing is wrong.
You get a 404 for trying to access collections/collections twice leading to a non existing URL of course.
A solution to this would be:
url: {{ url('/collections/25') }},

Related

Laravel undefined variable into blade after calling from JSON

I've Signup form in my website. It was properly submitting before. Now I wanted to submit my form using ajax and wanted to return a variable from controller into JSON that I will use into blade file.
The form is submitting and values are showing into database but after redirection, it returns error.
Undefined variable: seller in report blade
I tried to decode my variable to make it work but still the same error.
How would I make it work?
Report-Blade
#foreach(json_decode($seller, true) as $row)
<a href="{{route('Report', $row->id) }}" >
{{ __('Show Report of ')}} {{$row->car_title}}
</a>
#endforeach
Controller
$seller = Sellers::take(1)->latest()->get();
return response(view('report',array('seller'=>$seller)),200, ['Content-Type' =>
'application/json']);
JavaScript
$("#submit-all").click(function(e){
e.preventDefault();
var _token = $('input[name="_token"]').val();
$.ajax({
type: "post",
url: "{{ route('form_for_private_sellers') }}",
data : $('#msform').serialize() + "&_token=" + _token,
dataType: 'JSON',
beforeSend: function(){
// Show loading image
$("#se-pre-con").show();
},
success: function(data) {
window.location = "http://127.0.0.1:8000/report/";
},
complete:function(data){
// Hide loading image
$("#se-pre-con").hide();
}
});
});
As understood from your comments,
window.location = "http://127.0.0.1:8000/report/";
will hit the route
Route::get('/report', function () {
return view('report');
})->name('private_seller_report');
Report blade expects a variable named $seller, and it is not being sent from the route. You would need to change the route to something similar to this:
Route::get('/report', function () {
$sellers = Seller::get(); //your logic
return view('report', ['seller' => $sellers]);
})->name('private_seller_report');
Alternatively you can point the route to a method in a controller if you want to avoid bulking up your routes.
you need two route for this
first for rendering blade
return view('report');
and the second for fetch seller
$seller = Sellers::latest()->take(1)->get();
return $seller

How can i pass data to some view file rather send control back to ajax call in laravel

I am making an ajax post request to controller where i fetch some details, now i don't want to send control back to ajax rather i want to pass data to some view.
return response()->json(['students' => $students]);
instead i want to do like this
return view('frontend.student.leadThanksPage',compact('students'));
ajax call
$.ajax({
type:"POST",
url:"{{ route('check.student.detail') }}",
data:$(this).serialize(),
success: function(data){
//....... },
error: function(data){
//........ }
});
and my route is
Route::post('fetch/student/detail', [ 'as'=>'check.student.detail',uses' => 'Frontend\Student\StudentController#fetchStudentDetail' ]);
Yes, You can render a view in the Laravel by returning view.
You need to configure the route whether the AJAX request is 'get' or 'post' like below,
Route::post('/ajax/GetContent', array(
'uses' => 'AjaxController#loadContent'
));
And you can do the implementation in your controller,
public function loadContent(Request $request )
{
// you can do your coding
return view('frontend.student.leadThanksPage')->with('students', $students);
}
}
Nothing needs to return in your Ajax response.
Happy Coding,
AK

Laravel 5.1 save something in database with ajax call

I am building an application where users can upload projects. I am implementing a system where users can 'Like/Unlike' other projects. I am trying to use an AJAX call to save likes. Users are able to like projects on the detail page of a project (/projects/{id})
I have a table users, projects and likes. My plan is to save the likes in the likes table obviously so a record looks like this: id, user_id, project_id. In the future I can do a COUNT query and find out how many likes each project has, etc.
For some reason when I click on the like button my application gets stuck and keeps loading until it crashes.
My files:
Ajax call
$(document).ready(function(){
console.log("js loaded");
$('#likeform').on('submit', function(e) {
console.log("like submitted");
e.preventDefault();
$.ajax({
url: $(this).parent().attr('action'),
type: "post",
data: {'_token': token, 'user_id': $('input[name=user_id]').val(), 'project_id': $('input[name=project_id]').val()},
success: function(data){
alert(data);
}
})
});
});
My Form
{!! Form::open(array('url'=>'projects/'.$project->id.'/like','method'=>'POST', 'id'=>'likeform')) !!}
<input type="hidden" id="token" value="{{ csrf_token() }}">
{!! Form::Submit('Like', array('class'=>'send-btn')) !!}
{!! Form::close() !!}
My Routes:
Route::get('/', 'LikeController#index');
Route::post('projects/{id}/like', 'LikeController#like');
My like function in the LikeController:
public function like()
{
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}
The
gets stuck and keeps loading until it crashes
part may be related to the fact that the ajax post expects some kind of response, but you are not responding at all in your controller. Try something like
public function like()
{
if(Request::ajax()) {
$data = Input::all();
return Response::json([
'error' => false,
'insertedData' => $data
], 200);
}
}
Remenber to use Response in your controller. Now you are returning something to the ajax call and you should be able to access $data
success: function(data){
alert(data.insertedData);
}
Are you experiencing the same behaviour? If not you can move on and perform the actual db insert.

ajax request in laravel 5

im not sure how to do this in laravel. Im trying to do a simple ajax request to my controller. Then in my controller return the values that i sent through so i can console.log the data.
However im having a problem doing so.
Ajax Request:
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
jQuery.ajax({
url:'/group/create',
type: 'GET',
data: {
name: groupName,
colour: "red"
},
success: function( data ){
console.log(data);
},
error: function (xhr, b, c) {
console.log("xhr=" + xhr + " b=" + b + " c=" + c);
}
});
Route:
Route::get('/group/create', ['middleware' => 'auth', 'uses' => 'GroupController#create']);
Controller:
public function create()
{
$data = Request::all();
return json_encode($data);
}
Now when i console.log the returned data it shows at the exact html for the page im on. Any ideas?
Check on the browser console-network-lastprocess- preview, it could show you the error.
Also you can "console log" from the controller using Log::info('useful information') and it will show it to you at storage/logs/laravel.log
You should use Laravel's JSON return: return response()->json(['name' => 'Abigail', 'state' => 'CA']);
But also what you're doing is actually calling a GET with data however it should be a POST in this case. If you have to provide data to a controller, it's a POST and you can just return the data that way.
So change your AJAX to be POST and then you can use the Request::all() to get all data, and return it via JSON.

ajaxOnValidation and ajaxSubmitButton in Yii not working together

I have a jQuery dialog popup form shown within an iframe on Yii. If the form validates, it needs to save and close, otherwise it needs to show with the errors. However, while the validateOnChange is working, the validateOnSubmit doesn't - clicking on submit just returns the output of the view, instead of the errors (or an empty array). I'm not really sure where to start with fixing it.
I have these options in the beginWidget() call:
'enableAjaxValidation'=>true,
'clientOptions' => array(
'validateOnSubmit'=>true,
'validateOnChange'=>true,
'validateOnType'=>false,
),
And I am using this code to generate the button:
CHtml::ajaxSubmitButton('Submit', 'enter', array('success' => 'afterValidate()'));
I found a couple of other links talking about the problem of these two options not working together at: Yii ajaxSubmitButton() with fields validation and
http://code.google.com/p/yii/issues/detail?id=2008. However, I'm not sure what to do with the suggested fix in the last link:
function afterValidate(form, data, hasError){
if (!hasError) {
$.ajax({
url: '{$postUrl}',
type: 'POST',
dataType: 'json',
data:jQuery(this).parents("form").serialize()
})
.done(function ( response ) {
// my successhandler
})
.fail(function ( xhr, status ) {
// my error handler
});
return false;
}
}
The callback function is being called, but always fails, whether the data is valid or not.
So, how do I implement a jQuery dialog form in Yii?

Categories