Show posts with ajax - Use of undefined constant postObj - assumed 'postObj' - javascript

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.

Related

JavaScript ajax didn't working.Where am I going wrong?

<div class="media-bottom">
#Html.TextAreaFor(model => model.Message, new { #class = "ui form", #rows = "5", #maxlenght = "300", #placeholder = "Paylaşmak istedikleriniz" })
</div>
<br />
<div class="footer-logo">
<button class=" mini ui right labeled right floated icon button" id="Button_Click" onclick="javascript: Button_Click();">
<i class="right arrow icon"></i>
Paylas
</button>
<div class="container bootstrap snippets bootdey downlines">
<div class="row">
<div class="col-md-6 col-xs-12">
<section class="widget">
<div class="widget-body">
<div class="widget-top-overflow windget-padding-md clearfix bg-info text-white">
</div>
<div class="post-user mt-n-lg">
<span class="thumb-lg pull-left mr media-object">
<img class=" img-circle" src="https://bootdey.com/img/Content/user_3.jpg" alt="...">
</span>
<span class="thumb-lg pull-right mr star">
<img src="~/Content/img/star.png" />
</span>
<div class="Thanksicon">
</div>
<div class="namespace">
<h5 class="mt-sm fw-normal text-black txt post">
#Html.DisplayFor(model => model.FullName)
<br />
<small class="text-black text-light departmen post">#Html.DisplayFor(model => model.Departmen)</small>
</h5>
</div>
</div>
<br />
<br />
<div class="text-light fs-mini m" id="Label1">
<div id="label1">
<p class="article">
#Html.DisplayTextFor(model=>model.Message)
</p>
</div>
<div class="thanksnames">
<span class="thumb-xs avatar mr-sm">
<img class="img-circle thank" src="https://bootdey.com/img/Content/user_2.jpg" alt="...">
</span>
<div class="mt-sm fw-normal text-black " id="person"> <small class="text-black text-light">Rose Tyler</small></div>
</div>
<br />
<div class="img"></div>
<div class="fs-mini text-muted text-right"><time class="time-table-top"></time></div>
</div>
</div>
</section>
</div>
</div>
</div>
This is my javascript
$(function () {
$('#Button_Click').on('click', function () {
$.ajax({
type: "POST",
url: '#Url.Action("Share")',
data: {
fullname: $("#username").val(),
departmen: $("#departmen").val(),
textarea: $(".ui.form").val()
},
datatype: "json",
success: function (data) {
$('.downlines').html(result);
}, error: function (data) {
}
});
});
});
This is my controller httppost
[HttpPost]
private JsonResult Share(SocialMedia data,string id)
{
var employee = _employeeRepository.GetById(id);
ViewBag.IsOwner = id == Session.GetEmployeeNo();
if (Session["MediaList"] == null)
{
Session["MediaList"] = new List<SocialMedia>();
}
var fullname = data.FullName;
var departmen = data.Departmen;
var textarea = data.Message;
foreach (MediaList list in data.MediaLists)
{
list.FullName = fullname;
list.Departmen = departmen;
list.Message = textarea;
list.Date = DateTime.Now.ToLocalTime();
if(data.Photo!=null)
{
list.Photo = data.Photo;
string fileName = Path.GetFileNameWithoutExtension(list.Photo);
list.Photo = "~/Image/" + fileName;
string _path = Path.Combine(Server.MapPath("~/Image/"),fileName);
}
}
return Json(new { data = PartialView("~/Views/SocialMedia/DisplayTemplates/MediaList.cshtml") });
// return PartialView("~/Views/SocialMedia/DisplayTemplates/MediaList.cshtml",
//return Json(new { success = true, message = GlobalViewRes.CreatedSuccessfully }, JsonRequestBehavior.AllowGet);
}
When I write an article and press the button, I want the page to appear below without refreshing and I want it to be repeated. It should be with the whole design. But when I press the button, I made ajax, but my ajax does not work, where am I going wrong?
Sorry for my English:)
success: function (data) {
$('.downlines').html(result);
}, error: function (data) {
}
You handle the data named 'data'. Then you are trying use it like 'result'. What is result, where is it came from? Whatever, try this
$('.downlines').html(data)

send data from ajax GET to ejs file

