Laravel 5.3 API not fetching data while using JavaScript on server - laravel

Routes: \routes\web.php
Route::get('api/get-market-list','MemberTradesController#getMarketList');
Route::get('api/get-market-list1','MemberTradesController#getMarketListtest');
Controller MemberTradesController
There're two function, getMarketListtest(just for testing on server) and getMarketList (this is for Request $request because, i have used it in dependent select box)
public function getMarketListtest(){
$markets = DB::table("markets")
->pluck("market","id");
return response() -> json($markets);
}
public function getMarketList(Request $request){
$markets = DB::table("markets")
->where("exchange_id", $request->exchange_id)
->pluck("market","id");
return response() -> json($markets);
}
Java scripts :
<script type="text/javascript">
$('#exchange').change(function(){
var exchangeID = $(this).val();
if(exchangeID){
$.ajax({
type:"GET",
url:"{{url('api/get-market-list')}}?exchange_id="+exchangeID,
success:function(res){
if(res){
$("#market").empty();
$("#market").append('<option>Select</option>');
$.each(res,function(key,value){
$("#market").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#market").empty();
}
}
});
}else{
$("#market").empty();
$("#symbol").empty();
}
});
</script>
View:
<title>Laravel 5 - Dynamic autocomplete search using select2 JS Ajax</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
{!! Form::open(['method'=>'POST', 'action'=> 'MemberTradesController#store']) !!}
<div class="form-group col-sm-5">
{!! Form::label('exchange_id', 'Exchanges:') !!}
{!! Form::select('exchange_id', [''=>'Choose Options'] + $exchanges , null, ['class'=>'form-control', 'id'=>'exchange'])!!}
</div>
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] , null, ['class'=>'form-control', 'id'=>'market'])!!}
</div>
{!! Form::close() !!}
Screenshot of TABLE:
Screenshot of TABLE:
For Function two Link for API result : api/get-market-list
Important information :
when i'm using this in my localhost, its give me result.
first api getMarketListtest() is working, because there is not having : (Request $request)
Error Log of laravel
[Changed code as per you function ]4

You can use $request->input('exchange_id'); instead of $request->exchange_id
Just try to replace this function.
public function getMarketList(\Illuminate\Http\Request $request){
$exchange_id = $request->input('exchange_id');
if(!empty($exchange_id)){
\Log::info('This is working.');
}
$markets = DB::table("markets")
->where('exchange_id', $exchange_id)
->pluck("market","id");
return response()->json($markets);
}
Please comment if any errors.

Related

laravel API, not fetching data from DB

This is on production side (on unbtu Digital Ocean server)
"laravel: 5.3"
"php": "5.5.9"
Route path : /route/web.php (not in middleware)
Route::get('api/getsymbol-request','MemberTradesController#getSymbolRequest');
Route::get('api/getsymbol','MemberTradesController#getSymbol');
Controller:
public function getSymbolRequest(Request $request){
$symbol = DB::table("symbols")
->where("market_id", $request->market_id)
->pluck("symbol","id");
return response() -> json($symbol);
}
public function getSymbol(){
$symbol = DB::table("symbols")
->pluck("symbol","id");
return response() -> json($symbol);
}
http://yourtradelog.com/api/getsymbol-request?market_id=1 //This is not working url I am getting issue WHY THIS IS NOT WORKING
http://yourtradelog.com/api/getsymbol //This is working url
Database tables
<script>
$(document).ready(function() {
$('#exchange').change(function(){
var exchangeID = $(this).val();
if(exchangeID){
$.ajax({
type:"GET",
url:"{{url('api/getsymbol-request/')}}?exchange_id="+exchangeID,
success:function(res){
if(res){
$("#market").empty();
$("#market").append('<option>Select</option>');
$.each(res,function(key,value){
$("#market").append('<option value="'+key+'">'+value+'</option>');
});
}else{
$("#market").empty();
}
}
});
}else{
$("#market").empty();
}
});
});
</script>
{!! Form::open(['method'=>'POST', 'action'=> 'MemberTradesController#store']) !!}
<div class="form-group col-sm-5">
{!! Form::label('market_id', 'Markets:') !!}
{!! Form::select('market_id', [''=>'Choose Options'] , null, ['class'=>'form-control', 'id'=>'market'])!!}
</div>
<div class="form-group col-sm-10">
{!! Form::label('symbol_id', 'Symbol:') !!}
{!! Form::select('symbol_id', [''=>'Choose Options'] , null, ['class'=>'symbol_id', 'id'=>'symbol','data-width'=>'60%', 'data-live-search'=>'true'] )!!}
</div>
<div class="form-group col-lg-4">
{!! Form::submit('Add trade', ['class'=>'btn btn-success btn-lg']) !!}
</div>
{!! Form::close() !!}
I prefer using route parameters like this (see more in the documentation here):
Routes:
Route::get('api/getsymbol-request/{id}','MemberTradesController#getSymbolRequest');
Route::get('api/getsymbol','MemberTradesController#getSymbol');
Controller:
public function getSymbolRequest(Request $request, $id){
$symbol = DB::table("symbols")
->where("market_id", $id)
->get()
->pluck("symbol","id");
return response() -> json($symbol);
}
public function getSymbol(){
$symbol = DB::table("symbols")
->pluck("symbol","id");
return response() -> json($symbol);
}
Please note that the URL has changed to this format:
http://yourtradelog.com/api/getsymbol-request/1
Try to this code:
public function getSymbolRequest(Request $request)
{
$marketID = (int)$request->get('market_id')
$symbol = DB::table('symbols')
->where('market_id', $marketID)
->get(['symbol','id']);
return response()->json($symbol);
}
public function getSymbol()
{
$symbol = DB::table('symbols')
->get(['symbol','id']);
return response()->json($symbol);
}

