Javascript change inner html of div that contains php include - javascript

I am trying to do a javscript where the div contents changes after a certain amount of time to include the next flash animation but javascript is not accepting my code. I've tried to escape <?php include 'flash-2.php'; ?> with this <?php include \'flash-2.php\'; ?>
<script type="text/javascript">
setInterval(function()
{
var res = "<?php include \'flash-2.php\'; ?>";
document.getElementById("swfdiv").innerHTML = res;
},
3000);
</script>

PHP code is executed BEFORE the page is rendered to the user. Always. No exceptions. By the time your JS runs, it will do nothing.
If you want to include something in your page after it's already loaded, you need to look at an asynchronous technology, like AJAX.

Ajax is your best bet:
<script type="text/javascript">
setInterval(function()
{
$.ajax( "example.php" )
.done(function(res) {
document.getElementById("swfdiv").innerHTML = res;
})
},
3000);
</script>

If you want to show output of you PHP file in a DIV, then call your php file through AJAX and then update the innerHTML of the DIV.
For example if you use jQuery then you can do like,
$.get( "flash-2.php", function( data ) {
$("#swfdiv").html(data);
});
Hope it helps, thanks.

use ajax like this
<script type="text/javascript">
setInterval(function()
{
$.ajax({
type: "POST",
url: flash-2.php,
success: function(res){
if(res)
{
document.getElementById("swfdiv").innerHTML = res;
}
}
}),
3000);
</script>

Related

loading message with jquery and calling id

I made a small shoutbox for my site and I am loading the page with jquery and storing all my data in a database like usual. anyways, when a user wants to edit a post they double click on it and they can edit their post. I am using the following code to show the editor and let them do whatever they need to with it. sadly something isn't working and that something is:
i cant include my tag id in the url: on my ajax call
Here's is a look at the code
<? php
public function make_editable($shout, $id) {
$string = "<span ondblclick=\"javascript: edit_shout('".$id."'); return false;\">".$shout."</span>";
return $string;
}
?>
<script type="text/javascript">
function edit_shout($id) {
$("#panel_edit_shout").slideDown();
$('#update').val($id);
$('#delete').val($id);
$.ajax({
url : "/chat?loadModule=3&id={$id}",
dataType: "text",
success : function (data) {
$("#updateshoutmessage").val(data);
}
});
}
</script>
If i replace the {$id} with say, 1 for example, then it works correctly and loads the text of shout id 1 into the field like its supposed to, but if I try and load dynamically using $id, it just gets an error because the $id is coming up as blank... Thanks for your help :).
Uhm... if the variable is in javascript you can do:
url : "/chat?loadModule=3&id=" + $id,
If it is php then you have to do
url : "/chat?loadModule=3&id=<?=$id?>",
But like the other guys said, without more code we can't help much.
Very easy fix thanks to #Dranes for his help. Simply needed to add +
<script type="text/javascript">
function edit_shout($id) {
$("#panel_edit_shout").slideDown();
$('#update').val($id);
$('#delete').val($id);
$.ajax({
url : "/chat?loadModule=3&id=" + $id,
dataType: "text",
success : function (data) {
$("#updateshoutmessage").val(data);
}
});
}
</script>

Reload an AJAX loaded page after update

I'm trying to understand how a dynamic page loaded with AJAX can be reloaded after one of the records is updated. I've got the following jquery script on my page.
<script type="text/javascript">
function showUser(str) {
if (str == "") {
$("#txtHint").empty();
return;
}
$("#txtHint").load("data_ajax.php?q=" + str);
}
$(document).ready(function () {
$("#txtHint").delegate(".update_button", "click", function () {
var id = $(this).attr("id");
var dataString = 'id='+ id ;
var parent = $(this).parent();
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString
});
return false;
});
});
</script>
I thought I could get this done with the code below if I call it from within the data_ajax.php page after it loads the corresponding data from the database, but it refreshes the whole page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
location.reload();
});
});
</script>
I know this can be done, just not sure where to turn after searching for an answer for a while.
You would just do what you did to initially populate it:
$("#txtHint").load("data_ajax.php?q=" + str);
That will load your "new" AJAX and overwrite what's currently inside #txtHint with it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ref_butn").click(function(){
//location.reload();
$("#txtHint").load("data_ajax.php?q=" + str); // I don't know where str comes from, but you get the idea.
});
});
</script>
A part/block/div of the page cannot be refreshed but can be dynamically updated with the data on a callback.
On the server side, echo the data you'd like to show on the client-side.
For example:
//Successful update in the database
$callback = array('heading' => 'Success!', 'message' => 'The data was successfully submitted');
echo json_encode($callback);
To retrieve the data you've to pass success callback function to your ajax block.
$.ajax({
type: "POST",
url: "data_update_ajax.php",
data: dataString,
dataType: 'json',
success: function(data) {
$('#yourDiv .heading').text(data.heading);
$('#yourDiv .message').text(data.message);
}
});
Ben's answer worked, but he lead me to figure out an easier way to do this. So I essentially called the original function showUser(str) { on the button and just had to give it the selected $_GET value.
<button name="users" onClick="showUser(this.value)" value="<?php echo $_GET['q']; ?>">Refresh Content</button>
This button was placed on the data_ajax.php page, not the parent index.php for anyone looking to do the same. So, every time I hit the Refresh Content button, the table refreshes without reloading the page and I no longer lose the loaded content.

Cannot read property 'load' of null

