How to use a javaScript Variable within PHP? - php

What I have at the moment is a simple Facebook app that has pulled the video information from a YouTube channel.
Just now, I embed the first video of the response from YouTube into the placeholder along with the title, views and description and all videos (including the first) are displayed below the div that holds the embedded video.
Then, when the user clicks any of the video thumbnails, that video is then embedded in the placeholder div.
I can get this to work by hard-coding the id of the video inside the YouTube associative array but I can't figure out how to use the id variable with PHP in the last line of my jQuery code.
Here is my current code:
$url = 'http://gdata.youtube.com/feeds/api/videos?max-results=20&alt=jsonc&orderby=published&format=5&safeSearch=none&author=CHANNELID&v=2';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body = curl_exec($ch);
curl_close($ch);
$data = json_decode($body, true);
?>
<div id="placeholder" style="font-family:Helvetica; max-width:500px; margin:0 0 20px 0;">
<div id="player"><iframe width="480" height="274" src="https://www.youtube.com/embed/<?php echo $data['data']['items'][0]['id']; ?>" frameborder="0" allowfullscreen></iframe></div>
<div class="title" style=" font-size:14px; font-weight:bold; color:#3B5998; margin:2px 0 3px 0;"><?php echo $data['data']['items'][0]['title']; ?> </div>
<div class="views" style="color:#BBB; font-size:12px;"><?php echo $data['data']['items'][0]['viewCount'];?> views</div>
<div class="description" style="font-size:14px;"><?php echo $data['data']['items'][0]['description'];?></div>
<div class="hr" style="padding:5px 0 0 0; float:left; border-bottom: 1px solid #96CC90; width:480px;"></div>
</div>
<?php
foreach($data['data']['items'] as $item) {
$id = $item['id'];
$description = $item['description'];
$description = str_replace('uk.opticalexpress.com', '', $description);
$description = str_replace('-', '', $description);
$description = trim($description);
$thumb = $item['thumbnail']['sqDefault'];
$i = 0;
?>
<div class="video" id="<?php echo $i; ?>" style="font-family:Helvetica; float:left; max-width:150px; min-height:130px; margin:0 0px 20px 10px;">
<div class="thumb" style="position:relative; left:0; top:0;">
<img src="<?php echo $item['thumbnail']['sqDefault'];?>" title="<?php echo $description;?>" style="position:relative; top:0; left:0px;"/>
<img src="../images/play-thumb.png" style="position:absolute; top:30px; left:45px;"/>
</div>
<div class="title" style="font-size:14px; font-weight:bold; color:#3B5998; margin:2px 0 3px 0;"><?php echo $item['title']; ?> </div>
<div class="views" style="font-size:12px;"><?php echo $item['viewCount'];?> views</div>
</div>
<?php
$i++;
}
?>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.video').click(function() {
var id = $(this).attr('id');
$('#placeholder').fadeOut('slow');
$('#placeholder').html('<div id="player"><iframe width="480" height="274" src="https://www.youtube.com/embed/<?php echo $data['data']['items'][1]['id']; ?>" frameborder="0" allowfullscreen></iframe></div>');
$('#placeholder').fadeIn('slow');
});
});
</script>
Sorry for the wall of text (and inline css)!

Difficult... I would watch the click event on .video with jQuery, then carry out a GET request to a PHP file on the server (RESTish) which would generate the HTML needed for the iframe, then set the #video html to the html you just received. Might work...
Another possibility, is to load all the iframes, then on .video click just show the one matching the same unique id or something. This would mean more load time for your users though, best to go with the AJAX type approach.

you can use the ajax by doing this, i have done it like this way, hope this will also work for you.
<div id="video1" class=".temp"></div>
<script type="text/javascript">
$(document).ready(function() {
$('.temp').click(function() {
var currentId = $(this).attr('id');
showVideo(currentId);
});
};
function showVideo(str)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("VideoFrameDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","inc/AjaxOnClickValues.php?id="+str,true);
xmlhttp.send();
}
</script>

Related

What's wrong in my ajax?

