Convert PHP variable to JQuery - javascript

Im trying to update the src from the audio tag if i click on a button.
So i need to translate the $muziek variable to Jquery
View:
<?php
foreach ($muziek as $ms)
{
if ($ms->id == 2) {
echo '<audio id="player" controls src="data:audio/mpeg;base64,' . base64_encode($ms->audio) . '">';
echo '</audio>';
}
}
foreach ($muziek as $ms)
{
echo '<br>';
echo '<input id="'.$ms->id.'" type="button" value="' . $ms->naam . '" class = "btn btn-login login-formcontrol"/>';
}
?>
</div>
<script>
$("input").click(function () {
var test = $(this).attr("id");
console.log(test);
//Here needs to be the foreach muziek
});
</script>
Muziek variable:
This is how i fill the music variable
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
return $muziek;
}
Does someone has an idea or show me how this can be done?

I spent sometime trying to figure out what you want and from what i understood you want to return an array of all muzieks returned to your js to do whatever you wanna do with it, which you can simply get with a simple ajax request:
$.get( "base_url/your_controller/getAllMuziek" )
.done(function( muziek ) {
//Here needs to be the foreach muziek
$.each(muziek, function( index, value ) {
// whatever
});
});
with a simple modification to your method getAllMuziek:
function getAllMuziek()
{
$query = $this->db->get('muziek');
$muziek = $query->result();
header('Content-Type: application/json');
echo json_encode($muziek);
}
now when you make you ajax call you will get your result.

Convert $muziek into javascript array using json_encode
<script>
var myArray = <?php echo json_encode($muziek); ?>;
</script>

Related

Using variable on php to create another variable in JS

I'm having a hard time getting the value of a specific variable in php to use in js. This is my code in php:
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
}
?>
I want to get the value of this ($result['status']) and pass it on the variable pos in js. This is my js code:
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
var pos = $('PHP VARIABLE HERE').val();
alert(pos);
}
Thanks for your help.
The easiest way is to output it to javascript directly:
?>
<script type="text/javascript">
window.MY_PHP_VAR = <?php echo json_encode($myPhpVar); ?>;
</script>
...
window.MY_PHP_VAR now contains your php variable
if your javascript code is on same page where the result is comming then you can use this
var pos = `<?php echo $result['status'] ?>`;
var pos = `<?= $result['status'] ?>`;
===============
// refresh.php
===============
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
echo "<script> alert('". $result['status'] ."'); </script>";
/* If the $result['status'] is 'success' the above line will be converted to:
echo "<script> alert('success'); </script>";
*/
}
?>
so, every time the refresh.php loads, the script is going to get executed.
However, I suggest you to assign a id or class attribute to your h4 where you are echoing your status and access the value using the selectors in the javascript.
you could try giving an id or class to the status.
then in JavaScript you could then get the value of the id or class.
PHP
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<h4> <span class="status">' . $result['status'] . '</span></h4>';
}
?>
JavaScript
var oldStatus = '';
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
// note that since we used a class, you will get the value of the first element only.
var pos = $('.status').text(); // use .text() instead of .val()
if (pos.toLowerCase() == 'out' && pos != oldStatus){
oldStatus = pos;
alert(pos);
}
}

Yii - ajax call on mouseover and get Data

Index File
<h4>Dates</h4>
<?php
foreach($dates as $date){
echo TbHtml::ajaxButton(date("D, d M" ,strtotime($date->date)),
array(
'matches/countryVenue'
),
array(
// 'dataType'=>'json',
'type'=>'POST',
'data'=>array('id'=>$date->id),
'success'=>'js: function(data) {
alert(data);
}',
'failure'=>'js: function(data) {
alert("error");
}',
),
array(
"id"=>$date->id,
"onmouseover"=>"date(this.id);"
)
);
echo "<br>";
}
?>
</div>
JS Code
<script>
function date(x){
//alert("Date " + x);
};
</script>
Matches Controller File :
public function actionCountryVenue(){
if(isset($_POST['id'])){
$id = $_POST['id'];
}
// echo $id;
$criteria = new CDbCriteria();
$criteria->select = "*";
$criteria->condition = "DATE = ".$id;
$countryVenue = Matches::model()->findAll($criteria);
if(!empty($countryVenue)){
echo CJSON::encode(array('countryVenue'=>$countryVenue));
}
}
My Question
I need help from someone to give an exact idea of callback and ajax.
Moreover what I plan to do is onmouseover of the ajaxButton, I want to make an ajax call sending the ID of the button to the controller and return json data from the controller and convert into php array.
Edit Info
I have managed to send the data from the controller to the index file but can not render json data in php.

js can not call function name right

I want to make one javascript function, but I cannot call my function name right when i click on it(show_more_in_month_0/1/2).
this is my code
$i = 0;
foreach ($data as $row){
echo '<td><span class="glyphicon-plus show_more_in_mont_'.$i.'"></span><span class="glyphicon-minus_'.$i.'"></span></td>';
echo '<td>';
echo $row[0];
echo '</td><td>;
echo $row[1];
echo '</td><td>';
echo $row[2];
echo '</td><tr>';
$i ++;
}
And this is my script, i just want alert my class name after i call right function name
$(document).ready(function() {
$(".show_more_in_mont_'.$i.'.").click(function(){
alert(show_more_in_mont_'.$i.');
});
});
You are doing it wrong -- $i i suppose its your PHP variable ? well you shouldnt have those in your JS..
Just add as javascript one global class such "show-more-container" and use it to show whatever you want to show
$( document ).ready(function() {
$(".show-more-container").click( function() {
var elementId = $(this).data('id');
alert ('show_more_in_mont_'+elementId);
});
});
Now your html should look like
<div data-id="<?= $i ?>" class="show-more-container">
</div>
Hope this make sense to you :)
EDIT:
If you want to go far -- and call that as a function then do as follow:
window['my_fn_name_as_string'+appendId]()
for this to work the function should be on a Global scope -- on Body or Head and not inside Jquery! if you want to add it to jQuery then make sure you use:
$.function() {
window.my_fn_name_as_string_div = function() { }
}
EXAMPLE:
http://jsfiddle.net/7d23y99b/1/

