How to use php for each inside javascript - javascript

I am working on Get Instagram Stories and show them on website project. So I have done getting stories with API from facebook. I also have an javascript code to show these stories just like instagram does. But here is my question >
How can I put my php variables inside the javascript?
How javascript adds or removes stories. I mean I need some kind of "for each loop"
My php variable codes;
<?php foreach ( $stories as $story ) : // loop over each story element ?>
<?php if ( 'VIDEO' == $story['media_info']['media_type'] ) : // story media is a video ?>
<div>
<video controls poster="<?php echo $story['media_info']['thumbnail_url']; ?>" style="max-width:300px">
<source src="<?php echo $story['media_info']['media_url']; ?>" />
</video>
</div>
<?php elseif ( 'IMAGE' == $story['media_info']['media_type'] ) : // story media is an image ?>
<div>
<img src="<?php echo $story['media_info']['media_url']; ?>" style="max-width:300px" />
</div>
<?php endif; ?>
<div>
<b>
<?php echo $story['media_info']['username']; ?>
</b>
</div>
<a href="<?php echo $story['media_info']['permalink']; ?>" target="_blank">
View on Instagram
</a>
<?php endforeach; ?>
My javascript code;
stories: [
Zuck.buildTimelineItem(
"ramon",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/users/1.jpg",
"Ramon",
"https://ramon.codes",
timestamp(),
[
[
"ramon-1",
"photo",
3,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/1.jpg",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/1.jpg",
"",
false,
false,
timestamp()
],
[
"ramon-2",
"video",
0,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/2.mp4",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/2.jpg",
"",
false,
false,
timestamp()
],
[
"ramon-3",
"photo",
3,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/3.png",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/3.png",
"https://ramon.codes",
"Visit my Portfolio",
false,
timestamp()
]
]
)
]

Just use PHP as a proxy and pass the JSON to the JS
Otherwise you have to do something like this
{
id: "storyid", // story id
photo: "..", // story photo (or user photo)
link: "", // story link (useless on story generated by script)
lastUpdated: "", // last updated date in unix time format
seen: false, // set true if user has opened
items: [ // array of items
// story item example
<?php
$cnt = 0;
foreach ( $stories as $story ) : // loop over each story element
?> {
id: "item<$cnt++ ?>", // item id
type: "<?= $story['media_info']['media_type'] ?>", // photo or video
length: 10, // photo timeout or video length in seconds - uses 3 seconds timeout for images if not set
src: "<?= $story['media_info']['media_url']; ?>", // photo or video src
preview: "", // optional - item thumbnail to show in the story carousel instead of the story defined image
link: "<?= $story['media_info']['permalink'];?>", // a link to click on story
linkText: "", // link text
time: "", // optional a date to display with the story item. unix timestamp are converted to "time ago" format
seen: false // set true if current user was read,
[customKey]: "", // custom-value
[anotherCustomKey]: "" // another-custom-value
}
<?php endforeach; ?>
]
}

Related

Passing variables to Html file in google scripts

