Calling a Javascript function from PHP with variables created in php - javascript

I have a javascript function in a file comment_insert.js:
function comment_insert(data,ul_id) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('#' + ul_id).prepend(t);
}
I want to call this function from a php file display.php as:
$smthng = new stdClass();
$smthng->comment_id = 24;
$smthng->Userid = 1;
$smthng->comment = "Hard coded comments";
$smthng->Username = "Sagar_username";
//$smthng->profile_img = "images/Setting-icon.png";
$data = json_encode($smthng);
$ul_id = "ul218";
comment_insert(jQuery.parseJSON($data),$ul_id);
The function being called is the same as in comment_insert.js which accepts 2 inputs (data and ul_id). These are being created in display.php and then I want to execute the function.

Assuming that the PHP code is in the same file as Javascript and is being used for front end out put to the browser, you can do this:
<?php
$smthng = new stdClass();
$smthng->comment_id = 24;
$smthng->Userid = 1;
$smthng->comment = "Hard coded comments";
$smthng->Username = "Sagar_username";
//$smthng->profile_img = "images/Setting-icon.png";
$data = json_encode($smthng);
$ul_id = "ul218";
?>
<script type="text/javascript">
comment_insert(jQuery.parseJSON(<?php echo $data ?>), <?php echo $ul_id ?>);
</script>
However, if this is not in a file that is producing output to the browser, you cannot execute Javascript server-side

In order to execute Javascript in PHP you'll need to install the V8js Extension.
After installing you should parse your comment_insert.js to a PHP variable via file_get_contents and execute it somehow like this:
<?php
$v8 = new V8Js();
/* Get you js file's content */
$JS = file_get_contents("PATH/TO/JS-FILE/comment_insert.js");
try {
$v8->executeString($JS, 'basic.js');
} catch (V8JsException $e) {
var_dump($e);
}
?>
Note: In order to make it work, I think you'll replace the jQuery call with native JS.
So modify you comment_insert.js to something like this:
function comment_insert(data,ul_id) {
var t = '';
t += '<li class="comment-holder" id="_' + data.comment_id + '">';
t += '<div class="user-img">';
t += '<img src="' + data.profile_img + '" class="user-img-pic" />';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field" >' + data.Username + '</h3>';
t += '<div class="comment-text">' + data.comment + '</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">[x]</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
//$('#' + ul_id).prepend(t);
elem = document.getElementById(ul_id);
elem.insertBefore(t);
}

Related

Uncaught TypeError: Cannot read property 'length' of undefined on node.js

How's it going?
I have been trying to put some upvotes functionalities on this web app I have been developing but I am stuck. Please help. The error that it is shown on Chrome's console is:
Uncaught TypeError: Cannot read property 'length' of undefined
at createUpvotesSection ((index):41)
at XMLHttpRequest.ajax.onreadystatechange ((index):343)
But could it be? I have already stated the "createUpvotesSection" and tried to use it in Index.ejs as you can see below:
Index.ejs:
function showNewsfeed() {
var ajax = new XMLHttpRequest();
ajax.open("POST", "/getNewsfeed", true);
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "";
for (var a = 0; a < response.data.length; a++) {
var data = response.data[a];
html += '<div class="central-meta item">';
html += '<div class="user-post">';
html += '<div class="friend-info">';
html += '<figure>';
html += '<img src="' + mainURL + "/" + data.user.profileImage + '" style="width: 45px; height: 45px; object-fit: cover;">';
html += '</figure>';
html += '<div class="friend-name">';
html += '<ins>';
if (data.type == "post")
{
html += '<a href="/user/' + data.user.username + '">';
html += data.user.username;
html += '</a>';
}
else
{
html += data.user.name;
}
html += '</ins>';
var createdAt = new Date(data.createdAt);
var date = createdAt.getDate() + "";
date = date.padStart(2, "0") + " de " + months[createdAt.getMonth()] + ", " + createdAt.getFullYear();
html += '<span>Publicado em: ' + date + '</span>';
html += '</div>';
html += '<div class="post-meta">';
html += '<div class="description">';
html += '<p>';
html += data.caption;
html += '</p>';
html += '</div>';
if (data.image != "") {
html += '<img src="' + mainURL + "/" + data.image + '">';
}
if (data.video != "") {
html += '<video style="height: 359px; width: 100%;" controls src="' + mainURL + "/" + data.video + '"></video>';
}
html += createUpvotesSection(data);
html += '</div>';
html += '</div>'
html += '</div>';
html += '</div>';
}
document.getElementById("newsfeed").innerHTML = html;
}
};
Header.ejs (shorter version):
function createUpvotesSection(data) {
var isUpvoted = false;
for (var b = 0; b < data.upvoters.length; b++) {
var upvoter = data.upvoter[b];
if (upvoter._id == window.user._id) {
isUpvoted = true;
break;
}
}
var html = "";
html += '<div class="we-video-info">';
html += '<ul>';
html += '<li>';
var className = "";
if (isUpvoted) {
className = 'upvote';
} else {
className = "none";
}
html += '<span class="' + className +'" onclick="toggleUpvotePost(this);" data-id="' + data._id +'">';
html += '<i class="ti-thumb-up"></i>';
html += '<ins>' + data.upvoters.length + '</ins>';
html += '</span>';
html += '</li>';
html += '<li>';
html += '<span class="comment" title="Comments">';
html += '<i class = "fa fa-comments-o"></i>';
html += '<ins>' + data.comments.length + '</ins>';
html += '</span>';
html += '</li>';
html += '<li>';
html += '<span class="share" onclick="sharePost(this);" data-id="' + data._id +'">';
html += '<i class="ti-share"></i>';
html += '<ins>' + data.shares.length + '</ins>';
html += '</span>';
html += '</li>';
html += '</ul>';
html += '</div>';
return html;
}
According to the error that Cannot read property 'length' of undefined on node.js that means the variable that you try to get length of it is undefined variable. try to define that first before you take the length