Im making a code where the viewer count automatically refreshes every 10 seconds. Problem is, nothing is getting outputted, and on the console, it says cannot read property 'load' of null
I am using this as my code:
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#viewers').load('ajax.php?request=viewers&id=19').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
PHP
<?php
define('IN_MYBB', 1); require "./global.php";
require_once MYBB_ROOT."/inc/class_parser.php";
switch ($_GET['request']) {
case 'viewers':
$urlid = $db->escape_string($_GET['id']); // never trust any user inpit
$result = $db->query("SELECT * FROM ****_streams WHERE id='$urlid'");
$row = $db->fetch_array($result);
echo "Viewers: ".$row['viewers'];
break;
case 'contact':
break;
default:
break;
}
?>
Can anyone help? Thanks a bunch!
It looks like the $('#viewers') call is returning null. This is not normal for jQuery, as in every case it would return an object, even if it doesn't include any matching element.
For this reason, I suspect that you may have a problem with loading jQuery. It might just be a conflict with the $ sign, being handled by some script other tha jQuery, so try using:
jQuery('#viewers').load(/*....*/)
If that doensn't work either, then it might be that jQuery is not even loaded on your page, so check your script references.
Just taking a guess - most likely your script is executing before the DOM is loaded - since you are using Jquery - you can do this -
$(document).ready(function(){
var auto_refresh = setInterval(
function ()
{
$('#viewers').load('ajax.php?request=viewers&id=19').fadeIn("slow");
}, 10000);
});
Not tested but you can try change this:
$('#viewers').load('ajax.php?request=viewers&id=19').fadeIn("slow");
with this:
$.ajax({
url: 'ajax.php',
type : 'get',
data : { request : viewers, id : 19},
success: function(data){
$('#viewers').hide().html(data).fadeIn('slow')
},
error: function(xhr){
console.log(xhr.responseText);
}
});
Well i have tried running this locally. It works perfectly fine for me
Create a separate php file and check it!
text.php
<?php
if(isset($_GET['request'])){
echo "Hello from load";
}else{
?>
<html>
<head>
<script src="jquery.js"></script> <!-- replace with ur jquery -->
<script type="text/javascript">
$(function(){
setInterval(
function ()
{
$('#output').load('text.php?request=viewers&id=19').fadeIn("slow");
}, 10000);
});
</script>
</head>
<body>
<h2>Content</h2>
<div id='output'>
</div>
</body></html>
<?php } ?>
The element with id "viewers" does not exist yet. Move the <script> to the end of your document or replace it with
$(document).ready(function() {
var auto_refresh = setInterval(
function ()
{
$('#viewers').load('ajax.php?request=viewers&id=19').fadeIn("slow");
}, 10000);
});

Calling a php function from Javascript and using a javascript var in the php code

JavaScript
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "/test.php",
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
Php
<?php
$content = $_POST['prime'];
$fn = "content.txt";
$content = stripslashes('prime'"\n");
$fp = fopen($fn,"a+") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
?>
So this is all the relevant scripting I think. I have a script that can get prime numbers and it works perfectly. But now I want to record these numbers on a text file. This is how I am trying to do it but I am having no success at all. Thank you. The issue is the numbers aren't being recorded.
I added an alert the Ajax is working. But when I add a form to the php script and submit it that works. So the ajax and php scripts are not working together as such.
You should read up about AJAX and see how you can pass information to a serverside page using Javascript and retrieve the return value.
http://www.w3schools.com/ajax/default.asp
https://www.youtube.com/watch?v=qqRiDlm-SnY
With ajax and jQuery it is actually simple.
function calcPrimesLoop() {
var primes = document.getElementById('primes');
primes.appendChild(document.createTextNode('\n'+this.prime.nextPrime()));
$.ajax({
url: "myScript.php", // URL of your php script
type: "post",
data: {prime: this.prime.nextPrime()},
success: function(data) {
alert("success");
}
});
calcPrimesDelay = setTimeout('calcPrimesLoop()', this.delay);
}
myScript.php :
<?php
$content = $_POST['prime'];
...
You should definately look for Asynchronous JavaScript and XML.
You can choose between using AJAX with a Javascript function, or simplify your life with jQuery
Here is a sample:
//STEP ONE: INCLUDE THE LAST VERSION OF JQUERY
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
//STEP TWO, GET YOUR FUNCTION TO WORK:
function sendVariableTo(variable,url) {
$.ajax({
url:url, //Or whatever.php
type: "GET", //OR POST
data: { myVar: variable}, //On php page, get it like $_REQUEST['myVar'];
success:function(result){
//If the request was ok, then...
alert(result) //Result variable is the php page
//output (If you echo "hello" this alert would give you hello..)
},
});
}
Hope this helped, bye !

Ajax PHP not returning updated variable

My apologies, similar questions have been asked before - Tried a lot of things and can't figure out why this is not working. I'm calling ajax via a click function. I can't seem to get the jList value to return, updating the variable in the main page.
Here is a simplified version of what is not working. PHP file:
<?php
echo <<<END
<script type="text/javascript">
jList = "ELLO!!??";
//alert(jList);
</script>
END;
?>
Main Page is this:
<script>
var jList = false;
...
...
...
function loadMore(listFile, nextS, nextE) {
url = 'files/php/jList.php?l='+ listFile +'&s='+ nextS +'&e='+ nextE;
$.ajax({
url: url,
type: 'POST',
success:function(results) {
console.log(jList); // can't get the var to update with the value from PHP
}
});
}
...
...
...
$("#readMore").unbind("click").click(function(e){
loadMore(listFile, nextS, nextE);
});
</script>
Continually returns (console.logs) the value set initially on the main page. What am I missing? Thanks.
Your PHP should be:
<?php
echo 'jList = "ELLO!!??";';
?>
And the jQuery should be:
$.getScript(url, function() {
console.log(jList);
});

Categories

Resources