I own a site called flopl.com. It's pretty basic. Upload your files, and get a URL back with a link to the file. But I wasn't the one coding it, and now I can't get help from the person who did anymore. There's something wrong in the code, but I don't know enough to figure out what. So.. Here's the code:
HTML:
<!DOCTYPE html>
<html style="width:100%">
<head>
<title>flopl</title>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8" />
<link rel="shortcut icon" href="http://flopl.com/images/favicon.ico" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:25px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:-1px; left:48%; }
</style>
</head>
<body style="width:100%">
<div style="background-color:#2d2d2d; width: auto; height:150px; padding:-10px; margin-top:-20px;">
</div>
<div style="background-color:#8be1ab; width: auto; height:10px; padding:-10px; margin-top:0px;">
</div>
<center>
<img width="275px" src="images/logo.png" style="position:absolute; margin-top:-145px; margin-left:-145px;" />
</center>
<div style="width:400px; margin:auto; position:relative; margin-top:15%;" >
<center>
<div style="margin-top:90px; margin-left:25px;">
<p style="word-spacing:0.6px; font-family:Helvetica font-weight:light; margin-top:-20px; position:center;">Upload any type of file,</p>
<p style="word-spacing:0.6px; font-family:Helvetica font-weight:light; margin-top:-20px; position:center;">with no compression!</p>
</div>
</center>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_image.php'>
<img width="332px" src="images/upload.png" style="position:absolute; top:-120px; left:40px;"/>
<input type="file" name="photoimg" id="photoimg" style="padding: 0; margin: 0; display: none;" />
</form>
<div class="progress" style="display: none;">
<div class="bar"></div >
<div class="percent">0%</div>
</div>
<div id="status"></div>
<center>
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img width="300" src="images/uploading.png" alt="Laddar upp...."/>');
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
var progress = $('.progress');
$('#imageform').ajaxForm({
target: '#preview',
beforeSend: function() {
status.empty();
progress.show();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
//status.html(xhr.responseText);
}
}).submit();
});
});
</script>
<div id='preview' style="margin-top:40px;">
</div>
</center>
</div>
</div>
<div class="footer" id="footer">
<div id="top">
<img id="copyright" src="images/footer.png" alt="">
<a id="logo" href="http://www.simplyvisual.se" target="_blank">
<img width="150px" src="/images/SV.png" alt="Simply Visual">
</a>
</div>
<!--<div class="footer" id="footer"><img style="margin-top:1%; margin-left:0%" width="150" src="images/SV.png" /><img style="margin-top:0%;" src="images/footer.png" />--></div>
</body>
</html>
And the PHP:
<?php
session_start();
$session_id='1'; // User session id
$path = "upload/";
function url($url) {
$url = preg_replace('~[^\\pL0-9_]+~u', '-', $url);
$url = trim($url, "-");
$url = iconv("utf-8", "us-ascii//TRANSLIT", $url);
$url = strtolower($url);
$url = preg_replace('~[^-a-z0-9_]+~', '', $url);
return $url;
}
if(!empty($_POST) && !empty($_FILES['photoimg']) && $_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
$pi = pathinfo($name);
$txt = $pi['filename'];
$ext = $pi['extension'];
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
echo "Here's the link to your file: <a href='http://flopl.com/".$path.$actual_image_name."'>http://flopl.com/".$path.$actual_image_name."</a>";
}
} else {
echo "Something went wrong.";
exit;
}
?>
The progress-bar is showing, but I only get "Something went wrong" back. I've checked, the PHP.ini is set up correctly. The files are not uploading, and therefor also not giving me a URL back.
Could anyone figure out what's wrong?
Best regards,
primarypanda
I found at least 2 problems with your project.
Your host may allow upload big files but you need to check that file uploads are set or not in PHP.ini file. in most of the CPanels, they allow to make custom php.ini file settings, here you need to set max_file_uploads = 20M or so.
using isset() function may cause some problem, I use !empty() function instead because it checks whether the variable is set and not empty both. so you can do it in your code like...
if(!empty($_POST) && !empty($_FILES['photoimg']) && $_SERVER['REQUEST_METHOD'] == 'POST'){...}
You can notice that I have also checked that $_FILES['photoimg'] are also not empty, that means that the file is actually uploaded.
Best luck and Thank you