I am trying to create an input tag for an HtmlTemplate function for each file in a folder on my google Drive.
This input tag works, but I'm trying to use variables to set the team (BAL) and the src id:
<input type="image" class="teamLogo" onClick="getTeam('BAL');" src="https://drive.google.com/uc?id=12p5P6dmmHTX3PIq0kyUKr2qhWtSkmi3h">
This is the scriptlet in my html file:
<? var logos = getTeamLogos() ?>
<? for (i in logos) { ?>
<input type="image" class="teamLogo" onClick="getTeam('"+logos[i][0]+"');" src="https://drive.google.com/uc?id="+logos[i][1]+"">
<? } ?>
And this is the getTeamLogos function I am calling:
function getTeamLogos(){
var getLogos = DriveApp.getFolderById('redacted').getFiles();
var logos = []
while (getLogos.hasNext()) {
var logo = getLogos.next();
var teamAbbrv = logo.getName();
var logoId = logo.getId();
logos.push([teamAbbrv,logoId])
}
logos.sort()
console.log(logos)
return logos
}
Here's the console.log from the getTeamLogos function:
[ [ 'ANA', '1A8UJAYuKCter4V0gvd6nYP7z8G_QpWzK' ],
[ 'BAL', '12p5P6dmmHTX3PIq0kyUKr2qhWtSkmi3h' ],
[ 'BOS', '1AVMrn7E3fOlgFc_slCFPGQjFG2eauAKF' ],
[ 'CLE', '1yY76xP_axJfbCmEZoSx2nDlILOaoKIBg' ],
[ 'CWS', '1ZCPbHLQ_iIB8WSQ_sPYELiSw3p23uzc2' ],
[ 'DET', '1GMmqhGr1eeCfoRgNMqliHFehwTopLVQE' ],
[ 'HOU', '1iN-78qrvkT_E7K-CCUZbfdZV_o1vokPk' ],
[ 'KC', '1vd_0mby6wV9qxSA4lvzBNPFi5bLnFsf3' ],
[ 'MIN', '1HP5gArugPbXBlsCKrtYs0cPmIcff-Uf0' ],
[ 'NYY', '1VIAYsnGgIKIG9VIIkcOVib446Wh2Ue1D' ],
[ 'OAK', '1dYECC_EJwc2_e2WGJ_H5W0hvOAmv3w7V' ],
[ 'SEA', '1jRotoBam7UFoCxpOxfBncdr6-JEcsnhq' ],
[ 'TB', '10UlOIjit_K7Vmyna85aAztRuXzULnpb_' ],
[ 'TEX', '1MgZfakotrGTrOotDVCNpehAKlWo7O4wp' ],
[ 'TOR', '1RwmaPY8o5oPYs_hJCiEvvVe3NEE9Kuth' ] ]
But I keep getting a malformed HTML content error:
Exception: Malformed HTML content: <input type="image" class="teamLogo" onClick="getTeam('"+logos[i][0]+"');" src="https://drive.google.com/uc?id="+logos[i][1]+""> .
I've tried every combination of single quote, double quote, plus sign, ampersand, can't get the syntax quite right.
I thought that in your HTML, the scriptlets are required to be modified as follows.
From:
<? var logos = getTeamLogos() ?>
<? for (i in logos) { ?>
<input type="image" class="teamLogo" onClick="getTeam('"+logos[i][0]+"');" src="https://drive.google.com/uc?id="+logos[i][1]+"">
<? } ?>
To:
<? var logos = getTeamLogos() ?>
<? for (i in logos) { ?>
<input type="image" class="teamLogo" onClick="getTeam('<?= logos[i][0] ?>');" src="https://drive.google.com/uc?id=<?= logos[i][1] ?>">
<? } ?>
The scriptlets are replaced the HTML template with the values of Google Apps Script. Please be careful about this.
Note:
As additional information, in the current stage, when the loop process is used with the HTML template, the process cost will become high. Ref (Author: me) So, in your situation, I thought that the following modification might be able to be used.
HTML side
<?!= values ?>
Google Apps Script side
const html = HtmlService.createTemplateFromFile("index");
html.values = getTeamLogos().map(([a, b]) => `<input type="image" class="teamLogo" onClick="getTeam('${a}');" src="https://drive.google.com/uc?id=${b}">`).join("");
const htmlOutput = html.evaluate();
// You can use htmlOutput to Web Apps, sidebar, dialog, and so on.
Reference:
HTML Service: Templated HTML

jQuery Full Calendar Events are not loading from Database in PHP,Codeigniter3