Passing data from Vue.js request to Laravel 5.3 form

I have two tables: Countries and Cities. Idea is to show the second dropdown when User has selected country and fill it with cities that correspond to selected country.
Unfortunately I cannot figure out how to pass retrieved values to form.
Values retrieved are below the country with id 21 is Norway :)
Selected { "country": "21", "CountrySelected": true, "cities": { "6": "Oslo", "11": "Lillehammer" } }
// My app.js
const app = new Vue({
el: '#events',
data: {
country:'',
CountrySelected: false,
cities:[],
},
methods: {
WhenCountryHasBeenSelected: function(event) {
this.getCities();
this.CountrySelected= true;
},
getCities: function(){
this.$http.get('api/cities/'+this.country).then(function (response) {
this.cities = response.data;
});
}
},
})
//My api.php routes
Route::get('/cities/{country_id}', function (Request $request, $country_id) {
$cities=App\City::where('country_id', $country_id)->get()->pluck('name','id');
return $cities;
});
//My blade file
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div id="events">
<div class="panel panel-default">
<div class="panel-heading">Select cities by country</div>
<div class="panel-body">
{!! Form::open() !!}
{!! Form::select('country', $countries, null, ['v-model'=>'country', '#change'=>'WhenCountryHasBeenSelected' ,'class'=>'form-control']) !!}
<div v-show="CountrySelected">
{!! Form::select('city',$cities, null, ['class'=>'form-control']) !!}
{!! Form::close() !!}
Selected #{{ $data | json }}
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Ended up to use Laravel collection map feature. Mu route looks now like this
Route::get('/cities/{country_id}', function (Request $request, $country_id) {
$collection=App\City::where('country_id', $country_id)->get();
$cities=$collection->map(function($city){
return ['id' => $city->id, 'name' => $city->name];
})->toArray();
Long live Laracast forums and bashy :)

How to fix NotFoundHttpException laravel?

Hi all I am a new of laravel 5.1,I just start learning laravel. I have problame in laravel I can not find the way to correct it I try to search but I still can not.I want to update form, but when I click button update its show error
NotFoundHttpException in Handler.php line 46: No query results for model [App\Course].
ModelNotFoundException in Builder.php line 129: No query results for model [App\Course].
And here is my code:
CourseController.php
public function update(Request $request, $id)
{
$input = $request->all();
$data = Course::findOrFail($id);
$data->update($input);
return redirect('course');
}
and my model Course.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $table = "course";
protected $primaryKey = "course_id";
protected $fillable=[
'course_title',
'course_code',
'course_credite'
];
}
And here is my view edite.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<div class="container">
{!! Form::open(array('route'=>['course.update','$course->course_id'],'class'=>'jack','method'=>'PUT')) !!}
{!! Form::label('Course_title','Course Title',array('class'=>'aswe')) !!}
{!! Form::text('course_title', $value=$course->course_title, $att = array('class'=>'blu','id'=>'single','required')) !!}
{!! Form::label('Course_code','Code_title',array('class'=>'no')) !!}
{!! Form::text('course_code',$value=$course->course_code,$att = array('class','blue','required')) !!}
{!! Form::label('Course_creadit','creadit_title',array('class'=>'no')) !!}
{!! Form::text('course_credite',$value=$course->course_credite,$att = array('class','blue','required')) !!}
{!! Form::submit('submit',$att=array('class'=>'has')) !!}
{!! Form::close() !!}
</div>
</body>
</html>
And my route
Route::resource('course','CourseController');
It looks like the problem is how you're opening the form:
{!! Form::open(array('route'=>['course.update','$course->course_id'],'class'=>'jack','method'=>'PUT')) !!}
There are single-quotes around the parameter to the route, so it'd be looking to pass in the literal string "$course->course_id". To fix this, you can simply remove those quotes:
{!! Form::open(['route' => ['course.update', $course->course_id], 'class' => 'jack', 'method' => 'PUT']) !!}
Dirty way:
you may replace findOrFail() with find only and just handle it programmatically with if(!is_null($user))
Clean way:
Create a new exception file to catch your exception or just have it here within your code like so:
// Will return a ModelNotFoundException if no Course with that id
try
{
$data = Course::findOrFail($id);
$data->update($input);
return redirect('course');
}
// catch(Exception $e) catch any exception
catch(ModelNotFoundException $e)
{
dd(get_class_methods($e)); // lists all available methods for exception object
dd($e);
// you might do here
session()->flash('message', ['danger', 'Oops no such course found !']);
return redirect('course'); // please mind to change it later to use names route or perhabs action()
}
And in your course index view right the following HTML to render the error
#include('errors.alert',['type'=> Session::get('message.0'),'message' => Session::get('message.1') ])
and for sure create this partial view errors/alert.blade.php:
<div class="alert alert-{{ $type }} alert-page alert-dark">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
{!! $message !!}
</div>

