Cannot read property 'load' of null - javascript

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);
});

Related

javascript variable to external php and back

I need to pass value from javascript file (javascript.php) to php file (php.php), and get it back.
file javascript.php
<script>
var name = 'catalin';
$.post('php.php', {jsvar: name});
</script>
file php.php
$phpvar = $_POST['jsvar'];
How do I get variable's value back on the file javascript.php ?
Thanks!
$.ajax({
type: "POST",
url: url,
data: {"var":"value"},
success: function(data) {
// do something
}
});
https://api.jquery.com/jquery.post/
You can use callback function as below:
file javascript.php
<script>
var name = 'catalin';
$.post('php.php', {jsvar: name},function(data,status,xhr){
alert(data);
});
</script>
file php.php
$phpvar = $_POST['jsvar'];
echo $phpvar;
if you r doing this with ajax then just echo the php value and get it with return value in jquery
<script>
$(document).ready(function(e){
var name = 'catalin';
$.post('php.php', {jsvar: name},function(returnedValue){
alert(returnedValue);
});
})
</script>
in php do this
$phpvar = $_POST['jsvar'];
echo $phpvar ;
you can see the result in alert.
My answer is nothing new but find the complete code. I haven't tested it. Please be aware there might be a minor typo.
javascript.php
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<button onclick="test_request()">Test Request</button>
<script>
function test_request() {
$.post("php.php", {jsvar: name}, function(data_from_php) {
console.log(data_from_php);
});
}
</script>
</body>
</html>
php.php
<?php
$phpvar = $_POST['jsvar'];
echo 'Hello' . $phpvar;
What's happening is jQuery is posting some value to the HTTP server (aka a POST request) and the anonymous function(data_from_php) is waiting for the server to respond with some data. As soon as the data arrives the function is triggered.
You can verify it from the Chrome's debugger window (or Firefox etc). For example, in Chrome just press Ctrl+Shift+I to open the developers tools. Click on the Network tab and click on XHR and notice when the request is made. You will be able to see what is happening under the hood and how it is working.

Removing a WordPress filter by calling a PHP function with Ajax

I'm trying to remove the filter by calling a PHP function using and it's not working.
Here is my code
JS
<script type="text/javascript">
function in_right_place()
{
var x="<?php in_right_place(); ?>";
alert(x);
return false;
}
window.onload = in_right_place;
</script>
PHP
<?php
function in_right_place()
{
remove_action( 'login_init', 'send_frame_options_header', 10, 0 );
}
?>
This doesn't work, probably for good reasons for professional eyes,
but I don't know what to do next to make it work
This is a first step, at the end I want to Call this function on a specific condition, But can't make the first step work.
you will need to make ajax request to wordpress. something like this in functions.php or in a custom plugin (php file you are referring to)
function in_right_place()
{
remove_action( 'login_init', 'send_frame_options_header', 10, 0 );
die('done');
}
add_action("wp_ajax_nopriv_in_right_place", "in_right_place");
add_action("wp_ajax_in_right_place", "in_right_place");
In your js do something like this (assuming you have jQuery if not see this)
jQuery.post(
"http://yoursite/wp-admin/admin-ajax.php ",
{
'action': 'in_right_place'
},
function(response){
alert('The server responded: ' + response);
});
more details here and here

jQuery-ajax 'on click event' not working

I'm trying to use ajax to load certain pages, but the 'on-click' is not working. I created an init() function so one of the pages auto-loads when the page gets loaded. That works! However, when I click on any of the links, nothing gets loaded. In fact, nothing happens. Once a link is clicked, it's not going to the jQuery script. Any suggestions will be greatly appreciated.
Here are my links...
<a href="#" id='add' >Add</a>
<?php foreach($names as $name): ?>
<?= $name['name']; ?>
<?php endforeach; ?>
<section id='main'>Main content</section>
Here is my jQuery script...
var app = { // this is a namespace
nav: $('a.league'), // selector
content: $('section#main') // section where id='main'
};
app.putContent = function(content){
this.content.html(content);
}
app.loadPage = function(page){
$.ajax({
url: '../views/security.php',
type: 'GET',
cache: false,
//data:{id: page}, // this works too
data:"id=" + page,
success: function(data){
app.putContent(data);
},
error: function(){
app.putContent('Could not find page.');
}
});
}
app.init = function(){
app.loadPage('add'); // this part works
app.nav.on('click', function(){ // This part(on click) is not working
var page = $($this).attr("id");
app.loadPage(page);
});
}();
Change this line:
var page = $($this).attr("id");
Into this:
var page = $(this).attr("id");
Tip:
use your browser inspector/console to identify the problems in JS
code

Javascript change inner html of div that contains php include

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>

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