I am trying to send json response on my ajax into my view on my laraveL.
But i can't get any good codes for it, exam
public function viewMasakanAjax(Request $request)
{
if($request->ajax())
{
$alberMasakan = Masakan::where('alber_nama_masakan','LIKE','%'.$request->search."%")->get();
return response()->json($alberMasakan)->view('kasir/ajax-menu');
}
}
When i am try that code, it doesn't work.
also this is my view
#foreach($alberMasakan as $alberData)
<div class="col-xl-3 col-lg-6 col-md-6 col-sm-12 col-12">
<div class="card card-figure">
<figure class="figure">
<div class="figure-img">
<figure class="figure">
<img class="img-fluid" src="{{ asset('kasir/images/seafood.jpg') }}" alt="Card image cap">
<figcaption class="figure-caption">
<h6 class="figure-title"> Simple figure </h6>
<p class="text-muted mb-0"> Give some text description </p>
</figcaption>
</figure>
</figure>
</div>
</div>
#endforeach
here my ajax code
<script>
$('#cariData').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{route('admin.ajax')}}',
data:{'search':$value},
success:function(data){
$('.ajax').html(data);
if ($value == '') {
$('.isi').remove();
}
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
my route on web.php
Route::get('/cari', 'KasirRestoran\DetailOrderController#viewMasakanAjax')->name('admin.ajax');
You can return either $response->json() or view(), but not both together.
Your javascript is expecting to see HTML content, but you're feeding it JSON data. To pass data to a view, use something like this:
public function viewMasakanAjax(Request $request)
{
if ($request->ajax()) {
$alberMasakan = Masakan::where('alber_nama_masakan','LIKE','%'.$request->search."%")->get();
// Pass $alberMasakan as data along to the view
// Same as view('kasir/ajax-menu')->with($alberMasakan)
return view('kasir/ajax-menu', $alberMasakan);
}
}
You should try
public function viewMasakanAjax(Request $request)
{
if($request->ajax())
{
$alberMasakan = Masakan::where('alber_nama_masakan','LIKE','%'.$request->search."%")->get();
return response()->json($alberMasakan);
}
}
Related
Student Controller
#GetMapping("/numberStudent")
#ResponseBody
public String getStudentNumber(){
String repot = null;
repot = studentRepository.StudentsNBR();
return repot;
}
Studeent repository
#Query("select count(e) from Student ")
public String StudentsNBR();
so basicly i want to display the number of the student in a card using bootstrap
<div class="col-sm">
<div class="card bg-light" style="width: 18rem;">
<img class="card-img-top" src="https://cdn.discordapp.com/attachments/557595531526799390/1033961333584052224/spring.gif"
style="height: 180px;">
<div class="card-body">
<div class="p-1 mb-2 bg-dark text-white">
<h5 class="card-title" align="center">Spring BOOT</h5></div>
<script>
jQuery(function($) {$.number( 1234.5678, 2 );
$.ajax({
type : "GET",
url : "/numberStudent"});
</script>
</div>
</div>
</div>
Simply need to add model interface and create a variable that hold the return,
model.AddAttribute("var_name",var_name);
and go to the view and call it [th:text=${"variable-name"}]
I have a homepage where there is a menu with some categories and below there are the latest posts:
<ul class="Categories__Menu">
#foreach($categories->take(6) as $category)
<li class="ative">
{{$category->name}}
</li>
#endforeach
</ul>
<div class="row" id="posts">
#foreach($posts as $post)
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<div class="card">
<img class="card-img-top" src="{{$post->image}}" alt="Card image cap">
<h5 class="card-title">{{$post->name}}</h5>
<div class="card-footer d-flex justify-content-between align-items-center">
More
</div>
</div>
</div>
#endforeach
</div>
I want that when each category is clicked to show only the posts of that category in the homepage, but in the same homepage, not in a specific category page.
So I have this Ajax:
$(function() {
$("a[name='category']").on('click', function(){
var category_id = $(this).attr("id");
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, postObj){
$('#posts').append("<p>"+postObj.name+"</p>");
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});
});
});
And its working fine, but instead of show just this:
$('#posts').append("<p>"+postObj.name+"</p>");
I want to show the posts with the real html above like:
<div class="col-12 col-sm-6 col-lg-4 col-xl-3 mb-4">
<div class="card">
<img class="card-img-top" src="{{$post->image}}" alt="Card image cap">
<h5 class="card-title">{{$post->name}}</h5>
<div class="card-footer d-flex justify-content-between align-items-center">
More
</div>
</div>
</div>
So Im using like this in ajax:
$("a[name='category']").on('click', function(){
var category_id = $(this).attr("id");
alert(category_id);
$.ajax({
url: '{{ route('category.posts',null) }}/' + category_id,
type: 'GET',
success:function(result){
$('#posts').empty();
$.each(result,function(index, postObj){
//$('#posts').append("<p>"+postObj.name+"</p>");
$('#posts').append("<div class=\"col-12 col-sm-6 col-lg-4 col-xl-3 mb-4\">\n" +
" <div class=\"card box-shaddow\">\n" +
" <img class=\"card-img-top\" src=\"{{postObj.image}}\" alt=\"Card image cap\">\n" +
" <h5 class=\"card-title h6 font-weight-bold text-heading-blue\">{{postObj.name}}</h5>\n" +
" <div class=\"card-footer d-flex justify-content-between align-items-center\">\n" +
"\n" +
" More\n" +
" </div>\n" +
" </div>\n" +
" </div>");
});
console.log(result);
},
error: function(error) {
console.log(error.status)
}
});
});
But it appears an error:
Use of undefined constant postObj - assumed 'postObj'
Do you know why?
PostController:
public function WhereHasCategory(Request $request)
{
$posts = Post::whereHas('categories', function ($categories) use (&$request) {
$categories->where('id',$request->id);
})->get();
return response()->json($posts);
}
Route to the ajax part:
Route::get('posts/where/category/{id}','\PostController#WhereHasCategory')->name('category.posts');
Method to return the homepage view:
public function index(){
return view('home')
->with('categories', Category::orderBy('created_at', 'desc')->get())
->with('posts', Post::orderBy('created_at','desc')->take(8)->get());
}
Make sure you refer to variable in Blade template with $postObj, not postObj. I can see you use it without $, like postObj.image in your tag.
i dont know how to append external json data to div. i know append with table .but, i am confused with div.please help me to solve this doubt.
because,it need to append data with selected category div.
div1 category [books]
<div class="col-xs-12 col-sm-5 col-md-3 col-lg-2 card">
<!--Card content-->
<div class="card-body">
<!--Title-->
<h4 class="card-title">Card title</h4>
<!--Text-->
<img class="img-fluid z-depth-3 rounded-circle" src="https:/goo.gl/4cPCdn"
alt="Card image cap">
<h4 class="card-title">Category</h4>
<!--Card content-->
Button
</div>
</div>
div 2 category [games]
<div class="col-xs-12 col-sm-5 col-md-3 col-lg-2 card">
<!--Card content-->
<div class="card-body">
<!--Title-->
<h4 class="card-title">Card title</h4>
<!--Text-->
<img class="img-fluid z-depth-3 rounded-circle" src="https:/goo.gl/4cPCdn"
alt="Card image cap">
<h4 class="card-title">Category</h4>
<!--Card content-->
Button
</div>
</div>
Json
{
"category": {
"books": [
{"title":"Sentra", "url":"https:/goo.gl/4cPCdn","button":"https:google.in"},
{"title":"Maxima", "url":"https:/goo.gl/4cPCdn"},"button":"https:google.in"}
],
"games": [
{"title":"Taurus", "url":https:/goo.gl/4cPCdn},"button":"https:/google.in"}
{"title":"Escort", "url":https:/goo.gl/4cPCdn},"button":"https:/google.in"}
]
}
}
Javascript & jquery
<script>
$.ajax({
url: 'json-data.json',
type: "get",
dataType: "json",
success: function (data) {
drawTable(data);
}
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData) {
**This part i dont know please teach me**
}
</script>
Fiddle
Fiddle codes click to edit
This isn't perfect but it should give you some help in understanding how to append to a div via jQuery. Your data was messed up, so I fixed it and made it a valid object. You may want to use things like JSLint to check your data before testing your pages - https://jsonlint.com/
var data = {
"category": {
"books": [
{"title":"Sentra", "url":"https:/goo.gl/4cPCdn", "button":"https:google.in"},
{"title":"Maxima", "url":"https:/goo.gl/4cPCdn", "button":"https:google.in"}
],
"games": [
{"title":"Taurus", "url":"https:/goo.gl/4cPCdn","button":"https:/google.in"},
{"title":"Escort", "url":"https:/goo.gl/4cPCdn","button":"https:/google.in"}
]
}
}
/* not needed for test, we've already included our data above
$.ajax({
url: 'json-data.json',
type: "get",
dataType: "json",
success: function (data) {
drawTable(data);
}
});
*/
data = data.category;
drawTable(data)
function drawTable(theData) {
for (category in theData) {
console.log('category is '+category)
var categoryEntries = theData[category]
for (var i = 0; i < categoryEntries.length; i++) {
var rowData = categoryEntries[i];
drawRow(category,rowData)
}
}
}
function drawRow(category,rowData) {
// console.log(JSON.stringify(rowData))
var title = rowData.title;
var url = rowData.url;
var button = rowData.button
var newDiv = '<div class="card">'+
'<div class="card-body">'+
'<h4 class="card-title">'+title+'</h4>'+
'<img class="img-fluid z-depth-3 rounded-circle" src="'+url+'" alt="Card image cap">'+
'<h4 class="card-title">'+category+'</h4>'+
'Button'+
'</div>'+
'</div>'
$('#'+category).append(newDiv);
}
#books,#games {
display:block;
width: 100%;
clear:both;
}
.card {
float:left;
width: 30vw;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div id="books">
</div>
<div id="games">
</div>
I'm trying to send a PHP variable to JavaScript using AJAX and implementing to HTML, but the result doesn't show anything.
My HTML code:
<div class="contain" id="konten_data"
style="margin-top: 20px;"></div>
My JavaScript code:
function tampilDepan(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=tdepan&id='+id,
success:function(html){
$('#konten_data').html(html);
}
});
}
My PHP code (userAction.php):
($_POST['action_type'] == 'tdepan'){
$link = mysqli_connect("localhost", "root", "", "universitas");
$datas = mysqli_query($link, "SELECT * FROM mahasiswa where user='john' ");
if(!empty($datas)){
while ($datak = mysqli_fetch_assoc($datas)){
echo '<div class="row" style="margin-left: -90px;">
<div class="col-xs-6 col-sm-6 col-md-4">
<img class="img-thumbnail img-responsive"
src="images/test/'.$datak['gmb_batik'].'" alt=""></div>
<div class="col-xs-12 col-md-8">
<div class="content-box-large">
<p>'.$datak['desc_batik'].'</p>
</div>
</div>
</div>
<div class="row" style="margin-left: -90px; margin-top: 10px;">
<div class="col-xs-12 col-sm-6 col-md-4 col-md-offset-3">
<div class="content-box-large">
<h1 >asal <strong>'.$datak['asal_batik'].'</strong></h1>
</div>
</div>
<div class="col-xs-16 col-sm-6 col-md-2 col-md-offset-1">
<img class="img-thumbnail img-responsive"
src="login/admin/files/qrcode/'.$datak['qr_batik'].'"
alt="">
</div>
</div>
<div class="row" style="margin-left: -90px; margin-top: 10px;">
<div class="col-xs-12 col-sm-6 col-md-9 col-md-offset-4">
<div class="content-box-large">
<p>'.$datak['pola_batik'].' </p>
</div>
</div>
</div>';
}
}else {``
echo '<tr><td colspan="5">No user(s) found......</td></tr>';
}`
}
I don't know what is wrong, I hope somebody can help me.
Try to change the javascript code to
function tampilDepan(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: {action_type: "tdepan", id: id},
success:function(html){
$('#konten_data').html(html);
}
});
}
As you can see, data is passed as an object instead of a string.
Also, be aware that if no user was found, you are putting a <tr> inside a <div>.
try to change in your ajax call.
function tampilDepan(id){
var postData ={"action_type":tdepan,"id":id};
$.ajax({
type: 'POST',
url: 'userAction.php',
data: postData ,
success:function(html){
$('#konten_data').html(html);
}
});
}
try to use the format below in calling ajax:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{ "action_type":"' + tdepan + '", "id":"' + id + '"}',
url: 'userAction.php',
success: function (data) {
conosle.log(data);
},
error: function (error) {
console.log(error);
}
});
You are trying to get your data using konten_data probably by using jQuery selector $('#konten_data').val();
, but I don't see it in the PHP code as where you are pushing the data to render onto the DOM. Try setting the value of konten_data by adding an element before the success callback or on DOM render and you should be good from there.
main.html
<div class="row" ng-repeat="post in myBlogPosts.slice().reverse()">
<br>
<div class="col-md-9 text-center">
<a href="#/blog-post/{{post._id}}">
<div class="thumbnail mTextBg customShadow">
<br>
<img class="img-responsive" src="http://placekitten.com/700/400" alt="">
<div class="caption">
<h3>{{post.imdbId}}</h3>
<p>{{post.blogContent}}</p>
</div>
</div>
</a>
</div>
<div class="col-md-3">
// I WANT THIS PART !!
<div class="well sideBars customShadow">
<img class="img-responsive" ng-src="{{film.Poster}}" title="{{film.Title}}">
<h4 class="text-center">{{film.Title}}</h4>
<p class="text-center" style="margin-bottom: 2px;"><b>Year:</b> {{film.Year}}</p>
<p class="text-center"><span class="customMargin">Runtime: {{film.Runtime}}</span></p>
<p class="text-center"><span class="customMargin">Director: {{film.Director}}</span></p>
<p class="text-center"><span class="customMargin">Writer: {{film.Writer}}</span></p>
<p class="text-center"><span class="customMargin">Actors: {{film.Actors}}</span></p>
</div>
</div>
</div>
This is part of my main.html . In h3 and p tags, I get imdbId and blogContent from my database and put it in ng-repeat in order to traverse blog posts in list. I want to be able get other information(under // I WANT THIS PART) for every post in myBlogPost.
MainController.js
var refresh = function() {
$http.get('/myDatabase').success(function(response) {
$scope.myBlogPosts = response;
});
};
refresh();
This part work as expected when page loaded.
I need also these parts in Main Controller ;
var onGetFilmData = function (data) {
$scope.film = data;
};
var onError = function (reason) {
$scope.error = reason;
};
imdb.getImdbInfo(-- need Id --).then(onGetFilmData, onError);
But I need to put each post id somehow in order to get specific data from Imdb api.
Imdb.js
(function(){
var imdb = function($http){
var getImdbInfo = function (id) {
return $http.get('http://www.omdbapi.com/?i=' + id + '&plot=short&r=json')
.then(function(response){
return response.data;
});
};
return{
getImdbInfo: getImdbInfo
};
};
var module = angular.module('myApp');
module.factory('imdb', imdb);
})();
If I delete id part and put a specific id string in getImdbInfo function, all post in main.html fill with just one film information. I want to fetch those data for each film in my database(I am holding imdb id of each film in my database).
MainController
var jsonObj = {};
var refresh = function() {
$http.get('/myDatabase').success(function(response) {
jsonObj = response;
for(var i = 0; i < jsonObj.length ; i++){
jsonObj[i].title = '';
}
for(var i = 0; i < jsonObj.length ; i++){
(function(i) {
imdb.getImdbInfo(jsonObj[i].imdbId).then(function (data) {
jsonObj[i].title = data.Title;
});
})(i);
}
$scope.myBlogPosts = jsonObj;
});
};
refresh();
main.html
<div class="row" ng-repeat="post in myBlogPosts.slice().reverse()">
<br>
<div class="col-md-9 text-center">
<a href="#/blog-post/{{post._id}}">
<div class="thumbnail mTextBg customShadow">
<br>
<img class="img-responsive" src="http://placekitten.com/700/400" alt="">
<div class="caption">
<h3>{{post.imdbId}}</h3>
<p>{{post.blogContent}}</p>
</div>
</div>
</a>
</div>
<div class="col-md-3">
<!-- Side Widget Well -->
<div class="well sideBars customShadow">
<h4 class="text-center">{{post.title}}</h4>
</div>
</div>
</div>
I solve my problem with adding response from Imdb to my json object which is coming from database. So I can easily use them in ng-repeat.