I implemented jQuery Full Calendar, as a separate module...That time it worked good. Now I want to show events after user logged in...User Login done... But issue with loading events only, events are added into Database.. But they won't be loaded into Calendar view
To redirect load.php, I used echo site_url('controller/method'),redirect('controller/method'). When I used redirect method it gives me 'json' data(the data which returned from load.php)
**views/calendar_view.php:**
<script>
$(document).ready(function(){
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events:'<?php echo site_url('Home/load'); ?>', /* redirect('Home/load');//<?php //$this->load->view('load')?>*/
selectable:true,
selectHelper:true,
**views/load.php:**
if($conn==false)
{
echo "Failed to connect to the Database | <br/>";
die(print_r(sqlsrv_errors(),true));
}
$timezone = new DateTimeZone("UTC");
$sql = "select * from events";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false)
{
die(print_r(sqlsrv_errors(),true));
}
while($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$data[] = array(
'id' => $row['id'],
'title' => $row['title'],
'start' => $row['start_event']->format("Y-m-d H:i:s"),
'end' => $row['end_event']->format("Y-m-d H:i:s")
);
}
I want to show events, after employee logged in successfully
It looks like views/load.php does not return anything, the jquery plugin expects a json object, so add the following to load.php
echo json_encode($data);
Furthermore as I remember the events in the plugin does not allow url's directly.
Therefore you will need to load the data from the url. Did not test it, but should be something like below.
$.get('<?php echo site_url('Home/load'); ?>', function(data) {
var calendar = $('#calendar').fullCalendar({
editable:true,
header:{
left:'prev,next today',
center:'title',
right:'month,agendaWeek,agendaDay'
},
events:data.parseJSON(),
selectable:true,
selectHelper:true,
});
You can check in your browser developer tools if the data was loaded correctly:
F.e. Chrome: https://developers.google.com/web/tools/chrome-devtools/network/reference

PHP and JQuery Variables in CodeIgniter

I was wondering if someone could explain me to the best way to go about this situation.
I have a sidebar that is populated with Li Elements from a foreach loop, that works fine.
Each element has an link that when clicked triggers a Jquery UI Dialog in which there is a text field to add a note and press Submit or cancel, this opens fine, submits fine.
I can't figure out how to retrieve say the link tag's id value and the dialogs
textarea value to submit them to the DB, so the DB is getting populated with 0's, from within the $.ajax Function, I'm sure it can be done and I'm sure I could hack it working but I want to know the right way to do it. Below is my attempt.
The JS
<script>
$(document).ready(function(){
var note;
$("#dialog").dialog({ autoOpen: false,
buttons:{"Add Note": function() {
$.ajax({
url:"<?php echo base_url();?>PropertyAdmin/addNoteToProperty",
data: {name: '20', value: note},
success:function(result){
alert("added");
},
error: function(result){
alert("fail");
},
cache : false
});
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
});
$(".clickable").click(function (e) {
// open and move the dialog
$("#dialog").dialog('option', 'position',[e.clientX+100,e.clientY]).dialog("open");
var element = $(this).find("#prop_note");
note = element.attr("value");
var myTag = $(this).attr('name');
return false;
})
})
</script>
The Dialog
<div id="dialog" title="Add Note">
<div>
<?php $attributes = array('role' => 'form'); echo form_open('PropertyAdmin/addProperty', $attributes); ?>
<div class="form-group">
<label for="prop_note" class="control-label">Note :</label>
<textarea id="prop_note" class="form-control" rows="3" name="prop_note"></textarea>
</div>
</form>
</div>
</div>
The CONTROLLER Function
function addNoteToProperty(){
$id = $this->input->post('name');
$note = $this->input->post('value');
$this->load->model('PropertyModel');
$this->PropertyModel->addNoteToProperty($id,$note);
}
The Model
function addNoteToProperty($propid, $note){
$data = array('prop_note'=> $note, 'prop_id' => $propid, 'prop_note_date' => now());
$this->db->insert('property_notes', $data);
}
One of my unparsed Li's
<li>Investment Properties
<ul>
<?php foreach($property as $row){ if($row['type_id'] != 1) { } else{ ?>
<li style="color: white" class="investmentitems inactive"><a id="<?php echo $row['id']; ?>" href="#"><?php echo $row['property_name'] ." ".$row['property_address1']; ?></a><?php echo anchor("FinancialInput/listproperty/".$row['id'],"Edit" ); ?><a class="clickable" href="" name="<?php echo $row['id']; ?>">Add Note</a></li>
<?php }} ?>
</ul>
</li>
Errors
PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for PropertyAdmin::addNoteToProperty()
Filename: controllers/PropertyAdmin.php
Line Number: 44
A PHP Error was encountered
Severity: Warning
Message: Missing argument 2 for PropertyAdmin::addNoteToProperty()
Filename: controllers/PropertyAdmin.php
Line Number: 44
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: id
Filename: controllers/PropertyAdmin.php
Line Number: 49
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: note
Filename: controllers/PropertyAdmin.php
Line Number: 49
A Database Error Occurred
Error Number: 1048
Column 'prop_note' cannot be null
INSERT INTO `property_notes` (`prop_note`, `prop_id`, `prop_note_date`) VALUES (NULL, NULL, 1396465225)
Filename: E:\wamp\www\oak\system\database\DB_driver.php
I believe getting the name value of the a just involves defining your variable outside of the click
<script>
$(document).ready(function(){
var note;
var name; //ADDED HERE
$("#dialog").dialog({ autoOpen: false,
buttons:{"Add Note": function() {
$.ajax({
url:"<?php echo base_url();?>PropertyAdmin/addNoteToProperty",
data: {name: name, value: $(prop_note).val()},
success:function(result){
alert("added");
},
error: function(result){
alert("fail");
},
cache : false
});
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
});
$(".clickable").click(function (e) {
// open and move the dialog
e.preventDefault();
$("#dialog").dialog('option', 'position',[e.clientX+100,e.clientY]).dialog("open");
name = $(this).attr('name'); //Changing the Value here
return false;
})
})
</script>
There you are defining the variable before the click event and changing it to the ID of the clickable link before sending it to the PHP controller in the AJAX request

Retrieve PHP Array with JSON and use the array in javascript to populate a playlist

I try to understand how it work. At the beginning, I was using inside my html code a php array with db and after that I was extracting my array inside my playlist.
Here the example:
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$row['emplacement'] = str_replace("../", "../../", $row['emplacement']);
$row['poster'] = str_replace("../", "../../", $row['poster']);
$row['duration'] = str_replace("00:", "", $row['duration']);
$info = '{artist:"'.$row['artiste'].'", title:"'.$row['track'].'", album:"'.$row['album'].'", mp3:"'.$row['emplacement'].'", cover:"'.$row['poster'].'", duration:"'.$row['duration'].'"}';
array_push($fileinfo, $info);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(
[
<?php
//for each file in directory
$arrlength=count($fileinfo);
for($x=0;$x<$arrlength;$x++)
{
if ($x < ($arrlength - 1))
{
echo $fileinfo[$x].",\n\t\t";
}else
{
echo $fileinfo[$x]."\n\t\t";
}
}
//the result look like this:
//{artist:"Boy Sets Fire", title:"After the Eulogy", album:"After The Eulogy",
mp3:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/01_After_the_Eulogy-JAH.mp3",
cover:"../../music/Punk/Hardcore_Punk/Boy_Sets_Fire_-_After_the_Eulogy-2000-
JAH/Folder.jpg", duration:"03:31"},
?>
],
To use everything more dynamically, I try to use JSON with PHP inside my javascript
And my code look like this:
var sourceplayer =
{
datatype: "json",
datafields: [
{ name: 'artiste' },
{ name: 'title' },
{ name: 'album' },
{ name: 'mp3' },
{ name: 'cover' },
{ name: 'duration' }
],
url: 'player.php'
};
$('#player').ttwMusicPlayer(
[
],
So afert url: 'player.php', I don't know how to work with result. It's an array of data like this: "Rows":[{"no_track":"1","track":"Grandma Dynamite","artiste":"24-7 Spyz","album":"Harder Than You","genre":"Alternative","year":"1989","duration":"00:03:44"}
And I want to use it inside the bracket of $('#player').ttwMusicPlayer(
Please give me a cue or an simple example to help me with this. I'm not using pure jplayer but a similar one.
Thanks in advance
Regards,
Eric
PHP json_encode - http://us2.php.net/json_encode
<?php
$fileinfo=array();
$count=0;
//SQL Query
$query = "select track, artiste, album, emplacement, duration, poster from tempo where genre like '%%' ORDER BY no_track";
$con=mysqli_connect("localhost","user","password","db_table");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resultat = mysqli_query($con,$query);
while($row = mysqli_fetch_array($resultat))
{
$fileinfo[] = array(
'mp3' => str_replace("../", "../../", $row['emplacement']),
'cover' => str_replace("../", "../../", $row['poster']),
'duration' => str_replace("00:", "", $row['duration']),
'artist' => $row['artiste'],
'title' => $row['track'],
'album' => $row['album']
);
}
mysqli_close($con);
?>
...
$('#player').ttwMusicPlayer(<?php echo json_encode($fileinfo); ?>);

Add File Attachment Name and URL into Javascript

I'm working on incorporating the jPlayer into our WordPress site. I don't particularly care for the two plugins that are available as our client is a bit on the technically deficient side. What we are looking to accomplish is have the Title and Mp3 load into the JavaScript for the jPlayer playlist. Currently everything is loading just fine and returning the appropriate texts, however I'm unable to get the File Name and the Attachment URL to load appropriately. I'm fairly new to java and wordpress for that matter. If you would like to see a live site example, please visit http://www.ourgoodfight.com/?p=6054
<!--Begin Jplayer Playlist -->
<script type="text/javascript">
//<![CDATA[
$(document).ready(function(){
new jPlayerPlaylist({
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
}, [
<?php
global $post;
$jukebox_args = get_posts( array(
'post_type' => 'attachment',
'posts_per_page' => -1,
'post_mime_type' => 'audio/mpeg',
'orderby' => 'menu_order',
'order' => 'ASC',
'post_parent' => $post->ID
));
$the_jukebox_query = new WP_Query( $jukebox_args );
?>
<!--This is what needs to loop -->
<?php
$loop = new WP_Query( $jukebox_args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
{
title:<?php echo apply_filters( 'the_title', $attachment->post_title ); ?>,
mp3:<?php echo wp_get_attachment_url( $attachment->ID, false ); ?>,
},
<?php endwhile;?>
<!--This would be the end of the loop -->
], {
swfPath: "<?php echo get_template_directory_uri(); ?>/js",
supplied: "mp3",
wmode: "window"
});
});
//]]>
</script>
You are attempting to use the var $attachment to access your attachments data. But you don't ever set your $attachment var to actually contain any data, so its currently empty. As you have set up your post data within your loop using $loop->the_post(); you should be able to;
title:<?php echo apply_filters( 'the_title', get_the_title() ); ?>,
mp3:<?php echo wp_get_attachment_url( get_the_ID(), false ); ?>,
http://codex.wordpress.org/Class_Reference/WP_Query
Take note of the point about re setting your post data using wp_reset_postdata().

Categories

Resources