I'm having a simple select statement using php-mysql and I have this script to change text with another.
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("text2");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<div id=deletesuccess > text1 </div>
Trying to display data from table using php-mysql and jquery above script but it's displaying only the last row the loop is not working
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html("<?php echo $row['desc']; ?>");
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
<?php
}
But couldn't use it with the above PHP code to display data one by one.
You can do this easily by using jQuery ajax.
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
url: 'getData.php',
dataType: 'json',
type: 'POST',
success: function(data) {
$('#deletesuccess').delay(500).fadeOut(function(){
$.each(data,function(key, value){
$('#deletesuccess').html(value);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
}
});
});
</script>
Now in getData.php page you need to do query and echo json_encode data. That means the getData.php file should contain the following code:
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
$json = '';
while($row = mysql_fetch_array($getTextR)){
$json .= $row['desc'];
}
echo json_encode($json);
?>
Attention, you have not a clear difference between php and javascript code execution. The php code will make an echo of that javascript code, and after php has finish execution(on document ready) the javascript code will be executed at istant, so the last echo of javascript will have effect in the execution. try to separate the codes.
The problem is that you overwrite your JavaScript each time the loop runs. Instead you should make it like this:
<script type="text/javascript">
var php_results = '';
</script>
<?php
$getTextQ = "select * from text";
$getTextR = mysql_query($getTextQ);
while($row = mysql_fetch_array($getTextR)){
?>
<script type="text/javascript">
php_results += "<?php echo $row['desc']; ?> | ";
</script>
<?php
}
?>
<script type="text/javascript">
$(document).ready( function() {
$('#deletesuccess').delay(500).fadeOut(function(){
$('#deletesuccess').html(php_results);
$('#deletesuccess').delay(500).fadeIn("slow");
});
});
</script>
Of course this would have to be cleaned up to make it pretty, but it should work. I added the pipe as a separator between the different descriptions from the database.
Related
I'm working on a notification message i want to load new message from a page call check_new-reply.php in every 10 second using Ajax and Jquery but my code is not showing anything i don't know what the error is please can someone help me out?
<script>
$(document).ready(function(){
$(function(){
var timer = 10;
var test = "";
function inTime(){
setTimeOut(inTime, 1000);
$("#timer-u").html("Time refreshing"+timer);
if(timer == 8){
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
})
timer = 11;
clearTimeout(inTime);
}
timer--;
}
inTime();
});
});
</script>
Here is PHP
<?php include($root . '_inc/Initialization.php');?>
<?php require_once("_inc/dbcontroller.php"); $db_handle = new DBController();?>
<?php
$users = $_SESSION['username'];
$newquery = "SELECT * FROM blog_post
INNER JOIN replys
ON blog_post.UserName = '$users'
WHERE replys.read = 0
ORDER BY rtime";
$newhisory = mysql_query($newquery);
while($newrow = mysql_fetch_array($newhisory)){
echo '<div class="fnot">'.htmlentities($newrow['blog_title']).'';
echo '<span class="ttcredit"><font color="darkgreen">94</font> </span> <a class="reqttag reqttag2" href="#">No</a> ';
echo '</div>';
echo '<input type="hidden" id="unr" name="unr" value="'.$newrow['BID'].'"/>';
}
?>
If you just want to call it every 10 seconds, use 10000 milliseconds in the setTimeOut . Also, it is best to call again the function only when the previous Ajax call is done:
$(document).ready(function(){
$(function(){
var test = "";
function inTime(){
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
setTimeout(inTime, 10000);
});
}
inTime();
});
});
To call any function with some intervals you will have to use
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 10000);
});
function myAjaxCall() {
alert("Hi");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>
window.setInterval will call your function on every 3 seconds with above code, and will generate an alert message,
what you have to do is set your ajax code in a function and use above method, change 3000 to 10000 and your ajax call will defiantly work with every 10 seconds,
This is the code which will call our javascript function on every 10 seconds,
just copy it and check it, you will get an idea, also i have included the jquery as we have discussed.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
</body>
<script>
$(document).ready(function(){
window.setInterval(function(){
myAjaxCall();
}, 3000);
});
function myAjaxCall() {
alert("Call your Ajax here");
$("#message-u").html("Loading....");
$.POST("check_new_reply.php",{testing:test}, function(data){
$("#message-u").html(data);
});
}
</script>
I try to put data into js file, through "jquery $.post" and "fwrite php", and get back that data into array. How to do that?
here's the html:
<!doctype html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
});
var arr = [$.getScript("talk.js")];
alert(arr[0]);
}
})
})
</script>
</head>
<body>
<input type="text" id="nameput" />
<button id="button">send AJAX req</button>
</body>
</html>
Here's the php, I name it "processing.php" :
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,'"'.$text.'",');
fclose($file);
?>
And "talk.js" will look like this :
"a","b","c",
Why I can't put that data from "talk.js" into array at " var arr = [$.getScript("talk.js")]; " as in html file above?
Here's what I try after I read comments. I change the scirpt into this:
<script>
$(document).ready(function() {
$("#button").click(function() {
if ($("#nameput").val() != "") {
$.post("processing.php", {
putname: $("#nameput").val()
}, function() {
$.getScript("talk.js", function(data) {
var arr = data.split(",");
alert(arr[0]);
})
})
}
})
})
</script>
And php into this:
<?php
$file = fopen("talk.js","a");
$text = $_POST["putname"];
fwrite($file,$text);
fclose($file);
?>
But it still not work?
here's a simplified version of your button click to help you out:
$("#button").click(function() {
$.getScript("talk.js", function(data){
var arr = data.split(',');
alert(arr[0]);
});
});
If you log the output of $.getScript you will easily see why what you're trying doesn't work.
Using this method you will get the data returned from the script ("a","b","c"), but you'll need to split it on a comma into an array. Then you can reference whichever part of the array you want.
Note that the each element of the array will have quotations around them.
I need help with putting this $id value into the javascript below
PHP:
<?php
$id = NULL;
$username = 'YouTube';
$xml = simplexml_load_file(sprintf('http://gdata.youtube.com/feeds/base/users/%s/uploads?alt=rss&v=2&orderby=published', $username));
if ( ! empty($xml->channel->item[0]->link) )
{
parse_str(parse_url($xml->channel->item[0]->link, PHP_URL_QUERY), $url_query);
if ( ! empty($url_query['v']) )
$id = $url_query['v'];
}
echo $id; // Outputs the video ID.
?>
JS: Need $id value ---> 'I need the value to go right here'
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: 'I need the value to go right here', start: 3 };
$('#video1').tubular(options);
});
</script>
Do something like this....
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: '<?php echo $id?>', start: 3 };
$('#video1').tubular(options);
});
</script>
But make sure, you are including this script in php file.
Other solution could be to use html hidden variable, and access that value using js.
by the use of
<script type="text/javascript">
....
</script>
I understand you're using javascript inside of your view! then why not just do this
var options = { videoId: '<?php echo $id; ?>', start: 3 };
Use
<script type="text/javascript">
var id= '<?= $id; ?>';
</script>
now you can use the id variable in your javascript
<script type="text/javascript">
$('document').ready(function() {
var options = { videoId: id, start: 3 }; // id variable which is filled by $ib variable of php
$('#video1').tubular(options);
});
</script>
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);
});
});
I got a page with a form to fill it with custormers info. I got previous custormers data stored in a php array. With a dropdownlist users can fill the form with my stored data.
what i have is a jquery function that triggers when the value changes and inside that function i whould like to update the form values with my stored data (in my php array).
Problem is that i dont know how to pass my php array to the jquery function, any idea ??
this is how i fill the array:
$contador_acompanantes = 0;
foreach ($acompanantes->Persona as $acomp)
{
$numero = $acomp->Numero;
$apellidos = $acomp->Apellidos;
$nombre = $acomp->Nombre;
$ACOMPANANTES[$contador_acompanantes] = $ficha_acomp;
$contador_acompanantes++;
}
got my select object:
<select name="acompanante_anterior" id="acompanante_anterior">
<option value="1" selected>AcompaƱante</option>
<option value="2">acompanante1</option>
<option value="2">acompanante2</option>
</select>
and this is my code for the jquery function (it is in the same .php page)
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
});
});
</script>
var arrayFromPHP = <?php echo json_encode($phpArray); ?>;
$.each(arrayFromPHP, function (i, elem) {
// do your stuff
});
You'll likely want to use json_encode, embed the JSON in the page, and parse it with JSON-js. Using this method, you should be aware of escaping </script>, quotes, and other entities. Also, standard security concerns apply. Demo here: http://jsfiddle.net/imsky/fjEgj/
HTML:
<select><option>---</option><option>Hello</option><option>World</option></select>
<script type="text/javascript">
var encoded_json_from_php = '{"Hello":[1,2,3], "World":[4,5,6]}';
var json = JSON.parse(encoded_json_from_php);
</script>
jQuery:
$(function() {
$("select").change(function() {
$(this).unbind("change");
var val = json[$(this).val()];
var select = $(this);
$(this).empty();
$.each(val, function(i, v) {
select.append("<option>" + v + "</option>");
});
});
});
try this one..
<script type="text/javascript">
$(document).ready(function()
{
$('#acompanante_anterior').on('change', function()
{
my_array = new Array();
<?php foreach($array as $key->val)?>
my_array['<?php echo $key?>'] = '<?php echo $val;?>';
<?php endif; ?>
});
});
</script>