jQuery is not working in AJAX loaded div

This is my slider.php page in which content of ajax.php file is loaded through ajax.
var xmlhttp;
function showtemplate(temp)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState===4 && xmlhttp.status===200) {
var div = document.getElementById('contain');
div.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'ajax.php?section='+temp, true);
xmlhttp.send();
}
The content of ajax.php file is loading into the contain div.
This is my ajax.php file where I am using jquery to slideshow images.
<?php
$final=$_REQUEST['section'];
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js?ver=1.4.2"></script>
<script type="text/javascript">
$(function()
{
var currentIndex = 0,
var items = $('.container div'),
var itemAmt = items.length;
function cycleItems()
{
var item = $('.container div').eq(currentIndex);
items.hide();
item.css('display','inline-block');
}
var autoSlide = setInterval(function()
{
currentIndex += 1;
if (currentIndex > itemAmt - 1)
{
currentIndex = 0;
}
cycleItems();
}, 3000);
$('.next').click(function() {
clearInterval(autoSlide);
currentIndex += 1;
if (currentIndex > itemAmt - 1)
{
currentIndex = 0;
}
cycleItems();
});
$('.prev').click(function() {
clearInterval(autoSlide);
currentIndex -= 1;
if (currentIndex < 0) {
currentIndex = itemAmt - 1;
}
cycleItems();
});
});
</script>
<section class="demo">
<button class="next" id="next">Next</button>
<button class="prev" id="prev">Previous</button>
<div class="container">
<div style="display: inline-block;">
<img src='images/<?php echo $final;?>/image1.jpg'/>
</div>
<div>
<img src='images/<?php echo $final;?>/image2.jpg'/>
</div>
<div>
<img src='images/<?php echo $final;?>/image3.jpg'/>
</div>
<!--<span u="arrowleft" class="jssora12l" style="width: 41px; height: 50px; top: 110px; left: 2px;"> </span>
<span u="arrowright" class="jssora12r" style="width: 41px; height: 50px; top: 110px; right: 5px"> </span>-->
</div>
but when I clicked on next and previous button it doesn't work. Please help me out.
My code is working now. I simply request section and display it as thumbs without using jquery.
<?php
$final=$_REQUEST['section'];
include "slider/relatedcat.php";
?>
<div style="margin-bottom: 10px; font-size: 18px;font-family: 'Roboto Slab',serif;margin-top: -7px">Choose <?php echo ucwords($final);?> Card Template.</div>
<?php
for($i=1;$i<=count($template);$i++)
{
?>
<div id="thumb<?php echo $i;?>" onclick='showimage("template<?php echo $i; ?>","<?php echo $final;?>");' style='box-shadow: rgba(34, 25, 25, 0.4) 0px 1px 3px;border-radius: 15px;width: 150px !important;height: 150px !important;top: 0px;float:left;margin-right: 20px;margin-bottom:15px;overflow: hidden;transform: perspective(2000px);background: white;cursor: pointer;'>
<img alt='<?php echo ucwords($final);?>' u='image' src='images/<?php echo $final;?>/template<?php echo $i?>.jpg' style='width:100%;height:100%;' />
</div>
<?php
}
?>
If you want to use jquery in ajax loaded div then you have to redefine jquery function on success of ajax function like below code :
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState===4 && xmlhttp.status===200) {
var div = document.getElementById('contain2');
div.innerHTML = xmlhttp.responseText;
$('#resize').draggable({containment: '#main'}).resizable({maxWidth:350, maxHeight:333});
$('#msgvisible').draggable({containment: '#main'});
//alert(xmlhttp.responseText);
document.getElementById('stylepart').style.display="block";
}
}

run php mysql_query on onclick div

