ajax request in laravel 5 - php

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.

Related

Ajax Call Back and Laravel

I have created an API which my AJAX post send values to it. AJAX does post and my laravel API does process the values. My issues is with the callback returning the value back to my AJAX post. My AJAX doesn't return the results in the success section when I do console log. I would like the results from my api to can use data to make my condition. At the moment, the console log doesn't even return a value. But in my chrome inspector under preview it shows the response from my API but not in the success section.
AJAX
var fname = "Joe";
var lname = "Test";
var processUrl = "api.example.com/z1";
$.ajax({
type: 'POST',
url: processUrl,
data: {"name": fname,"surname": lname},
dataType: 'json',
success: function(res){
console.log(res);
if(res.length >= 1){
$('#display').val(res.name);
}
}
});
PHP
public function checkResults(Request $request){
$name = $request->name." ".$request->surname;
$result = array();
$result['name'] = [$name];
return response()->json($result,201);
}
For first it will be good to return with 200 OK response code (instead of 201).
Note: If you want to just immediately get the answer for your question only, you can see the last part of this answer (usage of "done/fail" construct instead of "success/error").
Additional:
There is many patterns which are used by Client(Frontend)<->API<->Server(Backend) developers.
Approximately all APIs built without any 500 server error codes. But there is exists also many differences between APIs structures.
One of them is to send response like this (this is the only one example of response):
return response()->json([
'success' => true, // true or false
'message' => "Message about success!",
], 200); // 200, 401, 403, 404, 409, etc
The other approach is to always sending 200 OK, but message can be also about error:
return response()->json([
'success' => false, // true or false
'code' => 404,
'message' => "Resource not found!",
], 200);
This kind of methods will written under try{}catch() and will return only 200, but that messages can imitated also as an error (as in example).
The other (appropriate approach for you) is to change your Frontend AJAX functionality like this:
$.ajax({
type: 'POST',
url: processUrl,
data: {
{{--_token: "{{ csrf_token() }}",--}}
name: fname,
surname: lname
},
dataType: 'json'
}).done(function(res) {
console.log(res);
if(res.length >= 1) {
$('#display').val(res.name);
}
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("Error: " + textStatus);
});
AJAX .done() function replaces method .success() which was deprecated in jQuery 1.8. This is an alternative construct for the success callback function (like before: "success: function(){...}").
AJAX .fail() function replaces method .error() which was deprecated in jQuery 1.8. This is an alternative construct for the complete callback function (like before: "error: function(){...}").
Note: .error() callback is called on HTTP errors, but also if JSON parsing on the response fails. This is what's probably happening if response code is 200/201 but you still are thrown to error callback.
I believe this is happening because you are sending status code 201 (Created), but you need to send status code 200 (OK) to trigger the success callback.
public function checkResults(Request $request){
$name = $request->name." ".$request->surname;
$result = array();
$result['name'] = [$name];
return response()->json($result,200);
}
I couldn't find it specifically in the jQuery docs, but this SO question addresses it.
Due to the asynchronous nature of Ajax calls, do not put them in the normal execution flow of your program. See this post to get more insight.
A quick fix for your problem is to include the ajax call in a function and call that function anytime you want to interact with the server asynchronously.
var fname = "Joe";
var lname = "Test";
var processUrl = "api.example.com/z1";
ajaxCall();
function ajaxCall() {
$.ajax({
type: 'POST',
url: processUrl,
data: {"name": fname,"surname": lname},
dataType: 'json',
success: function(res){
console.log(res);
if(res.length >= 1){
$('#display').val(res.name);
}
},
error: function() {
console.log('error');
}
});
}
In addition, include an error function in the ajax call settings to handle cases where the ajax request fails. See this answer for alternative styles of doing this.

Ajax call problems

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') }},

How to pass data from controller to view in laravel?

I need to pass data from controller to view this is code :
Controller :
function requete()
{
$id = Str::random();
return view('Demo.requete', compact('id'));
}
View :
$(document).ready(function() {
$.ajax({
url: "{{ route('support.requete') }}",
method: "get",
data: data,
dataType: "json",
success: function(data)
{
$('#code').html(data.id);//nothing happens here
}
});
});
I keep getting this error :
You can do :
return view('Demo.requete', compact('id'));
Then you can use {{ $id }} directly in the blade file.
Update :
You are using ajax so you will need a json response :
return response()->json(compact('id'), 200);
Then you can do in ajax success :
$('#code').html(data.id);
You shouldn’t return a view with an Ajax request, that should be a different route to hit with the $.ajax get request. Laravel can then return JSON responses and you can use that in your success callback.
Yo
return response()->json([‘id’ => $id]);
You shouldn't use echo in the view.
You shouldn't use ajax to get the view (unless you want to receive HTML and it does not seem the case here)
You should have a different endpoint for your ajax request if you want to fetch the data asynchronously otherwise you can just return the view with all the data you need.
In case of ajax, try returning response json
function requete()
{
$id = Str::random();
return response()->json([
"id" => json_encode($id)
]);
}

ajax post data is not read yii2

I'm trying to read $_POST array posted through AJAX in a controller action using Yii::$app->request->post(), but something strange happens.
jQuery:
`
function renderGridView() {
var formId = $('#input-field :input[value!=""]');
// extract values. Make sure to send _csrf token
$.ajax({
url: "?r=value-search%2Fsearch", //this one works
method: 'POST',
data: {
searchData: formId.serializeArray(),
},
success: function(response) { //JSON array is returned.
/*$('#resultGrid').DataTable( {
data: [
response['provider']
],
columns: [
response['columns']
]
}); */
console.log(response);
}
})
}
`
PHP Controller action:
public function actionSearch() {
$data = \Yii::$app->request->post('searchData');
$tt; $svalue;
if(count($data) === 0) {throw new UserException('data is emptry');}
echo var_dump($data);
}
And here's the issue, the code above works just fine. But when I'm trying to echo $data my custom UserException 'data is empty' is thrown, instead of PHP's 'trying to pass array as a string', which I'd normally expect. What is causing this? Why does post() behave like this? Is there a technical reason to it?
just change
data: {
searchData: formId.serializeArray(),
},
to
data:formId.serialize(),
you should use ActiveForm to create your form using your model and the names will be automatically assigned to inputs which include the convention ModelName[field_name] apart from this you haven't shown your form but in your action you are getting the searchData in the post() array so I assume you have the data being posted as
[
searchData=>[
field_1=>value,
field_1=>value,
field_1=>value,
field_1=>value,
]
]

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

Categories