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
Related
In my view , let's call it View-A, I get an input from user in a prompt and assign it to a variable, and then I need to load in browser another view, say View B, while passing it that variable.
Say, in my viewA.blade.php, I have taken user's input and assigned it to variable usersInput. Now I need to send it to view B, whose route in web.php is defined at Route::get('editRecord', 'MyController#displayEditRecordView')->name('editRecordFormView');.
Question is how do I load route(editRecordFormView) in browser and pass usersInput variable to it, from javascript written in my blade view?
#Tushar In in my ViewA.blade.php:
$.ajax({
url: url_editRecordView.url,
data: {
usersInput: dataToSend.usersInput,
},
method: "get",
cache: false,
success: function (dataReturned, stringStatus, jqXHR) {
console.log("dataReturned from mYController.displayEditRecordFormView:-");
console.log(dataReturned);//check
console.log("Type of dataReturned:-" + typeof dataReturned); //SAME DATA COMES BACK, AS THE DATA I SENT
},
error: function (jqXHR, stringStatus, stringExceptionThrown) {
alert("Error! status: " + stringStatus + " ExceptionThrown: " + stringExceptionThrown);//check
}
});
In my MyController:
public function displayEditRecordFormView (Request $request) {
error_log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//check
error_log("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");//check
$title= $request->input('usersInput');
error_log("In displayEditRecordFormView: title: ".$title);//check
$allPaintingsArray = $this->getAllPaintingsArraySanitized();
$data = [
"allPaintingsArray"=>$allPaintingsArray ,
"title"=>$title
];
return view("paintings.editRecordForm")->with("allGoodData", $data);
}
Instead of AJAX call why don't use something like this:
var url = "/editRecord?usersInput=dataToSend.usersInput;
window.location.href = url;
catch variable In controller:
$title= request()->filled('usersInput');// or find a way according to Laravel version
You can make use of AJAX. Just set an event handler for when the user gives an input, and send a request containing the user input to a method in your View-A controller via AJAX and from there you can redirect to View-B along with the value that you got from the request.
EDITED
Instead of using view() method try using redirect() method like this:
return redirect()->route('editRecordFormView', ['input' => 'userInput']);
To know more about redirects please refer to this
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') }},
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)
]);
}
I want to send drop-down list data from view to controller via AJAX as a form variable using post method.
I am able to send the drop-down list data from view to controller using get method and using route parameters.
Here is my view code snippet:
function drawChart(frmyear, toyear)
{
console.log(frmyear);
console.log(toyear);
var jsonData = $.ajax({
url: "get_salesthree/"+ frmyear + "/"+ toyear +"/",
dataType: 'json',
async: false
}).responseText;
console.log(jsonData);
Route code snippet:
Route::get('get_salesthree/{frmyear}/{toyear}', array('uses'=>'Analytics\DashboardController#get_salesthree'));
For security reasons I don't want to pass user input data using route parameters. Also I have multiple user input parameters which needs to send to controller hence above method is not feasible as well. Hence any other alternative solution available in this case?
Controller code snippet:
public function get_salesthree($frmyear, $toyear)
{
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear ));
}
Dropdownlist code snippet:
<label>From Date</label>
<select id="ddlfrmyear" name="frmyear" onchange="check(this);">
<option value="-1">Select Date </option>
#foreach ($date_lists as $date_list)
<option value="{{ $date_list}}">{{ $date_list}}</option>
#endforeach
</select>
JavaScript check function:
function check(sel)
{
document.getElementById('ddltoyear').disabled = !sel.selectedIndex;
var frmyear = document.getElementById('ddlfrmyear').value;
var toyear = document.getElementById('ddltoyear').value;
console.log(frmyear);
console.log(toyear);
if (toyear != '-1')
{
drawChart(frmyear, toyear);
//drawChart();
}
}
Now I am getting check function is not defined after changing ajax call as suggested. I am wondering what it the relation between on-select event of drop-down list and AJAX route?
This is just an example for your understanding, I hope this will guide you to get your functionality.
if you don't want to show your data/parameter in URL, then you can also use Ajax Post,
$.ajax({
type: 'POST'
url: "get_salesthree/",
data: yourForm.serialize()
dataType: 'json'
and in your routes, remove variable for query string, and make it like this.
Route::post('get_salesthree/', array('uses'=>'Analytics\DashboardController#get_salesthree'));
and in your controller
public function get_salesthree(Request $request){
$frmyear = $request->input('frmyear');
$toyear = $request->input('toyear');
//do your functionality as per your need
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear ));
}
Try this jquery answer:
js:
$('form').submit(function(e){
e.preventDefault();
var frmyear = $('#ddlfrmyear').val();
var toyear = $('#ddltoyear').val();
$.ajax({
type: 'POST'
url: "get_salesthree/",
data: {frmyear:frmyear ,toyear:toyear},
dataType: 'json',
success:function(data){
console.log(data);
}});
});
laravel:
Route::post('get_salesthree/', function(Request $request){
$frmyear = $request->input('frmyear');
$toyear = $request->input('toyear');
return \Response::json(Salethree::get_formatted_salesthree($frmyear, $toyear
});
How can I retrieve data using ajax? I have my ajax code that I've been using in some of my projects when retrieving records from database but dont know how to make it in laravel 5 because it has route and controller.
I have this html
<select name="test" id="branchname">
<option value="" disabled selected>Select first branch</option>
<option value="1">branch1</option>
<option value="2">branch2</option>
<option value="3">branch3</option>
</select>
<select id="employees">
<!-- where the return data will be put it -->
</select>
and the ajax
$("#branchname").change(function(){
$.ajax({
url: "employees",
type: "post",
data: { id : $(this).val() },
success: function(data){
$("#employees").html(data);
}
});
});
and in my controller, I declared 2 eloquent models, model 1 is for branchname table and model 2 is for employees table
use App\branchname;
use App\employees;
so I could retrieve the data like (refer below)
public function getemployee($branch_no){
$employees = employees::where("branch_no", '=', $branch_no)->all();
return $employees;
}
how to return the records that I pulled from the employees table? wiring from routes where the ajax first communicate to controller and return response to the ajax post request?
any help, suggestions, recommendations, ideas, clues will be greatly appreciated. Thank you!
PS: im a newbie in Laravel 5.
At first, add following entry in your <head> section of your Master Layout:
<meta name="csrf-token" content="{{ csrf_token() }}" />
This will add the _token in your view so you can use it for post and suchlike requests and then also add following code for global ajax setting in a common JavaScript file which is loaded on every request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
So, you don't need to worry or add the csrf_token by yourself for methods who require this _token. Now, for a post request you may just use usual way to make an Ajax request to your Controller using jQuery, for example:
var data = { id : $(this).val() };
$.post(url, data, function(response){ // Shortcut for $.ajax({type: "post"})
// ...
});
Here, url should match the url of your route declaration for the employees, for example, if you have declared a route like this:
Route::post('employees/{branch_no}', 'EmployeeController#getemployee');
Then, employees is the url and return json response to populate the select element from your Controller, so the required code for this (including javaScript) is given below:
$.post('/employees/'+$(this).val(), function(response){
if(response.success)
{
var branchName = $('#branchname').empty();
$.each(response.employees, function(i, employee){
$('<option/>', {
value:employee.id,
text:employee.title
}).appendTo(branchName);
})
}
}, 'json');
From the Controller you should send json_encoded data, for example:
public function getemployee($branch_no){
$employees = employees::where("branch_no", $branch_no)->lists('title', 'id');
return response()->json(['success' => true, 'employees' => $employees]);
}
Hope you got the idea.
First check url of page from which ajax call initiates
example.com/page-using ajax
In AJAX
If you call $.get('datalists', sendinput, function())
You are actually making GET request to
example.com/page-using ajax/datalists
In Routes
Route::get('page-using-ajax/datalists', xyzController#abc)
In Controller Method
if (Request::ajax())
{
$text = \Request::input('textkey');
$users = DB::table('datalists')->where('city', 'like', $text.'%')->take(10)->get();
$users = json_encode($users);
return $users;
}
In Ajax Success Function
function(data) {
data = JSON.parse(data);
var html = "";
for (var i = 0; i < data.length; i++) {
html = html + "<option value='" + data[i].city + "'>";
};
$("#datalist-result").html(html);
}
Add in your route:
Route::post('employees', [
'as' => 'employees', 'uses' => 'YourController#YourMethod'
]);
Ajax:
Change:
url: "employees"
to:
url: "/employees"