I need to put a mysql_query in the onClick event of a div. I tried this, but it does not work.
notifiche.php
while ($i < $result) {
$id_noti = mysql_result($res, $i, "id");
$msg=mysql_result($res,$i,"msg");
?>
<div class="box" align="left" style="color: #5c5c5c; padding:4px; border-bottom: 1px solid #c0c0c0; width: 170px !important; position:relative;z-index: auto;">
<div onClick="doSomething();" class="close_box" align="right"style="font-weight:bold; position:absolute;right:0; top:0; z-index:1;cursor:pointer;">
x
<input type="hidden" name="del_noti" value="<?echo $id_noti;?>">
</div>
<? echo $msg; ?>
</div>
<? $i++;
}
the script in the head of main page is
<script type="text/javascript">
function doSomething(){
$.post("del_notif.php");
return false;
}
</script>
and the del_notif.php
include 'files/config.php';
mysql_query("UPDATE notifiche SET a='delete' WHERE id='$_POST[del_noti]'");
You have to pass the argument to your doSomething function
<div onClick="doSomething(<?echo $id_noti;?>)"...>
and in your script
<script type="text/javascript">
function doSomething(id){
$.post("del_notif.php", {id: id});
return false;
}
</script>
and on the server
include 'files/config.php';
mysql_query("UPDATE notifiche SET a='delete' WHERE id=". (int) $_POST["id"]);

ajax get and insert with php and mysql

I have a page that has a form on it, when I click a button on the page it sends 3 variables to a layer(page_ref, template_ref, and box_id) via a javascript call.
Then with ajax I get some content from the mysql db with the variables and insert this into a text area on the layer.
The layer has a save button and when I click that I want to save the content of the textarea back to the db.
I can fill the textarea from the db no problem but am having problems pushing is back to the db.
The problem I have is sending the javascript variables to the ajax update page as they need to be passed to php varriables.
heres what I have
on the main page I call a javascript function
edit_box('show',i,'<? echo $page_ref; ?>','<? echo $template_ref; ?>');
in the layer I have this
<style type="text/css">
#popupbox
{
padding:0;
width: 99%;
height: auto;
margin: 0px auto;
position:absolute;
background: #FBFBF0;
border: solid #000000 2px;
z-index: 9000;
font-family: arial;
visibility: hidden;
}
</style>
<script type="text/javascript" src="http://js.nicedit.com/nicEdit-latest.js"></script>
<script>
//Browser Support Code
function get_edit_content(box_id,page_ref,template_ref)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("edit_content").innerHTML=xmlhttp.responseText;
var area1 = new nicEditor({fullPanel : true}).panelInstance("edit_content",{hasPanel : true});
}
}
var queryString = "?box_id=" + box_id + "&page_ref=" + page_ref + "&template_ref=" + template_ref;
xmlhttp.open("GET","get_content.php" + queryString,true);
xmlhttp.send();
}
$("#sub").click( function()
{
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(info)
{
$("#result").html(info);
});
clearInput();
});
$("#myForm").submit( function()
{
return false;
});
function clearInput()
{
$("#myForm :input").each( function()
{
$(this).val('');
});
}
function edit_box(showhide,box_id,page_ref,template_ref)
{
if(showhide == "show")
{
get_edit_content(box_id,page_ref,template_ref);
document.getElementById('popupbox').style.visibility="visible";
}
else if(showhide == "hide")
{
document.getElementById('popupbox').style.visibility="hidden";
}
}
</script>
<div id="popupbox">
<form id="myForm" action="update_textarea.php" method="post">
<input type="hidden" name="page_ref" value="<? echo $page_ref; ?>" />
<input type="hidden" name="template_ref" value="<? echo $template_ref; ?>" />
<input type="hidden" name="box_id" value="<? echo $box_id; ?>" />
<textarea name="edit_content" id="edit_content" style="width: 500px; height:500px;"></textarea>
<center>close</center>
<button id="sub">Save</button>
</form>
</div>
then I have get_contents page
<?php
include("connect.php");
$page_ref = $_GET['page_ref'];
$template_ref = $_GET['template_ref'];
$box_id = $_GET['box_id'];
$sql = "SELECT * FROM site_content WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
echo "<p>".$row['content']."</p>";
}
?>
and finally the update_textarea page
<?
include("connect.php");
$page_ref = $_POST['page_ref'];
$template_ref = $_POST['template_ref'];
$box_id = $_POST['box_id'];
$edit_content = $_POST['edit_content'];
if(mysql_query("UPADTE site_content SET content='$edit_content' WHERE page_ref='$page_ref' AND template_ref='$template_ref' AND box_id='$box_id' AND box_type='text'"))
{
echo "Successfully Inserted";
}
else
{
echo "Insertion Failed";
}
?>
I realised that i needed to set the values of the hidden inputs in the ajax call after
document.getElementById("edit_content").innerHTML=xmlhttp.responseText;
by adding
document.getElementById("box_id").value = box_id;
etc