Laravel 5.1 datatables reorder row

I need help.
I'm using yajra/laravel-datatables for include datatables into my project.
All is working.
Now I want to use the row reorder extension: https://datatables.net/extensions/rowreorder/
But when I make a drag and drop with a row seems to work, but is not working.
I think is possible that is reloaded because I use ajax url to load data, unmaking the reorder I do. Is possible?
Well, these are my codes:
Controller:
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$med = new Medicinas;
return view('admin.medicinas.index', ['med' => $med->get()]);
}
/**
* Process datatables ajax request.
*
* #return \Illuminate\Http\JsonResponse
*/
public function anyData()
{
return Datatables::of(User::select('*'))->make(true);
}
Routes:
Route::get('administrator/medicinas', [
'as' => 'admin.medicinas',
'uses' => 'MedicinasController#index'
]);
Route::controller('administrator/medicinas', 'MedicinasController', [
'anyData' => 'datatables.data',
'index' => 'administrator/medicinas',
]);
View:
#extends('app')
#section('content')
<div class="col-xs-12 col-sm-10">
#foreach($med as $medicina)
<div class="col-xs-12 col-sm-4">
{{ $medicina->nombre_comercial }}
</div>
#endforeach
</div>
<table id="users-table" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</tfoot>
</table>
<input type="text" name="" value="" placeholder="">
#endsection
#section('scripts')
<script type="text/javascript">
$(function() {
var table_id = '#' + 'users-table';
window.table = $(table_id).DataTable({
rowReorder: true,
processing: true,
serverSide: true,
ajax: '{!! route('datatables.data') !!}',
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
window.table_h = $(table_id + ' thead th');
window.table_f = $(table_id + ' tfoot th');
});
</script>
#endsection
This is my layout:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Medicinas de amoooor</title>
{!! Html::style('assets/css/bootstrap.css') !!}
{!! Html::style('assets/css/bootstrap-switch.css') !!}
{!! Html::style('assets/css/bootstrap-tagsinput.css') !!}
{!! Html::style('assets/css/rowReorder.bootstrap.min.css') !!}
{!! Html::style('assets/css/style.css') !!}
<!-- Datatables -->
<link rel="stylesheet" href="//cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css">
<!-- Fonts -->
<link href='https://fonts.googleapis.com/css?family=Arimo:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
{!! Html::style('assets/css/font-awesome.min.css') !!}
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
#include('header')
<!-- Contents -->
#if (Auth::guest())
<div class="row">
<div class="container">
#yield('content')
</div>
</div>
#else
<div class="row">
<div class="container">
#include('admin.sidebar')
#yield('content')
</div>
</div>
#endif
#if (Session::has('errors'))
<div class="container">
<div class="alert alert-danger" role="alert">
<ul>
<strong>Oops! Something went wrong : </strong>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
<!-- Footer -->
#include('footer')
<!-- Modal -->
#yield('modal')
<!-- Scripts -->
{!! Html::script('assets/js/jquery-2.1.4.min.js') !!}
{!! Html::script('assets/js/jquery.dataTables.min.js') !!}
{!! Html::script('assets/js/dataTables.jqueryui.min.js') !!}
{!! Html::script('assets/js/dataTables.bootstrap.min.js') !!}
{!! Html::script('assets/js/bootstrap.min.js') !!}
{!! Html::script('assets/js/bootstrap-switch.js') !!}
{!! Html::script('assets/js/bootstrap-tagsinput.js') !!}
{!! Html::script('assets/js/dataTables.rowReorder.min.js') !!}
<!-- DataTables -->
<script src="//cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
#yield('scripts')
<script type="text/javascript">
$(function() {
if (typeof table_h !== 'undefined') {
// Setup - add a text input to each header cell
table_h.each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
}
if (typeof table_f !== 'undefined') {
// Setup - add a text input to each header cell
table_f.each( function () {
var title = $(this).text();
$(this).html( '<input type="text" placeholder="Search '+title+'" />' );
} );
}
// Apply the search
table.columns().every( function () {
var that = this;
if (typeof table_h !== 'undefined') {
$( 'input', this.header() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
});
}
if (typeof table_f !== 'undefined') {
$( 'input', this.footer() ).on( 'keyup change', function () {
if ( that.search() !== this.value ) {
that
.search( this.value )
.draw();
}
});
}
});
});
</script>
What you need to do is inject the sequence into the data.
<script type="text/javascript">
$(function() {
var table_id = '#' + 'users-table';
window.table = $(table_id).DataTable({
rowReorder: true,
processing: true,
serverSide: true,
ajax: {
url:'{!! route('datatables.data') !!}',
dataSrc: function ( d ) {
for ( var i=0, ien=d.data.length ; i<ien ; i++ ) {
d.data[i].seq = i;
}
return d.data;
}
},
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'created_at', name: 'created_at' },
{ data: 'updated_at', name: 'updated_at' }
]
});
window.table_h = $(table_id + ' thead th');
window.table_f = $(table_id + ' tfoot th');
});
</script>

