Laravel ajax post data - javascript

I have an eCommerce shop where I have to filter products by its categories.
I have to post an array of all filters in the controller, but I am getting this error
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file": "C:\\xampp\\htdocs\\web_front\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\RouteCollection.php",
"line": 179
Here is my code:
<script>
$(document).ready(function () {
var categories = [];
$('input[name="cat[]"]').on('change', function (e) {
e.preventDefault();
categories = []; // reset
$('input[name="cat[]"]:checked').each(function()
{
categories.push($(this).val());
});
$.ajax({
type:"GET",
url:'advanced_filter/' + categories,
success:function(data){
console.log(data);
},
error: function(xhr,errmsg,err)
{
console.log(xhr.responseText);
}
});
});
});
</script>
web.php
Route::get('advanced_filter/{filters}', 'HomepageController#advanced_filter')->name('advanced_filter');
public function advanced_filter($filters)
{
dd($filters);
}
I am trying to show all the filters, so I can make a query to get all the products based on filters. I have created the script where I get all filters and want to post it in the controller. Please, can you see this? Thank you

first of all :
"exception":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
above exeption occur when route is not found . NotFoundHttpException has status 404
in your code you are passing array of categories in route params , which is syntactically wrong , so thats why failed to find route .
Route::get('advanced_filter', 'HomepageController#advanced_filter')->name('advanced_filter');
from frontend side : pass categories as query parameters
url will be :
/advanced_filter?queryParameter= ids of selected categories
/advanced_filter?categories=1,3,7
your ajax function will be :
$.ajax({
type:"GET",
url:`/advanced_filter?categories=${categories.join(',')}`,
success:function(data){
console.log(data);
},
error: function(xhr,errmsg,err){
console.log(xhr.responseText);
}
});
in your controller :
use Illuminate\Http\Request;
public function advanced_filter(Request $request)
{
$filter_categories=[];
if($request->has('categories')){
$filter_categories=$request->query('categories');
}
/* you can pass extra query parameter like sortBy,sortOrder,limit in url
`/advanced_filter?categories=1,3,7&limit=24&sortBy=name&sortOrder=desc`
*/
$sortBy=$request->has('sortBy')?$request->query('sortBy'):'id';
$sortOrder=$request->has('sortOrder')?$request->query('sortOrder'):'desc';
$limit = $request->has('limit')?$request->has('limit'):12;
/* assuming you have models with relations */
$query = Products::query();
$query->with('categories');
if(count($filter_categories)>0){
$query->whereHas('categories', function ($q) use ($filter_categories) {
$q->whereIn('categories.id',$filter_categories);
});
}
$query->orderBy($sortBy,$sortOrder);
$products = $query->paginate($limit);
return response()->json($products);
}

Related

Laravel 500 Internal Server Error Ajax

I am developing a website using Laravel and Ajax. I have a problem when I try to return all messages (Messages model) that belong to specific user (User model) using hasMany method.
web.php
Route::get('/test', 'UserController#testFunction');
Route::post('/test', 'UserController#testFunction');
UserController.php
public function testFunction(Request $request) {
if ($request->isMethod('post')) {
$messages = User::find(1)->messages;
return $messages;
} else {
return 'get method';
}
}
User model
class User extends Authenticatable {
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function messages() {
$this->hasMany('App\Message', 'from');
}
}
Message model
class Message extends Model {
protected $fillable = [
'from', 'to', 'content'];
}
Then I have two buttons (just for testing - POST and GET). They are handled by this JavaScript code
window.onload = function() {
// AJAX Setup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Post Method
$('#postMethod').click( function() {
$.post('test', function (data) {
console.log(data);
});
});
// Get Method
$('#getMethod').click(function() {
$.get('test', function(data) {
console.log(data);
});
});
}
Tables in the databse have a structure as shown below:
users table
messages table
When I click on POST button (handled by above javascript code), I receive this error in console: error in console
If I change $messages = User::find(1)->messages; to $messages = User::find(1)->name;, for example, I get the name of the user with ID 1 returned to the console normally.
I assume that something is wrong with messages() function in UserController.php. Maybe 'from' as foreign key? This is just my guess, maybe the error is somewhere else, please take a look yourself.
Here is your fix, you need to call messages like this messages() that will return relationship instance.
public function testFunction(Request $request) {
if ($request->isMethod('post')) {
$messages = User::find(1)->messages();
return $messages;
} else {
return 'get method';
}
}
Hope this helps.
test with /.
Try this
// Post Method
$('#postMethod').click( function() {
$.post('/test', function (data) {
console.log(data);
});
});
// Get Method
$('#getMethod').click(function() {
$.get('/test', function(data) {
console.log(data);
});
});

jquery is this a valid http request

