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....
Related
When doing an ajax-request for an autocomplete I get an undefined error:
View:
<input type="text" name="" id="search">
<ul>
<div id="result"></div>
</ul>
Javascript:
$("#search").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo base_url(); ?>index.php/admin/ajaxPro",
dataType: 'json',
type: 'POST',
data: req,
success: function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
select: function(event, ui) {
$("#result").append(
"<li>"+ ui.item.value + "</li>"
);
},
});
Controller:
public function ajaxPro()
{
$term = $this->input->get('term');
$this->db->like('business_name', $term);
$data = $this->db->get("user_table")->result();
header('Content-Type: application/json');
echo json_encode($data);
}
Database:
this is the table
There is no error in the console, Data is showing the network preview but it is not showing on the view page I do not know what the problem is Can you help
The Problem:
Return value: undefined
Change your Controller code to something like this:
public function ajaxPro()
{
$term = $this->input->get('term');
$this->db->like('business_name', $term);
$data = $this->db->get("user_table")->result();
$ajaxData = array();
foreach($data as $row) {
$ajaxData[] = array( // Set "label"+"value" for autocomplete for each result
'label' => $row['name'], // <- change this to your column name
'value' => $row['id'] // <- this should be the ID-Value
);
}
header('Content-Type: application/json');
echo json_encode(
'status' => 'success',
'data' => $ajaxData
);
}
And your ajax success callback:
success: function(r){
if(typeof r.status != "undefined" && r.status == "success"){
response(r.data); // lets autocomplete build response list
} else {
console.log(r); // error occured
}
},
(I changed your response variable from data to r to clearify this is not just the actual data, but a response in a variable that can contain much more than just the data from your sql-find result. It usually holds data exactly in the format you give in json_encode() )
Explanation:
In this line:
if(data.response =="true"){
You are asking for a value/key response that does not exist.
Tips on Debugging and Troubleshooting:
To see what your ajax-response look like, you can open the Dev-Tools in your Browser (ususally F12 and go to the Tab that shows your network requests. There you can find your ajax-request and see the headers you sent and the final response.
Furthermore if you add debugger; in this line, you can debug your javascript and see all variables available in the current scope:
success: function(r){
debugger; // this is a breakpoint equivalent and will halt your code execution when dev tools are open!
Trying to get products from productController with category_id
As seen blow. Codes are basic ajax request codes, there is no complicated things. But my result is allways null.
ROUTE
Route::post('urun-listele', 'ProductController#listele');
CONTROLLER
public function listele(Request $request)
{
$category_id = $request['category_id'];
$urunler = Product::where('category_id', $category_id)->get();
#var_dump($urunler);
return json_encode([
'urunler' => $urunler
], JSON_UNESCAPED_UNICODE);
}
AJAX
function urunListele(kategori_id) {
var kapsayici = $('#product-info');
$.ajax({
url: 'urun-listele',
type: "POST",
data: {category_id: kategori_id},
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
var urunler = data['urunler'];
for (var i = 0; i < urunler.length; i++) {
kapsayici.append('<div class="col-md-3 product-detail-item b-white br-10px"><p>' + urunler[i]['title'] + '</p></div>');
}
}
});
}
As i said, can't get any data.
var urunler = data['urunler'];
for (var i = 0; i < urunler.length; i++) {
kapsayici.append('<div class="col-md-3 product-detail-item b-white br-10px"><p>' + urunler[i]['title'] + '</p></div>');
}
console.log(urunler); allways return 0 object. Where is the problem? Thanks in advance.
EDIT:
i got Cannot read property 'length' of undefined when try return $urunler;
$category_id = $request['category_id']; can't get anything i think.
For example if i change $category_id = 5 it return [object Object],[object Object]
i have 2 object with $category_id = 5.
is problem here? $category_id = $request['category_id'];
EDIT2:
$category_id = $request->get('category_id');
$urunler = Product::whereCategoryId($category_id)->get();
return response()->json([
'urunler' => $urunler
]);
Controller changed like this and its working right now.
This could be due to a number of reasons first I am not sure if this is the correct syntax $request['category_id'];, but I may be wrong. I use most of the time `$request->category_id.
Second could you tell us wethere there is actual data here:
$category_id = $request['category_id'];
$urunler = Product::where('category_id', $category_id)->get();
Just dd($category_id) and dd($urunler) and tell us the results.
Furthermore you have a success method in your ajax request but not an error method could you add one and give us the results aswell?
Do something like this after your success function:
error: function(response) {
console.log(response) // this should hold a nice error message
}
Thus be sure that you actually post data in your ajax post, just console.log this kategori_id
At last laravel already returns a json by default so you do not actually need to do this, only if there is further reason for it.
You could replace this:
return json_encode([
'urunler' => $urunler
], JSON_UNESCAPED_UNICODE);
With this:
return $urunler;
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.
I am trying to save to a database in yii2 using ajax but I am getting errors. I just want to insert the value or rate which is "up" into the database and I don't want to use a form, just on-click of a button.
This is my controller
public function actionThumbs()
{
$thumbs = new Thumbs;
$thumbs->user = Yii::$app->user->identity->email;
$thumbs->topic_id = Yii::$app->getRequest()->getQueryParam('id');
$thumbs->rate = $_POST["rate"];
if ($thumbs->load(Yii::$app->request->post()) ) {
$thumbs->load($_POST);
$thumbs->save();
return $this->redirect(['blog', 'id' => Yii::$app->getRequest()->getQueryParam('id')]);
}
return $this->redirect(['blog','id' => Yii::$app->getRequest()->getQueryParam('id')]);
}
This is my this is my ajax file
$("#mys").click(function() {
var rate = "up";
$.ajax({
type: 'POST',
url: 'vot/frontend/web/index.php?r=site%2Fthumbs',
data: 'rate='+rate,
success: function (rate) {
alert("test");
},
error: function (exception) {
alert(exception);
}
});
});
the view
<div>
<?= Html::Button('ups', ['class' => 'btn btn-primary', 'name' => 'mys' ,'id'=>'mys']) ?>
</div>
I get this alert error
The page at localhost says":
"[object Object]"
By default Yii2 controller doesn't accept POST request without _csrf protection, so there are 2 ways here:
1 - disable csrf:
public function actionThumbs() {
$this->enableCsrfValidation = false;
//your code here
}
2 - Send post request via ajax with _csrf token:
In your layout/main.php file, put this: <?= Html::csrfMetaTags() ?>
Before your "ajax" code, call this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
//Your ajax code here
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"