How to by pass HTML encoding string in text fields?

I am setting a field in my HTML label from Viewbag which has a "'" in the text. when the HTML pulls up it shows ' in place of "'". How do I stop it from getting encoded?
Please find the code below.
setting text fileds in the HTML view.
$('#thStudentName').text('#ViewBag.Name');
if (sessionData.data.EventDate2Def != '' || sessionData.data.EventDate2Def != null)
$('#tdWhen').text(sessionData.data.EventDate1Def + ' and ' + sessionData.data.EventDate2Def);
else
$('#tdWhen').text(sessionData.data.EventDate1Def);
$('#tdWhere').text(sessionData.data.FacilityName);
$('#tdLocated').text(sessionData.data.Address1 + ', ' + sessionData.data.City + ', ' + sessionData.data.State + ' ' + sessionData.data.Zip);
$('#tdPhone').text(sessionData.data.Phone);
$('#tdDirections').text(sessionData.data.Directions);
$('#tdRoom').text(sessionData.data.RoomNumber);
Populating a different section with Dynamic data.
function populateSessionTable() {
var count = 1;
$('#SessionTable').html('');
var tableContent = '';
var record = '';
var Sessions = sessionData.data.Sessions;
tableContent = generateTableContent(count, Sessions[0].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').html(tableContent);
var radioStatus = '';
for (var i = 0; i < Sessions.length; i++) {
var content = Sessions[i];
radioStatus = '';
if (content.Capacity == content.Registered || content.Closed)
radioStatus = '<input disabled class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
else if (content.StartDateTimeDef == '#ViewBag.WorkshopDateDef' && t24to12Convert(content.StartTimeString) == t24to12Convert('#ViewBag.WorkshopTime'))
radioStatus = '<input class="selected-session radio" checked name="SessionId" type="radio" value="' + content.SessionId + '">';
else
radioStatus = '<input class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
record += '<tr>';
record += '<td class="session-schedule-table-btn">';
record += radioStatus;
record += '</td>';
record += '<td class="session-schedule-table-session-number"> ' + content.Number + ' </td>';
record += '<td class="session-schedule-table-session-start-time">' + t24to12Convert(content.StartTimeString) + '</td>';
record += '</tr>';
$('#SessionTBody' + count).append(record);
record = '';
if(Sessions.length != i + 1)
{
if(Sessions[i].StartDateTimeDef != Sessions[i + 1].StartDateTimeDef)
{
tableContent = '';
count++;
tableContent = generateTableContent(count, Sessions[i+1].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').append(tableContent);
}
}
}
}
populateSessionTable();
The preview shows the name in the correct format, but when it gets rendered instead of having the quote, it shows '
This is how the output is coming up
So finally it was a stupid problem and I swear I had tried this before, but this is the code that worked.
var stuName = '#ViewBag.Name';
stuName = stuName.replace("'", "'");
$('#thStudentName').text(stuName);

How do I get an ID from a click event handler?

I am trying to create an ID to use as a selector for a modal that I will then be able to access the display properties.
$.ajax({
url: 'https://randomuser.me/api/?results=12',
dataType: 'json',
success: function(data) {
console.log(data);
employees = data.results;
$.each(employees, function (i, employee) {
newHTML += '<div id="' + i + '" class="container">';
newHTML += '<div class="employee-img-container">';
newHTML += '<img class="employee-img" src="' + employee.picture.large + '" alt="employee image">';
newHTML += '</div>';
newHTML += '<div class="employee-info-container">';
newHTML += '<h3 class="employee-name">' + employee.name.first + ' ' + employee.name.last + '</h3>';
newHTML += '<p class="employee-email">' + employee.email + '</p>';
newHTML += '<p class="employee-location">' + employee.location.city + ', ' + employee.location.state + '</p>';
newHTML += '</div></div></div></div>';
employeeArr.push(employee);
modalHTML += '<div id="modal' + i + '" class="modal">';
modalHTML += '<div class="modal-content">';
modalHTML += '<div class="modal-header">';
modalHTML += '<span class="close">×</span>';
modalHTML += '<img class="employee-img" src="' + employee.picture.large + '" alt="employee image">';
modalHTML += '<h2 class= emp-modal-name>' + employee.name.first + ' ' + employee.name.last + '</h2>';
modalHTML += '</div';
modalHTML += '<div class="modal-body">';
modalHTML += '<p>Employee Info</p>';
modalHTML += '</div></div></div>';
modalArr.push(employee);
});
$('.grid-container').html(newHTML);
$('.modal-container').html(modalHTML);
$('.container').on('click', function (event) {
console.log(event.currentTarget.id);
let newId = '#modal' + event.currentTarget.id;
let displayModal = $(newId)
let display = document.querySelector(newId);
//displayModal.style.display = 'block';
console.log(displayModal);
console.log(display);
console.log(newId);
});
}
});
When I log the event.currentTarget.id I get a number, and I can also create a string that I want to use as a selector. I can't figure out how to use it as the actual sector though. Not sure if I need to use an if statement to compare it to the id of the modal class that i want to display. Thanks!
Try like this
$(document).ready(function() {
$("a").click(function(event) {
alert(event.target.id);
});
});

How to limit the results of codepen rss feed

I am working on my codepen rss feed for my website. I am having small issue limiting the results.
Currently displays over 10 results in the rss feed. But I would like to know the best way to limit results to 5
Question: How could I limit the results of my rss feed to 5 only.
Codepen Example
<script type="text/javascript">
$(document).ready(function(){
url = 'http://codepen.io/riwakawebsitedesigns/public/feed/';
$.ajax({
type: "GET",
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=1000&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
error: function(){
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: function(xml){
var postlist = xml.responseData.feed.entries;
var html = '<ul class="list-unstyled">';
$.each(postlist, function(idx, data) {
html += '<li>';
html += '<h3 class="codepen_feed_title">' + data.title + '</h3>';
html += '<a href="' + data.link + '" target="_blank">';
html += '<span class="codepen_feed_content">Click Here To View It!</div>';
html += '</a>';
html += '</li>';
});
html += '</ul>';
$(".codepen_feed").append(html);
}
});
});
</script>
Use a return value for your each loop
$.each(postlist, function(idx, data) {
var title = data.title;
html += '<li>';
html += '<h3 class="codepen_feed_title">' + data.title + '</h3>';
html += '<a href="' + data.link + '" target="_blank">';
html += '<span class="codepen_feed_content">Click Here To View It!</div>';
html += '</a>';
html += '</li>';
return idx < 4;
});

Need help with Flickr/JSON/Javascript issue when displaying gallery images

Wondering if anyone can help me. I'm trying to put together a weekly photo competition page by pulling in photos from a Flickr gallery, but I can't get the images to display. It works OK for groups, but having some problems with the gallery code. Getting the correct JSON response, but can't get the results to display on the page as good as the group images do.
Here's my Javascript:
$(function() {
var map;
var markers = [];
var infowindow;
// Get gallery photos
var visibleGallery;
$.getJSON("http://api.flickr.com/services/rest/" +
"?method=flickr.galleries.getPhotos" +
"&api_key=XXXX" +
"&photoset_id=XXXX" +
"&extras=geo,tags,url_sq,url_t,url_s,url_m,url_o" +
"&format=json&jsoncallback=?", function(data, textStatus) {
var htmlString = '<div id="weekContainer">';
var weeks = sortIntoWeekArrays(data.photos.photo);
$.each(weeks, function(i, week)
{
var weekNumber = i + 1;
var numberOfWeeks = weeks.length - 1;
htmlString += '<div id="week' + weekNumber + '">';
htmlString += '<ul class="weeks">';
if(i < numberOfWeeks)
{
htmlString += '<li><a class="weekLinksNext" href="#"><span>Next</span></a></li>';
}
var sunday = new Date(week.monday.toUTCString());
sunday.setDate(week.monday.getDate() + 6);
htmlString += '<li class="weekTitle">Week ' + weekNumber + ':</li><li class="weekDate"> ' + week.monday.format("ddd d mmm") + ' — ' + sunday.format("ddd d mmm") + '</li>';
if(i > 0)
{
htmlString += '<li><a class="weekLinksPrev" href="#"><span>Previous</span></a></li>';
}
htmlString += '</ul>';
if(week.winner !== undefined)
{
htmlString += '<p class="galleryTitleFirst">Photo of the Week</p>';
htmlString += '<ul class="imagesWinners">';
htmlString += '<li class="winner"><a href="http://www.flickr.com/photos/' + week.winner.owner + '/' + week.winner.id + '" target="_blank">';
htmlString += '<img title="' + week.winner.title + '" src="' + week.winner.url_m + '" alt="' + week.winner.title + '" />';
htmlString += '</a></li>';
htmlString += '<li class="name">' + week.winner.title + '</li>';
htmlString += '<li class="owner">' + 'by ' + week.winner.ownername + '</li>';
htmlString += '</ul>';
}
htmlString += '<p class="galleryTitle">Our other favourites this week</p>';
htmlString += '<ul class="imagesRunnersUp">';
$.each(week.images, function(i, item)
{
htmlString += '<li><a href="http://www.flickr.com/photos/' + item.owner + '/' + item.id + '" target="_blank">';
htmlString += '<img title="' + item.title + '" src="' + item.url_sq + '" alt="' + item.title + '" />';
htmlString += '</a></li>';
if(item.longitude == "0" && item.latitude == "0")
{
return true;
}
var latlng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title:item.title
});
marker.content = '<img title="' + item.title + '" src="' + item.url_s + '" alt="' + item.title + '" />';
markers.push(marker);
});
htmlString += '</ul>';
htmlString += '</div>';
});
htmlString += '</div>';
$('div#weekViewer').append(htmlString);
$('div#weekContainer > div').css('float', 'left').css('margin-right', '30px');
$('div#weekContainer').width(weeks.length * 450);
$('div#weekContainer .weekLinksPrev')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '-=450'}, 'slow');
return false;
});
$('div#weekContainer .weekLinksNext')
.click(function(){
$('div#weekViewer').animate({scrollLeft: '+=450'}, 'slow');
return false;
});
});
});
function sortIntoWeekArrays(items)
{
var weeks = [];
// Returns single dimension array containing single dimension arrays
$(items).each(function(i, item)
{
var monday = new Date(item.dateadded * 1000);
monday.setDate(monday.getDate() - monday.getDay() + 1);
monday.setHours(0,0,0,0);
var week, thisWeek;
for (i in weeks)
{
week = weeks[i];
if(week.monday - monday == 0)
{
thisWeek = week;
break;
}
}
if(thisWeek === undefined)
{
thisWeek =
{
monday: monday,
images: []
};
weeks.push(thisWeek);
}
if($.inArray('winner', item.tags.split(" ")) > -1)
{
thisWeek.winner = item;
}
else
{
thisWeek.images.push(item);
}
});
return weeks.sort(function(first, second)
{
return (first.monday > second.monday) - (first.monday < second.monday);
});
}
Any help would be fantastic :)
Regards,
David
Worked it out after some help from a friend. I was missing the date_upload value in the extras argument and item.dateadded needed to change to item.upload.

Categories

Resources