I'm trying to retrieve data from a php file named return that just contains
<?php
echo 'here is a string';
?>
I'm doing this through an html file containing
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
var x;
$.get("return.php", function(data){
x = data;
})
function showAlert() {alert(x);}
$(document).ready(function(){
alert(x);
});
</script>
</head>
<body>
<input type = "button" value = "Click here" onClick="showAlert();">
</body>
</html>
When the button is clicked it retrieves and displays the code fine, but on the $(document).ready thing, it displays "undefined" instead of the data in return.php. Any solutions?
Thanks.
the document.ready is running before the $.get has returned the msg probably
var x;
function showAlert() {alert(x);}
$(document).ready(function(){
$.get("return.php", function(data){
x = data;
showAlert();
})
});
that should work fine
The ajax probably has not loaded yet.
var x;
function showAlert() {alert(x);}
$(document).ready(function(){
$.get("return.php", function(data){
x = data;
alert(x);
});
});
It isn't a question of scope, it's a question of order of events. $.get is an asynchronous call, so it may not finish yet by the time your page loads in the browser (it's a fairly small page so I imagine it loads quite quickly).
Related
i'm new in PHP and JAVASCRIPT..
i need to do a little script who takes the data from data.php with
$.getJSON("data.php", function(json).. and push it into 2 arrays in the HTML file, to reuse them.
data.php produce this:
[[47,48,48,48,50,51,48,46,47,45,48,47],[25,23,22,21,19,21,24,25,27,29,31,28]]
at now i do this, but it doesn't run and i don't know how to do.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.getJSON("data.php", function(json) {
$row1[] = json[0];
$row2[]= json[1];
});
});
</script>
</head>
<body>
<div></div>
</body>
</html>
thanks to all guys ;)
Your assignment syntax is wrong. You can't put [] at the end of a variable in Javascript.
$(document).ready(function() {
$.getJSON("data.php", function(json) {
var row1 = json[0];
var row2 = json[1];
// put code that uses row1 and row2 here
});
});
I'm trying to build a basic JQuery app which loads images from Flickr, adds them to an array of jQuery objects, sequentially adds them to the DOM, fades them in, and fades them out in a 3 second cycle. However, in my displayImage function, I cannot use .hide(), .fadeIn() or .fadeOut() because it throws an 'Uncaught TypeError: Cannot read property 'fadeIn' of undefined' error. Here is my code, both the JS and the HTML:
var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
//Creates the empty array of jQuery image objects
var images = [];
$.getJSON(url, function(flickrResponse){
flickrResponse.items.forEach(function (photo){
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
//Populates the images array with jQuery objects defined from the Flickr JSON request
images.push($img);
// $("main .photos").append($img);
// $img.fadeIn();
});
});
function displayImage(imgIndex) {
var $displayedImg = images[imgIndex];
$(".photos").fadeOut('slow');
$(".photos").empty();
$(".photos").append($displayedImg);
$displayedImg.fadeIn('slow');
//Function which recursively calls 'displayImage' every three seconds
setTimeout(function(){
imgIndex = imgIndex + 1;
displayImage(imgIndex);
}, 3000);
}
displayImage(0);
};
$(document).ready(main);
And
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Flickr App</title>
<link rel="stylesheet" type="text/css" href="stylesheets/styles.css">
</head>
<body>
<header>
</header>
<main>
<div class = "photos">
</div>
</main>
<footer>
</footer>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="js/app.js"></script>
</body>
Any ideas what might be undefined? Note that the var $img = $("<img>").hide(); line in the $.getJSONrequest doesn't throw the undefined error!
Thanks very much!
EDIT:
I've also tried to make a synchronous request to fetch the JSON, to make sure it's loaded before the displayImage function is called, and still it throws the same errors:
var main = function(){
"use strict";
var url = "http://api.flickr.com/services/feeds/photos_public.gne?tags=cats&format=json&jsoncallback=?";
var images = [];
//THIS IS WHAT HAS CHANGED
$.ajax({url: url,
dataType: 'json',
async: false,
success: function(flickrResponse){
flickrResponse.items.forEach(function (photo){
var $img = $("<img>").hide();
$img.attr("src", photo.media.m);
images.push($img);
});
}});
function displayImage(imgIndex) {
var $displayedImg = images[imgIndex];
$(".photos").fadeOut('slow');
$(".photos").empty();
$(".photos").append($displayedImg);
$displayedImg.fadeIn('slow');
setTimeout(function(){
imgIndex = imgIndex + 1;
displayImage(imgIndex);
}, 3000);
}
displayImage(0);
};
$(document).ready(main);
You need to wait for the JSON to return before you try to displayImage(0). The JSON request is asynchronous, so your call to displayImage is happening before any JSON has been returned.
I recommend stepping through with a Javascript debugger to better understand what’s going on. You would see then that images is empty, and therefore $displayedImg is undefined.
I am using a PHP Simple HTML DOM Parser to save a website as a htm file. I then use jQuery to extract a div from the file and put it into a div. I want to create a
Previous and Next button but the problem I have is that to do this I have to change the URL so the parser can get the page. I would really appreciate if you can help. Below is the code I am using.
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=1');
$html->save('site/rtnews.htm')
?>
<script type="text/javascript" src="site/jquery.js"></script>
<script type="text/javascript">
$('document').ready(function() {
$('#wrap').click(function (event){
event.preventDefault();
});
$("#wrap").load('site/rtnews.htm #postsArea');
});
</script>
</head>
<body>
<div id="wrap">
</div>
</body>
You will have to create a new php file for this and make an AJAX request to that file. I assume you have already realised that you cannot make a cross-domain request due to CORS.
Here is your new php file, let's call it proxy.php. It will proxy the request, responding with the page that is passed to it via GET :
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=' . $_GET["page"]);
echo $html;
?>
Your new JavaScript;
$('document').ready(function() {
var $wrap = $('#wrap'),
page = 1;
$('#next').on('click', function () {
getPage(++page);
});
$('#prev').on('click', function () {
getPage(--page);
});
var getPage = function (page) {
$wrap.load('proxy.php?page=' + page + ' #postsArea');
};
getPage(page);
});
This code is working on other test environment but not on mine.
Do you know why?
I am using Amazon EC2 and Cotendo CDN.
The result I am getting is a blank page.
Thanks in advance!
<html>
<head>
<title>Geo Test</title>
<script type='text/javascript' src='http://www.101greatgoals.com/wp-includes/js/jquery/jquery.js?ver=1.7.1'></script>
<script>
$(document).ready( function() {
$.getJSON( "http://smart-ip.net/geoip-json?callback=?",
function(data){
console.log(data);
var c = data.countryCode;
if(c=="US" || c=="US" ){
document.getElementById('ddd').innerHTML = 'US'; } else {
document.getElementById('ddd').innerHTML = 'Not US';}
/*
this service needs ip
var ip = data.host;
alert(ip);
$.getJSON( "http://freegeoip.net/json/"+ip,
function(data){
console.log(data);
}
);*/
}
);
});?
</script>
</head>
<body>
<div id="ddd"></div>
</body>
</html>
Change this line:
$(document).ready( function() {
to that:
jQuery(document).ready( function($) {
It's necessary, because inside http://www.101greatgoals.com/wp-includes/js/jquery/jquery.js?ver=1.7.1 you've already got a call of jQuery.noConflict(); , so jQuery is not accessible by using the $
...and also remove the ? (see Pointy's comment above)
$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10");
while($message = $db->fetch_array($messages)) {
$oldmessages[] = $message['message'];
}
$oldmessages = array_reverse($oldmessages);
?>
<div id="chat">
<?php
for ($count = 0; $count < 9; $count++) {
echo $oldmessages[$count];
}
?>
<script language="javascript" type="text/javascript">
<!--
setInterval( "document.getElementById('chat').innerHTML='<NEW CONTENT OF #CHAT>'", 1000 );
-->
</script>
</div>
I'm trying to create a PHP chatroom script but I'm having a lot of trouble getting it to AutoRefresh
The content should automatically update to , how do you make it do that? I've been searching for almost an hour
I would take that PHP functionality you have and putting it in a sperate page that returns JSON. From there you can call that method using jQuery and the AJAX tools built in. Really simple. Start here for jQuery: http://api.jquery.com/category/ajax/
you'll need to set up a server side script that renders only the contents of the chat div and use ajax to grab that. it can be done with jquery quite easily:
In your html document:
<head>
...
<script src="/path/to/jquery.js" type="text/javascript"></script>
<script>
var chatUpdateInterval = null;
function initChat() {
chatUpdateInterval = window.setInterval(updateChat, 5000); /* every 5 seconds */
}
function updateChat() {
$.ajax({
url: '/url/path/to/your/script.php'
,dataType: 'HTML'
,success: function(data, status, xhr){
$('#chat').append($(data).html());
}
});
}
$(document).ready(function(){
initChat();
});
</script>
...
</head>
<body>
<div id="chat">
please stand by while we're firing up the coal!
</div>
</body>
Note that this won't be really good, it's just a sample to get you started. you should look into jquery's $.ajax