How to insert iFrame/PHP with ajax?

I am trying to include a Facebook like button iFrame that has PHP in it:
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo $row['id']; ?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
when the site loads this, it displays as in a list:
<ul class="recent-list">
<?php
require("inc/connect.php");
$result = mysql_query("SELECT * FROM entries ORDER BY id DESC LIMIT 0, 20", $link);
while($row = mysql_fetch_array($result)){ ?>
<li id="qoute-<?php echo $row['id']; ?>" class="quote-wrap group">
<span>
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo $row['id']; ?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
</span>
<div class="quote">
<p>
<?php echo htmlentities($row['quote']); ?>
</p>
</div><!-- /.quote -->
</li>
<?php } ?>
</ul>
But when someone click a button that fetches more list-items, the iFrame should be included...
function getQuotes(start, limit) {
//Clear the recent list element
//$(".recent-list").html("");
var recent = $(".recent-list");
$(".recent-list li").animate({opacity: 0.1} , 800).hide(500);
$.ajax({
url: "quotes.php?start=" + start + "&limit=" + limit,
success: function (data) {
data = jQuery.parseJSON(data)
console.log("success");
//Data should now be a javascript array of objects.
for (i = 0; i < data.length; i++) {
var newElem = jQuery("<li></li>").attr('id', data[i].id).addClass('quote-wrap-group');
newElem.append("<div class='quote'><p>" + data[i].quote + "</p></div>");
$(".recent-list").append(newElem);
}
}
});
}
var currentIndex = 0;
$("#more").click(function () {
getQuotes(currentIndex, 20);
currentIndex += 10;
});
When I try to include the iframe in the js above, nothing happens. No error, nothing is returned...
quotes.php:
$start = $_GET['start'];
$limit = $_GET['limit'];
$sql = "SELECT * FROM entries ORDER BY id DESC LIMIT ".$start.", ".$limit;
$result = mysql_query($sql, $link) or die("Error in query: ".mysql_error());
$data = array();
while($row = mysql_fetch_array($result)) {
array_push($data, $row);
}
echo(json_encode($data));
live version. Click "Get more". The quotes appear, but no like button.
http://kdevs.site40.net/#more
you didn't add the iframe tags while building the <li> it the success function
all you did was adding (for each row):
<li id="54" class="quote-wrap-group">
<div class="quote">
<p>fdggfdgdgdgfdg</p>
</div>
</li>
a better approach will be to make the whole list items on server side, and echo it, and then append the html that you received in the success to the existing list
for example:
your php will look like this:
$data = getData();//Get the data from the database here;
foreach($data as $row):
?>
<li id="qoute-<?php echo $row["id"];?>" class="quote-wrap group">
<span>
<iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo row["id"];?>&send=false&layout=button_count" style="border: medium none; overflow: hidden; width: 115px; height: 21px;" allowtransparency="true" frameborder="0" scrolling="no"></iframe>
</span>
<div class="quote"><p><?php echo $row["quote"];?></p></div>
</li>
<?php endforeach; ?>
your javascript function will be:
function getQuotes(start, limit){
$.ajax({
url:"quotes.php?start=" + start + "&limit=" + limit,
dataType: "html",
success: function(response){
$("ul.recent-list").append(response);
}
});
}
this of course trying to show the principle, and not necessarily be the exact code you need to write. You need to add the other functionality (like hiding the previous quotes etc...)

Categories