suppose I have $data, which is a collection of entire data of a table, is it possible to pass this collection type data in parameters via URL from view to controller?
I'm using Laravel. All the solutions I've been searching only for array type data. Thanks for help!
You can. First install the package guzzlehttp/guzzle. then try this way:
use GuzzleHttp\Client;
$client = new Client();
$sampleData = ['name' => 'billy', 'email' => 'billy#example.com']; // your collection
$url = 'http://api.example.com/bla-bla'; // your url
$res = $client->request('POST', "{$url}",['form_params' => $sampleData]);
$data = json_decode(json_encode($res->getBody()->getContents()),true);
return $data;
Make a post request from your view to the required URL.
Example:
Adapted from here
<table id="tData">
<tbody>
<tr>
<td class='dataVal1'>100</td>
...
$(document).ready(function() {
var toServer = {};
var data = $('#tData tbody tr td').each(function(key, value) {
toServer[$(this).attr('id')] = $(this).text();
});
$.ajax({
url: '/test/',
data: {
"_token": "{{ csrf_token() }}",
"table_data": toServer,
}
type: 'POST'
})
});
Now in your controller which handles the page, use the following
public function test(Request $request)
{
dd($request);
}
Note: Make sure the URL which you mention in the ajax request can accept post request.
Related
i just learn about Ajax. I am so confused and getting error after following some tutorials. The plan is after we get the id_program, we can change or reload the page to show the data inside the dropdown menu after we clicks it. May someone help me please?
1.1 Database ( Program )
1.2 Inside Payment
1.3 Inside actor
DatabaseController.php
public function data($id)
{
$client = new Client();
$response = $client->request('GET', 'http://localhost:8585/api/v1/tables', [
'query' => [
'limit' => '100'
]
]);
$data = json_decode($response->getBody()->getContents(), true)['data'];
$pay = Payment::get()->all();
$pro = Program::select('nama')->where('name', $id)->get();
$coba = Program::get()->all();
foreach ($pro as $p) {
$name = $p->name;
}
return view('database.index', compact('nama','data','pay','coba','pro','id'));
}
Route
Route::get('program/database/{database}', [DatabaseController::class,'data'])->name('database.data');
database.index
<select id="id" class="form-control" filter>
<option>Pilih Layanan...</option>
#foreach ($coba as $id)
<option value="{{$id->id_program}}">{{ $id->nama}}</option>
#endforeach
</select>
Ajax Script
$(function() {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')}
});
$(function(){
$('#id').on('change',function(){
number =$('#id').val();
console.log(number)
$.ajax({
type : 'POST',
url : "{{route('database.data',lcfirst($name))}}",
cache : false,
data:function(d){
d.number = number;
return d;
},
success: function(msg){
console.log('success')
},
})
})
})
});
Result (Error)
a. ( id_program = 1 ) Correct data output & Method Not Allowed error
b. ( id_program = 2 ) Incorrect data output & Method Not Allowed error
Thank you for the helps
Route::get('program/database/{database}', [DatabaseController::class,'data'])->name('database.data');
see the "get" key word? You are declare this route as a GET route, but your AJAX method:
$.ajax({
type : 'POST',
url : "{{route('database.data',lcfirst($name))}}",
....
is a POST request.
The solution is:
if your request only GET some data (no create, no delete, no update,... any data), then $.ajax({ type : 'GET', ....
if your request do modify data, then Route::post('program....
(1/1) ErrorException
Argument 2 passed to App\Http\Controllers\priceDetails::finalSubmit() must be an instance of Illuminate\Http\Request, none given
Error I'm getting while passing multiple parameters with controller function.
Ajax code:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
$.ajax({
url:"{{url('dbvalue')}}",
type: 'GET',
data: {form1: form1, form2: form2, form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
Laravel route:
Route::get('dbvalue','priceDetails#finalSubmit');
Controller:
public function finalSubmit(Request $priceform,Request $formdescription)
{
$var1 = $this->addPriceDetails($priceform);
$var2 = $this->addProductDetails($formdescription);
$var3 = $this->addAdditionalInformation($additionaldescription);
$var4 = $this->addImages($imagesform);
echo("success");
}
This what I'm trying to give multiple form parameters in laravel controller function.
addPriceDetails fn:
public function addPriceDetails(Request $priceform)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$priceform->input('skuid');
$priceInfo->deviceCategoryId=$priceform->input('dataId');
$id=$priceInfo->id;
$priceInfo->save();
return response()->json([
'SKUID' => $priceInfo->SKUID,
'sellingPrice' => $priceInfo->sellingPrice,
'id' =>$this->getpriceDetailsId()
]);
}
What you are attempting to do simply does not work. Just because you sent data of two form in your 1 ajax request does not mean laravel will interepret it as two request. That is simply not possible.
What you have done in your code is get get data from 3 forms and make a json object from them and sent that json object in 1 get request. You cannot send multiple request in 1 request. This is as fundamental as it gets.
The best way to get the result you want is to accept 1 request object in you controller and parse it to get data from multiple forms that you sent.
You need to make your function as
public function finalSubmit(Request $request)
{
$var1 = $this->addPriceDetails($request->form1);
$var2 = $this->addProductDetails($request->form2);
$var3 = $this->addAdditionalInformation($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have $imagesform
return response()->json(["response"=>"success"]);
}
Also change http verb from GET to POST
type: 'POST', //in ajax, it is good send bulk data in post not in get
In route
Route::post('/dbvalue','priceDetails#finalSubmit');
I am new to angular.So i dont know i am doing it in the right way.I am working in codeigniter along with angular.I need to get the id which i was passing though the angular $http service in my codeigniter controller.. I didn't get any console errors. Simply the data is not returning.. This is my angular controller
app.controller("newsController_id",function($scope,$http,$routeParams){
$http({ method:'POST',
url:'Controller1/get_list_id',
params:{id:$routeParams.id}
})
.then(function (response) {
$scope.blogs_id = response.data;
})
codeigniter controller
public function get_list_id() {
$id=$this->input->post('id');
//$id='6';
$data = $this->Blog_model->getAll_id($id);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
There are no errors in the codeigniter model and view pages..since i got my result perfectly when i hardcoded the id value as 6.But no output when i posting the id.help me solving this
you are doing wrong way to pass data angujarjs to codeigniter.
if you want to pass data in POST method pass object in $http service on data section like below
AngularJS Code
$http({
method:'post',
url:'/login',
dataType:"json",
data:{"vEmail":$scope.vEmail,"vPassword":$scope.vPassword},
}).then(function(suc){
console.log(suc);
},function(err){
console.log(err);
});
Codeigniter Code
$vEmail = $this->input->post('vEmail');
$vPassword = $this->input->post('vPassword');
If you want to pass data usgin GET you should be pass data in Param section like below
$http({
method:'get',
url:'/login',
dataType:"json",
params:{"vEmail":$scope.vEmail,"vPassword":$scope.vPassword},
}).then(function(suc){
console.log(suc);
},function(err){
console.log(err);
});
you can get that in codeigniter using get method like below
$this->input->get('vEmail');
You can not get the data by $_POST or $this->input->post , You should have something like this in constructor:
$postdata = file_get_contents("php://input");
$this->request = json_decode($postdata);
Now In controller, you can access the id:
$id = $this->request->id;
But it has a problem, you can't use Codeigniter form validation, because it works with $_POST superglobal. You can do something like this instead (in constructor):
$objectRequest = json_decode( file_get_contents("php://input") );
$this->request = xss_clean( json_decode(json_encode($objectRequest), true) );
$_POST = $this->request;
But this time you can access to id by the following example:
$id = $this->request['id'];
in order to get the post variables from angular you need use the following code
$postdata = file_get_contents("php://input");
$myData = json_decode($postdata);
instead of $id=$this->input->post('id');
so your $id = $myData->id;
Your final code would look like this:
public function get_list_id() {
$postdata = file_get_contents("php://input");
$myData = json_decode($postdata);
$id = $myData->id;
//$id='6';
$data = $this->Blog_model->getAll_id($id);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
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"