jquery load not reading string as variable (php hybrid) - php

I'm writing out a javascript string to be parsed by jquery - it works fine as an alert but not in the jquery load function
PHP:
$imgData = 'http://www.domain.com/_image.php/_MG_4156.jpg' ;
which is a php script to generate a thumbnail on the fly
<script type='text/javascript' language='javascript' charset='utf-8'>
<!--
var chart1img_".$i_gall." = new Image();
var imgData = '".$imgData."';
$(chart1img_".$i_gall.").load(function () {
$(this).hide();
$('#thumb_img_div_".$i_gall."').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
//}).attr('src', 'http://www.domain.com/_image.php/_MG_4156.jpg');
//-->
</script>";
If I hardcore the string it works.
If I use it as the imgData variable it fails, but the alert works using imgData
Tried string combos all ways. Defeated. Any ideas?

you need add php tags in your code
<script type='text/javascript' language='javascript' charset='utf-8'>
<!--
var chart1img_"<?php echo $i_gall;?>" = new Image();
var imgData = '<?php echo $imgData?>';
$("chart1img_<?php echo $i_gall;?>").load(function () {
$(this).hide();
$('#thumb_img_div_<?php echo $i_gall;?>').removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
//}).attr('src', 'http://clients.flatearth.co.uk/benhopper/project/_image.php/_MG_4156.jpg');
//-->
</script>";

Using closures will give you a cleaner code.
Also, use json_encode to send values to JavaScript.
For example,
echo "
<script type='text/javascript'>
(function() {
var image = new Image(),
imgData = " . json_encode($imgData) . ",
i_gall = " . json_encode($i_gall) . ";
$(image).load(function () {
$(this).hide();
$('#thumb_img_div_' + i_gall).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
})();
</script>";
This minimizes the number of embedded PHP value be defining them as JavaScript variables.
You can also put them in functions:
<script type='text/javascript'>
function loadAndShowImage(imgData, i_gall) {
var image = new Image()
$(image).load(function () {
$(this).hide();
$('#thumb_img_div_' + i_gall).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
// notify the user that the image could not be loaded
alert(imgData);
}).attr('src', imgData);
}
</script>
and then output just the dynamic parts:
echo "
<script type='text/javascript'>
loadAndShowImage(" . json_encode($imgData) . ", " . json_encode($i_gall) . ");
</script>";

Not sure what the problem is other than it's one of the characters in the full variable?:
var imgData = 'http://www.domain.com/_image.php/".$r_gall['image']."?width=145&height=205&cropratio=145:205&image=/images_cms/".$r_gall['image']."';
But I kept as much of the string in JS and just replaced the dynamic parts with PHP

Related

Passing sql string variable into javascript function

I am trying to pass a string from a query into a javascript function.
An integer will pass into the function but string will not.
echo "<a href='#' onclick='delete_game({$title});'
class='btn'>Delete</a>";
<script type='text/javascript'>
function delete_game(title){
var answer = confirm('Really?');
if(answer){
window.location = 'delete.php?id=' + title;
}
}
</script>
I expected the javascript function to be executed, but instead nothing happens.
Why don't you use ajax for this? As mentioned in comments mix PHP/JS isn't good.
In your HTML, you can do something like
I'm assuming that you are using Blade.
Delete Game
Then in your javascript, you do this using jQuery:
function deleteGame(title){
var answer = confirm('Really?');
if(answer){
$.ajax({
url : "your-php-file.php",
type : 'post',
data : {
title : title
}
})
.done(function(msg){
$("#result").html(msg);
})
.fail(function(error){
console.log(error);
});
}
}
In your PHP you process receiving the data from post $_POST
$title = $_POST['title'];
You can understand better the Ajax function of jQuery here.
A few things:
I would change window.location to window.location.href
Change your echo to:
echo "Delete";
Check if $title is set
var_dump($title);
If you'd like to make it a bit cleaner and are prepared to use jQuery:
Delete
<script type='text/javascript'>
$(document).on('click', '#delete', function () {
var title = $(this).data('title');
var answer = confirm('Really?');
if (answer){
window.location.href = 'delete.php?id=' + title;
}
});
</script>

How can i add this script in php

am trying to find out how to add this script to my php file , as i try echo it ,its not working.
am sure there is a way to add this, its my first time adding these scripts to php file ,maybe il learn something today and remmeber it thanks.
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000);
and the html div this is not needed to add to php as i have own div in php file
<div id="divID"></div>
Close the php tags, open a script tag, paste your script there, close your script tag, re-open your php tag. ;)
I recommend putting your js at the end of the file tho.
<?php
// your php here
?>
<div id="divID"></div>
<?php
// some php if you want to
?>
<script type="text/javascript">
//Your javascript here
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000);
</script>
Normally, you won't put javascript in your php file... But if there's no other solution:
<?php
echo"
<script type=\"text/javascript\">
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000);
</script>
";
In PHP pass js code into variable
<?php
$script = "<script type='text/javascript'>
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000); </script>";
?>
In HTML where you want to show/add
<html>
<head>
<?php echo $script; ?>
</head>
</html>
You can put it like this or you can put <script> part in the head of your page or in js file and include in page.
<?php
// code
?>
<script>
$( document ).ready(function() {
var counter = 1;
var auto_refresh = setInterval(
function () {
var newcontent= 'Refresh nr:'+counter;
$('#divID').html(newcontent);
counter++;
}, 5000);
});
</script>
<div id="divID"></div>
Note: you also need jquery. If you don't use one you can include this in your page also
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
I just tested it and it's working perfectly. Currently my counter is
Refresh nr:51

Preload audio and apply css during playback

I am looking to create sound buttons.
Have used the answer here:
Buttons click Sounds
and implemented it so that the buttons are divs and created dynamically from a MySQL DB.
Does anyone know how to preload that list of sounds on page load?
Also, I want to apply a CSS class to the div when clicked and then when the audio finishes, want it to switch back to the original CSS class.
This is what I have tried. The sounds play correctly but the onended fuction does not fire.
<script type='text/javascript'>
$(window).load(function(){
var baseUrl = "http://[URL HERE]";
var audio = [<?php echo $audiostring; ?>];
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = new Audio(baseUrl + audio[i-1]).play();
mySound.onended = function() {
alert("The audio has ended");};
});
});
</script>
If you are using HTML5 audio you can do something like the following:
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
Edit:
Try changing the way you create the audio tag, as referenced here.
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = $(document.createElement('audio'));
mySound.src = baseUrl + audio[i-1];
mySound.play();
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
});
<audio> and new Audio() should be the same but it doesn't look
like that is the case in practice. Whenever I need to create an audio
object in JavaScript I actually just create an element like
this:
The ended event is created based on .currentTime attribute. event-media-ended
the canplaythrough event was used to knowing when the browser has finished downloading the audio file and we can play
code complete use closest
<style type="text/css">
body{background: #aaa;color:#fff;}
div
{
width: 100px;
height: 100px;
background: #dda;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >
</div>
<div >
</div>
<div >
</div>
<script type="text/javascript">
$(window).load(function(){
var audioFiles = [
"http://www.soundjay.com/button/beep-01a.mp3",
"http://www.soundjay.com/button/beep-02.mp3",
"http://www.soundjay.com/button/beep-03.mp3",
"http://www.soundjay.com/button/beep-05.mp3"
];
function Preload(url) {
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.src = url;
}
var loaded = 0;
function loadedAudio() {
// this will be called every time an audio file is loaded
// we keep track of the loaded files vs the requested files
loaded++;
if (loaded == audioFiles.length){
// all have loaded
init();
}
}
var player = document.createElement('audio');
function playAudio(index) {
player.src = audioFiles[index];
player.play();
}
function init() {
$('div').click(function(event) {
$(this).css('background', 'blue');
playAudio(Math.floor(Math.random()*audioFiles.length));
player.addEventListener("ended", function(){
player.currentTime = 0;
$(event.target).closest('div').css('background', '#dda');
});
});
}
// We begin to upload files array
for (var i in audioFiles) {
Preload(audioFiles[i]);
}
});
</script>

How to transfer the image data uploaded using jquery to php?

I have a code here
<h2>Click blue button</h2>
<button id="open_btn" class="btn btn-primary">Open dialog</button>
<div id="output"></div>
<script src="src/bootstrap.fd.js"></script>
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
its a drag and drop upload using jquery and boostrap layout from http://www.jqueryscript.net/demo/Drag-Drop-File-Upload-Dialog-with-jQuery-Bootstrap. Its working, but the problem is, I don't know how to pass the data uploaded to php for processing and put the file into the server.
Anyone can help me with this?
you can try using ajax. Setup ajax in your project from tons of tutorials available on the net.
After that in your javascript function i suppose you want to pass variable text to php. So here's what you can do when you get a little hang about ajax by going through the tutorials
<script type="text/javascript">
$("#open_btn").click(function() {
$.FileDialog({multiple: true}).on('files.bs.filedialog', function(ev) {
var files = ev.files;
var text = "";
files.forEach(function(f) {
text += f.name + "<br/>";
});
$.ajax({
url: "'your php function name'?name ="+text,
success: function( data ) {
if(data == "retn value") { //return value of the php function
// alert("");
} else {
}
}
});
$("#output").html(text);
}).on('cancel.bs.filedialog', function(ev) {
$("#output").html("Cancelled!");
});
});
</script>
create a function in php which will take your data as an argument.
hope this helps.

Is it possible to insert php variables into your js code? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
passing variables from php to javascript
I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row.
Basically:
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>
The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!
Yes, if you include the <script> section in your PHP code, you can do something similar to the following:
<script>
var foo = <?php echo $foo; ?>;
</script>
In your case, you would be looking into the following code structure:
<script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>
The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of $cid with the one you have included.
Enjoy and good luck!
EDIT:
<script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>
You can do it like this :
$(location).attr('href','<?php echo $cid ?>');
The javascript code doesn't know it comes from php, it appears as a constant (a literal) for it.
Yes it is possible. All you have to do is put your <?PHP echo $cid; ?> in where you need it
<script>
$(function ()
{
$('#rc_desc<?PHP echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?<?PHP echo $cid; ?>');
});
});
This is possible because by the time the scrip is put into the page the cid has already been replaced by the string on the server. Since PHP is server driven, before it spits back the html/script it will be just like you put it in yourself.
There is almost no way to actually communicate PHP and JavaScript. However, the best and simplest way is to set the ID within an attribute. The new HTML5 data attributes would be perfect.
For example, have a anchor tag with
<span data-id="22">some event</a>
and then:
$(this).attr('href','student.php?'+$(this).attr('data-id'));
Or just use
<?php echo $id; ?>
if it is not external JS file
Try this code
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
$(location).attr('href','student.php?' + $(this).attr("data-id"));
// if you want to redirect the page do this
// window.location.href = 'student.php?' + $(this).attr("data-id");
});
});
</script>
I think you block should be :
<script>
$(function ()
{
<?php foreach($courses as $cid=>cinfo) : ?>
$('#rc_desc<?php echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid; ?>').click(function ()
{
$(location).attr('href','student.php?<?php echo $cid; ?>');
});
";?>
<?php endforeach; ?>
});
</script>
UPDATE
But you don't really need to do this, you have
"<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
You can try this
$(function (){
$('.rc_desc').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
attrId = $(this).attr("data-id");
$(location).attr('href','student.php?'+id);
});
});

Categories