I am retrieving some user data with an ajax GET call, and want to display each user in a bootstrap card, so that I can filter these on the page using jQuery.
Currently, I get the data, iterate over each user and append some card elements to the <div class="card-deck"></div>:
jQuery:
$(document).ready(function() {
$.getJSON('/api/user/all')
.then(data => {
$.each(data, function (i, user) {
var userCard = '<div class="col-md-auto mb-4">' +
'<div class="card matches mx-auto" style="width: 18rem; height: 24rem;">' +
'<div class="card-body">' +
'<h5 class="card-title">' + user.username + '</h5>' +
'<p class="card-text">' + user.jobTitle + '</p>' +
'<p class="card-text">' + user.city + '</p>' +
'</div>' +
"</div>" +
"</div>";
$('#userList').append(userCard);
});
})
})
ejs:
<div class="row">
<div class="card-container align-items-left">
<div class="card-deck" id="userList">
// cards go here ...
</div>
</div>
</div>
This works, but there will be a lot of html that goes into building the cards, so I would prefer to send the entire user object (below this is user) to the .ejs file, so that I can build the card there:
<div class="row">
<div class="card-container align-items-left">
<div class="card-deck" id="userList">
<div class="col-md-auto mb-4">
<div class="card matches mx-auto" style="width: 18rem; height: 24rem;">
<div class="card-body">
<h5 class="card-title"><%=user.username%></h5>
<p class="card-text"><%=user.jobTitle%></p>
<p class="card-text"><%=user.city%></p>
</div>
</div>
</div>
</div>
</div>
</div>
Is this a job fo the jQuery data method?
You need to implement an endpoint that fetches user information and forms the template for your userList div and sends the data back as a plain html string.
This endpoint has to be called from the client via an ajax call and set the response html to the div
Server
app.get('/api/user/all',(req, res){
//get user data
const data = [{username:"john",jobTitle:"a",city:"b"},{username:"doe",jobTitle:"a",city:"b"}];
res.render('userTemplate', {users:data} ,function(err, html) {
res.send(html);
});
Client
$.ajax({
url: "/api/user/all",
cache: false,
success: function(html){
$("#userList").innerHtml(html);
}
});
userTemplate.ejs
<% for(var i=0; i < users.length; i++) { %>
<div class="col-md-auto mb-4">
<div class="card matches mx-auto" style="width: 18rem; height: 24rem;">
<div class="card-body">
<h5 class="card-title"><%= users[i].username %></h5>
<p class="card-text"><%= users[i].jobTitle %></p>
<p class="card-text"><%= users[i].city %></p>
</div>
</div>
</div>
<% } %>
EJS is server-side code.
If you want to generate your HTML server side instead of modifying the DOM client side, then replace getJSON with an ajax call (with dataType: "html") and change /api/user/all to an endpoint (which you will have to create) which gets the data and inserts it into an EJS template.

Append external json data to div category wise

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>

Passing variable from JavaScript to PHP using AJAX doesn't show anything

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.

How to make two times for a loop in javascript?

I want to javascript loop for wrapping two line of products layouts after i got a respond from ajax.
Purposed: I want to get result like below
<div class="owl-item">
<div class="row item">
<div class="product">
<div class="image">
<img src="asset/img/main/9.jpg" alt="img">
<div class="promotion"><span class="discount">4</span></div>
<div class="description">
<div class="price"><span>1.0000</span></div>
<h4></h4><p>short detial</p>
</div>
</div>
</div>
</div>
<div class="row item">
<div class="product">
<div class="image">
<img src="9.jpg"alt="img">
<div class="promotion"><span class="discount">4</span></div>
<div class="description">
<div class="price"><span>2.0000</span></div>
<h4></h4>
<p>short detial</p></div>
</div>
</div>
</div>
</div>
As the above html planned I want to loop <div class="owl-item"> one times then I will loop <div class="row item"> two times So my html layout will wrap my products as the below images.
$.ajax({
type: "GET",
url: "<?php echo base_url('main/dataaccess'); ?>",
dataType: "json",
cache: false,
success: function (data, st) {
if (st == 'success') {
$.each(data, function (i, obj) {
var out = '<div class="row item">';
out += '<div class="product">';
out += '<div class="image">';
out += '<img src="asset/img/main/9.jpg" alt="img" class="img-responsive">';
out += '<div class="promotion"><span class="discount">' + obj.prodId + '</span> </div>';
out += '<div class="description"><div class="price"><span>' + obj.prodPrice + '</span></div><h4>' + obj.prodName + '</h4>';
out += '<p>short detial</p>';
out += '</div>';
out += '</div>';
$(out).appendTo("#ps");
});
$("#ps").owlCarousel({
navigation: false,
pagination: false,
items: 8,
itemsTablet: [408, 2]
});
}
}
});
This is the layout that i want to get
But as my code I will got layout as below that I don't want it
Are one of those classes that are applying to your div set as display:inline-block ? I suggest inspecting the rendered page to confirm that the divs are display: block.

Categories