<input> calling a PHP function using AJAX

I am trying to call a PHP function using AJAX to check if the pressed button is the right button.
But I can't seem to figure it out.
I am using this as <input> code :
<?php
$i=0;
while ($i<4){
?>
<input style="background-color: <?php echo $buttonColors[$i]; ?>" onclick="echoHello(<?php echo $i?>)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php $i=$i+1; } ?>
and I'm trying to call a PHP function when the button is clicked. I tried this :
<script>
function echoHello()
{
alert("<?php hello(); ?>");
}
</script>
<?php
function hello() {
echo "Hello World";
}
?>
This worked so I tried to change this to :
<script>
function echoHello(num)
{
alert("<?php hello(num); ?>");
}
</script>
<?php
function hello($num) {
if($num == 1) {
echo "Correct button!!!";
} else {
echo "WRONG BUTTON";
}
?>
But this didn't seem to work. What am I doing wrong?
I think you have quite some thing mixed up here.
I would suggest just writing out the buttons, and pass the buttons value to the javascript:
<?php
$i=0;
while ($i<4){
?>
<input onclick="echoHello(this.value)" type="submit" value="<?php echo $buttonName[$i]; ?>">
<?php
$i=$i+1;
} ?>
and then in your javascript (after adding all the jQuery goodness):
function echoHello(btnValue) {
$.ajax({
type: "POST",
url: "formhandler.php",
data: { buttonValue: btnValue }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
The javascript above will send the button value to your 'formhandler.php' page, using AJAX.
In the 'formhandler.php', you could then check what the value of $_POST["buttonValue"] is.
Using your setup, together with jQuery, PHP and JSON, it could be something like this:
function echoHello(btnValue) {
$.getJSON('page.php', {
choice: btnValue
})
.done(function(data) {
// based on $_GET["choice"], your PHP could render some JSON like:
// {"background":"image.jpg","fields":["newValue1", "newValue2", "newValue3"]}
// clear the current html
$("#form").html('');
// load a new background
$('body').css({'background-image':data.background})
// set up the new fields:
$.each(data.fields, function( i, item ) {
$("#form").append('<input type="text" value="' + item + '"/>');
});
});
}
This is just a sample, to give you an idea! It's untested also ;)

Ajax script loading/Displaying only once

This script displaying the dynamic content for once thereafter its not working
Here is the code:
$(document).ready(function(){
$('.getmore').on('click',function(){
var last_id = $(this).attr('id');
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/getmore.php',
data: 'last_id='+last_id,
beforeSend: function(){
$('.getmore').html('<img src="../images/loader.gif" alt="Loading..." />');
},
success: function(data){
$('.getmore').remove();
$('#comments').append(data);
}
});
});
});
Here is the complete php code:
<?php
mysql_connect('localhost','root','') or die('Error... Couldnt connect..');
mysql_select_db('mydb') or die('Error... Couldnt select the Db..');
$records = mysql_query(' SELECT * FROM `compare_post_comments` WHERE `post_id`=37 limit 5 ');
if(mysql_num_rows($records)){
echo '<div id="ajax_comment">';
echo '<ul id="comments">';
while($data = #mysql_fetch_array($records) ){
echo '<li>'.$data['comments'].'</li>';
$last_record = $data['sno'];
}
echo '<li class="getmore" id="'.$last_record.'">Get More</li>';
echo '</ul>';
echo "<span id='cmmnts'></span>";
echo '</div>';
}
?>
getmore.php code
<?php
if( ( isset($_POST['last_id'])!=null ) && $_POST['last_id']!="" ){
$last_id = $_POST['last_id'];
//echo "::".$last_id;
$qry = " SELECT * FROM `compare_post_comments` WHERE `post_id`=37 and sno > ".$last_id." limit 5 ";
//echo "::".$qry;
$comments = mysql_query($qry) or die('Error..');
if( mysql_num_rows($comments) ){
while( $data = mysql_fetch_array($comments) ){
echo "<li>".$data['comments']."</li>";
$last_id=$data['sno'];
}
echo "<li class='getmore' id='".$last_id."'>Get More</li>";
}else{
echo "<li class='nomore'>No More</li>";
}
}else{
echo "<li class='nomore'>No More</li>";
}
?>
ajax call working for once, thereafter its not clickable.
I dont have much knowledge about ajax and javascript, explanation is appreciated.
Try the deferred syntax of on instead:
$(document).on('click', '.getmore', function...
This will survive DOM changes. This answer presumes that your loaded data contains an object with class="getmore", as you are removing it from the DOM on success. If not you need to remove the remove as suggested by NewInTheBusiness, but probably replace it with empty() instead to remove the loading progress.
Note I have recently found problems with the version of on that only takes the event and function. In jQuery 1.10.3 it seems to not be firing when it should.
It's because you remove the getmore class after success.
Remove this line of code:
$('.getmore').remove();
Check your firebug console for any error
Remove this line $('.getmore').remove();
Delegate the click event to the element's static parent or to the document.
Try,
$(document).on("click",'.getmore', function( event ) {
});
Just try live or bind in-place of "on" :
$('.getmore').live('click',function(){
}
or
$('.getmore').bind('click',function(){
}

Categories