I have this http request
GET /deals/couchbaseDocument/_search
{
"query" : {
"match" : {
"amenities" : "Maids "
}
}
}
when i put it in curl, it gives me results, i want to build a web app to call that request.
what i did is removing the newlines and put the whole text in .getjson()
as this:
var query = $("#query").val();
query = query.replace(/(\r\n|\n|\r)/gm,"");
$.getJSON(query, function (results) {
alert("success");
alert(results);
})
.success(function () { alert(" second success"); })
.error(function () {
alert("error");
alert(query);
});
i kept getting the error alert, i wonder if what i did is actually what should it be done to send that request
I read this
I found that .getJson could be like this:
$.getJSON('httpURL',
{ parameter1: "parameter value", parameter2: "parameter value" })
i wonder if i should pass my json request as a parameter
in case of the whole picture** i am working on sense elasticsearch plugin
According to the documentation of jQuery's getJson, you can pass a javascript object (jQuery.getJSON() | jQuery API Documentation) so you can do something like this
var queryData = {
"query" : {
"match" : {
"amenities" : "Maids "
}
}
};
$.getJSON('httpURL', queryData)

AngularJS code is giving back error?

$scope.logout = function () {
//var auth_token = $cookieStore.get('auth_token');
Auth.delete({
'auth_token': $cookieStore.get('auth_token')
}, function(data){
$scope.isLoggedIn = false;
$cookieStore.remove('auth_token');
});
When this called it given me an error:
Error: [$resource:badcfg] http://errors.angularjs.org/1.2.27/$resource/badcfg?p0=object&p1=array
z/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:6:450
t/</f[d]/q<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular-resource.min.js:8:1
De/e/l.promise.then/J#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:101:87
De/e/l.promise.then/J#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:101:87
De/f/<.then/<#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:102:259
Yd/this.$get</h.prototype.$eval#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:113:28
Yd/this.$get</h.prototype.$digest#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:110:109
Yd/this.$get</h.prototype.$apply#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:113:360
m#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:72:452
w#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:77:463
ye/</B.onreadystatechange#http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js:79:24
http://ajax.googleapis.com/ajax/libs/angularjs/1.2.27/angular.min.js
Line 92
Its a common problem. The delete method of resource model is expecting a json response which must be an object but your server is returning the json data in array format. So you have two options either change your server code to respond the json object data or change your resource model something like:
var Auth = $resource('/your-server-url', {}, {
delete: {
isArray: false
}
});
Hope this helps!
Thanks,
SA

Ajax get caused in 500 Internal Server Error

I have two Ajax Get Request:
$.get('/tutorials/rate', {id: {{$tutorial->id}}}, function (data) {
$ratingCount = data;
});
$.get('/tutorials/rateAverage', {id: {{$tutorial->id}}}, function (data) {
$averageRating = data;
});
in my Controller:
public function get_rate() {
$postId = Input::get('id');
$ratings = rating::where('tutorial_id', '=', $postId)->get();
return count($ratings);
}
public function get_rateAverage(){
$postId = Input::get('id');
}
in my routes:
Route::controller('tutorials', 'TutorialController');
First Request is workin like a charm, second one gives me a 500 Error...
On your second get request, try
$.get('/tutorials/rate-average', {id: {{$tutorial->id}}}, function (data) {
$averageRating = data;
});
Your function names should be getRate() and getRateAverage()
This is what Laravel expects as far as naming conventions. Please see http://laravel.com/docs/controllers#resource-controllers

jquery.couchdb.js Ajax success/error not being called

I'm using jquery.couchdb.js to query my CouchDB database. The view I want to query has both map and reduce functions within. When sending the basic query as shown below:
$(document).ready(function() {
view_name = db_name+'/jobs_by_mod_stat'
options = {'group': 'true' , 'reduce': 'true' };
mod_stat = {};
$db.view(view_name , {
success: function(data) {
console.log(data)
for (i in data.rows) {
console.log(data.rows[i].value);
}
},
error: function(e) {
alert('Error loading from database: ' + e);
}
});
});
I see a sensible log for the data, indicating the query has been successful. However, changing the line:
$db.view(view_name , {
To
$db.view(view_name , options, {
I don't get a success outcome from the Ajax query, but an error message is not shown either. Firebug shows the query being sent, and the JSON data returned looks sensible:
{"rows":[
{"key":["template","completed"],"value":2},
{"key":["template","running"],"value":2},
{"key":["template","waiting"],"value":6}
]}
But the success function is not entered. Any ideas why I'm seeing this behaviour, I did wonder if it's a bug in jquery.couch.js (I have couchdb 1.1.0).
Cheers.
I've had a bit of trouble myself with the list function, until I went and looked through the source code of jquery.couch.js (the online documentation I found at http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference/ seems to be outdated).
Basically, the parameters for view and list are different, the list having an extra parameter for the options, instead of having everything under the same parameter as with views.
View:
$.couch.db('yourdb').view('couchapp/' + viewName, {
keys: ['keys here'],
success: function (data) {
}
});
List:
$.couch.db('yourdb').list('couchapp/' + listName, viewName, {
keys: ['keys here']
}, {
success: function (data) {
}
});

Categories