laravel 5 and Ajax get data from database:

I have simple form:
{{ Form::open(array('id' => 'frm')) }}
<div class="form-group">
{!! Form::label('id','id:'); !!}
{!! Form::text('id',null,['class' => 'form-control']); !!}
</div>
<div class="form-group">
{!! Form::submit('Update',['class' => 'btn btn-primary form-control']); !!}
{!! Form::close() !!}
I want to post the values from the form input fields to the controller then in the controller mthod run a query on the database for the id value from the form. Finally, using ajax, show the results of the DB query and if there are no results show a message alerting the user.
I have tried this:
<script>
$("document").ready(function(){
$("#frm").submit(function(e){
e.preventDefault();
var customer = $("input[name=postal]").val();
$.ajax({
type: "POST",
url : "http://laravel.test/ajax",
data : dataString,
dataType : "json",
success : function(data){
}
}, "json");
});
});//end of document ready function
</script>
I have tried a couple of ways to get the post data in the controller but have had no success.
---Problem 1:
There is problem when I try to use this in route:
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id');
return $user; // Eloquent will automatically cast the data to json
});
I get sintax error,on second line for (;)
Also, I try to get data in controller and than print them:
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
ROUTES.PHP
Route::post('/',
['as' => 'first_form', 'uses' => 'TestController#find']);
Route::get('/', 'TestController#index');
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id');
return $user; // Eloquent will automatically cast the data to json
});
Function:
public function ajax()
{
//
// Getting all post data
if(Request::ajax()) {
$data = Input::all();
print_r($data);die;
}
}
I found a couple more ways to send data from view to controller,but even woant show posted data. I check with fire-bug,there is posted value in post request
It appears you're passing your ajax method a variable that doesn't exist. Try passing it the form data directly and see if that yields any results, you can do this with the serialize method:
$("#frm").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "http://laravel.test/ajax",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
The ajax call has console.log in it now so it will output anything returned to it in the console.
routes.php (an example)
Route::post('ajax', function() { // callback instead of controller method
$user = App\User::find(\Input::get('id'));
return $user; // Eloquent will automatically cast the data to json
});
Please bear in mind I am just putting the code as an example as you didn't put your controller code in the question.
EDIT
I'm going to make a really simple example that works for you. I have made a fresh install of laravel and coded this and it's working fine for me. Please follow along carefully.
app/Http/routes.php
<?php
// route for our form
Route::get('/', function() {
return view('form');
});
// route for our ajax post request
Route::post('ajax', function() {
// grab the id
$id = \Input::get('id');
// return it back to the user in json response
return response()->json([
'id' => 'The id is: ' . $id
]);
});
resources/views/form.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax Example</title>
</head>
<body>
{!! Form::open(['url' => 'ajax', 'id' => 'myform']) !!}
<div class="form-group">
{!! Form::label('id','id:') !!}
{!! Form::text('id', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::submit('Update',['class' => 'btn btn-primary form-control']); !!}
</div>
{!! Form::close() !!}
<div id="response"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$("document").ready(function(){
// variable with references to form and a div where we'll display the response
$form = $('#myform');
$response = $('#response');
$form.submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url : $form.attr('action'), // get the form action
data : $form.serialize(), // get the form data serialized
dataType : "json",
success : function(data){
$response.html(data['id']); // on success spit out the data into response div
}
}).fail(function(data){
// on an error show us a warning and write errors to console
var errors = data.responseJSON;
alert('an error occured, check the console (f12)');
console.log(errors);
});
});
});
</script>
</body>
</html>

Resources