I am writing some jquery to call an ajax script every 2 seconds to get the result and update the page. I am mostly a backend programmer and could use some help on this.
This is the code I have now:
<script language="javascript">
function downloadProgress(id) {
$("#" + id + "").load("index.php?_controller=download&_action=getDownloadProgressAjax",
{
downloadId: id
}
);
setTimeout(downloadProgress(id), 2000);
}
</script>
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>">
<script language="javascript">
downloadProgress(<?php echo $dl["download_id"]; ?>);
</script>
</div>
<?php
}
?>
This does not work. What am I doing wrong or would you suggest another approach?
Thanks
I think that you are confusing your PHP script by giving it both query string variables (sent as GET) and data (which is probably getting sent as POST). Try this:
$("#" + id).load("index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id }
since you are using jquery, you can use the $.ajax function when the page is ready.
$(function () {
function function downloadProgress(id) {
$.ajax({
url: "index.php?_controller=download&_action=getDownloadProgressAjax&downloadId="+id
})
setTimeout(function () {
if (downloadnotcomplete){ // this way your script stops at some pont.
downloadProgress(id);
}
},2000);
}
});
You will attach the downloadProgress(id) function to your download button or anything else, to trigger the function the first time.
The problem you are having is that you have to provide a parameterless function and not a function call to setTimeout. Also, I would do it a little bit different and use setInterval instead of setTimeout as it relays your intention better in the code. Here is how I would do it:
<script language="javascript">
$(function() {
setInterval(downloadHandler, 2000);
});
function downloadHandler() {
// I'm not sure where the id is coming from you will probably need to put a
// class on your div's so that you can select them.
$(".MyDivClass").each(function() {
var id = $(this).attr("id");
downloadProgress(id);
});
}
function downloadProgress(id) {
$("#" + id + "").load(
"index.php?_controller=download&_action=getDownloadProgressAjax",
{ downloadId: id }
);
</script>
and then on your div:
<?php
foreach ($downloads as $dl) {
?>
<div id="<?php echo $dl["download_id"]; ?>" class="MyDivClass"/>
<?php
}
?>
Hope this helps.
Related
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 do I make jQuery get value from while loop and display it in another div?
I know I should do it with PHP, But I want to display it with only jQuery.
<? while($commentresult = $commentdata->fetch_array(MYSQLI_ASSOC)) { ?>
<div class="show_url"></div>
<? } ?>
$(document).ready(function() {
var getUrl = $('.get_url_comments').attr('href');
$(".show_url").text("Click This" + getUrl);
});
To do this you can set the text() of the .show_url element based on the following .get_url_comments. Try this:
$(document).ready(function() {
$(".show_url").text(function() {
return $(this).next('.get_url_comments').attr('href');
});
});
You should note though that it would be a much better idea to do this directly in PHP:
<? while($commentresult = $commentdata->fetch_array(MYSQLI_ASSOC)) { ?>
<div class="show_url"><? echo $commentresult['comment']; ?></div>
<? } ?>
Try with this..
$(document).ready(function() {
$('.get_url_comments').map(function(guc){
var el = $(guc);
var url = el.attr('href');
el.prev().text("Click This" + url);
// or
el.prev().html("Click This" + url);
});
});
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>
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a button in my php page :
<button id="myButton">Delete me</button>
and in that page I have a variable which I want to pass to a JavaScript function, and this is my JS code :
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
How can I do that ?
I think you might be wanting to put a variable through PHP on your button and pass it to your function using jQuery data. Check this out:
<button data-confirmed="<?php echo $confirmed; ?>" id="myButton">Delete me</button>
And in your js:
$(function() {
$('#myButton').on('click', function(e){
// get jquery object access to the button
var $thisButton = $(this);
// this gets that data directly from the HTML
var confirmed = $thisButton.data('confirmed');
if(confirmed) {
//Here I'll use the variable
}
})
});
Basically, you can access variables in javascript using this method if you are interpolating PHP vars directly on the page. If this isn't what you are looking for, please let me know in comments.
<button id="myButton">Delete me</button>
<input type="hidden" name="variable" id="variable" value=2>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {=
alert(document.getElementById('variable').value);
//Here I'll use the variable
}
})
});
You can declare the variable outside the click event like so:
$(function() {
var confirmed = true;
$('#MyButton').confirmOn('click', function() {
if(confirmed) {
// do stuff
}
});
});
Assuming you're talking about passing php variables to Javascript, you can do this when writing to the page, ex:
<?php
$passThis = 'Passing'
?>
<script language="javascript" type="text/javascript">
var sStr = "My name is <?php echo $passThis ?>.";
document.write(sStr);
</script>
You could also get integer values, doing something like
$integerValue = 5;
var int = "<?php echo $integerValue; ?>";
int = parseInt(int);
By modifying this, you could use it to pass more types of variables, so assuming you have something like this:
<?php
$text = 'someText';
?>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
you could do
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
console.log("<?php echo $text ?>");
}
})
});
</script>
to make Javascript alert 'someText'.
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);
});
});