I know there are a lot of these questions about this one, but unfortunately i cant find the right answer so i try it again.
I simply want to display the current song from "http://178.19.116.253/currentsong?sid=1" on my site that must refresh every x seconds.
I rather not use php cause it will make a background process for all users, so i've seen a lot of little scripts like this..
<div id="sc_stats"><?php include_once 'sc_stats.php'; ?></div>
var refreshId = setInterval(function() {
$.get("sc_stats.php", function(data) {
$("#sc_stats").html(data);
});
}, 10000);
But i cant get mine to work without php.
Someone can help me with this?
You don't need to use php, the following snippet which only uses jQuery will display the current song and refresh it every second.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="nowplaying"></div>
<script src="https://cdn.jsdelivr.net/jquery/3.2.0/jquery.min.js"></script>
<script>
setInterval(function() {
$.ajax({
url: "http://178.19.116.253/currentsong?sid=1",
dataType: "html",
success: function(data) {
$('.nowplaying').text(data);
console.log(data);
}
});
}, 1000);
</script>
</body>
</html>
Note: In order to get this to work, either:
This piece of code must run on the same domain/server as your stream
Or CORS must be enabled on your server. More about CORS can be found here
You can test CORS with the following Chrome plugin: Allow-Control-Allow-Origin:
Related
The code below does not update according to frequency;
It is just updating once at the beginning
new Ajax.PeriodicalUpdater('message_field', "http://localhost:8888/lsl_application/php/update_message_field.php?"+param, {
method: "GET",
frequency: 2,
decay: 1,
onSuccess: onSuccess_forPeriodic,
onFailure: function(xhrResponse){
alert("Failed to update!"+xhrResponse.statusText);
}
});
Hi according to your question I have made sample application as below. It looks like your web service/API is taking some time to process your request.
Please try to run as below example you may have an answer to your question.
My Client Code, Index.php, request every second.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Hello</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="prototype.js"></script>
<script type="text/javascript">
new Ajax.PeriodicalUpdater('message_field', "time.php", {
method: "GET",
frequency: 1,
//asynchronous: false,
onSuccess: function(s){
document.getElementById("t").innerText = s.responseText;
},
onFailure: function(xhrResponse){
alert("Failed to update!"+xhrResponse.statusText);
}
});
</script>
</head>
<body>
<h1 id="t"></h1>
</body>
</html>
Server Code, time.php, Web Service/API logic.
<?php
sleep(5);
echo date('h:i:s A');
?>
Note: Please have look to the Network of your browser. I have the frequency of 1 while answer comes at every 5 seconds.
According to the documentation http://api.prototypejs.org/ajax/Ajax/PeriodicalUpdater/ the frequency is the amount of time that the code waits between the end of the first request to when the next request is started.
For example what you are expecting is this
function poll()
{
//function body
}
setInterval(poll,2000);
However what Ajax.PeriodicalUpdater does is this
function poll()
{
//function body
setTimeout(poll,2000);
}
poll();
The benefit of waiting till the first(previous) request is finished prevents the UI from hammering the backend code every 2 seconds regardless of how fast the backend process runs. Especially if the backend process takes 2 seconds or longer to process, it will cause the requests to stack.
Also I believe you might be using it incorrectly as Ajax.PeriodicalUpdater is simply a wrapper around Ajax.Updater which does the content update for you. I could be wrong as I can't see the rest of your code. The code snippet you provided should be updating the element with id message_field with the response from your URL request. That content update is fired on the onComplete event which is after the onSuccess event. So if the URL response is not changing as it does in Jenish Zinzuvadiya's answer then you would see that behavior.
I hope I was able to help.
I´m trying to learn ajax, sitting here sinse 3 hours and trying to understand what I need to make it run.
I´m using it on Scriptly with Xampp.
This is my code:
<head>
<title>Titel</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax Example!</title>
<script src="js\jquery/jquery.js"></script>
<script>
$(document).ready(function(){
$("#btnSubmit").click(function(){
//alert("hello");
$.ajax({
type: "POST",
url: "http://localhost/inde.php",
data: {
myName: "durgesh technoclass"
},
success: function(output){
alert(output);
}
});
});
});
</script>
</head>
<body>
<form>
<button id="btnSubmit">Click me !</button>
</form>
I even watched a tutorial on Youtube and copied all the code from there.
The rating of the tutorial is good, the code seems to work for him, but why doesn´t it work for me ?! I don´t understand that.
The Jquery works, but ajax doesn´t. The Script just reloads the page and displays nothing.
Please help.
Edit:
May it be that it doesn´t work, because xampp doesn´t run an actual server ?
On request, here´s the code of the "inde.php":
<?php
echo "Welcome from Server";
?>
Edit 2:
Solution:
I messed up the path of the inde.php.
Just fixed it.
It works but there´s a mistake in the code. It had been fixed by Tanvir Ahmad Sohan. You can find his fix in his answer down there.
Try this...
<script>
$(document).ready(function(){
$("#btnSubmit").click(function(event){
event.preventDefault();
//alert("hello");
$.ajax({
type: "POST",
url: "http://localhost/inde.php",
data: {
myName: "durgesh technoclass"
},
success: function(output){
alert(output);
}
});
});
});
</script>
As your button is inside a form, when you click the button, form is being submitted to the same page, so it just reloads. To prevent this from happening use preventDefault() to prevent the default behaviour.
I'm trying to get photos from instagram by get request,
I tried jQuery.get() which worked well for other purpose of get request which is not instagram,
but for this one it doesn't work.
I used postman and I get the request no problem at all,
I also tried to change from jQuery.get() to jQuery.getJSON() and still no luck.
By the way, tried to get the request with NodeJS using request module and it works fine.
Hope you can help, here is my simple code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(function () {
$.get("https://www.instagram.com/uefachampionsleague/media/",
function (data) {
alert(items[0].id);
},"json");
});
</script>
</head>
<body>
<p></p>
</body>
</html>
You need to register your application and then set the credentials in the AJAX request, or you can also use the crossorigenme proxy:
$(function () {
$.get('https://crossorigin.me/https://www.instagram.com/uefachampionsleague/media/', function(data) { console.log(data); });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
As Jaromanda added "It's worth noting the caveat on crossorigin.me - PLEASE DO NOT USE THE PROXY ON A PRODUCTION SITE - if you want to "bypass" CORS, use your own damned server to do it".
Now I have a javascript code which refreshes a webpage every 2 seconds to check if there is any update from the database.
What I would like it to do is to play a sound when the webpage display new things.
Below is the html file:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function() {
$.ajaxSetup ({
cache: false
});
var auto_refresh = setInterval(function () {$('#loading').load('index.php').fadeIn("slow");}, 2000);
});
</script>
</head>
<body>
<div id="loading"></div>
</body>
</html>
I am new to Javascript
I think what you want is custom implementation like HTTP ETag.
It should look like this:
Extract version no from html sent by PHP script, pass this version no to each ajax request, server will check both versions and provide proper responses to client.
If server replies with
1) http status code 200 => web page is changed => play sound.
2) http status code 304 => web page is not changed
Hey guys,
I have a little problem with a simple ajax request. I can't figure it out why jquery ajax method doesn't work with the last version of chrome ... on ff work great so as on opera but on chrome i don't get any response and no errors. This is my js code:
function load(idno){
var url = 'index.php';
$.get(
url,
{
pagina:"ajax",
show:"cars",
brand:idno
},
function(data) { document.getElementById("model").innerHTML=data },
"html"
);
}
Any reason you're not just using jQuery.load()? Eg
$('#model').load('index.php', {
pagina: 'ajax',
show: 'cars',
brand: idno
});
At a guess, I'd say the problem is with the innerHTML call. A more robust method would be to use jQuery.html(), eg
function(data) { $('#model').html(data); }
Edit
Just whipped up this test and it works fine
<?php
// test.php
echo '<pre>', print_r($_REQUEST, true), '</pre>';
<!-- test.html -->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="model">
Default text
</div>
<p><button id="fetch-data">Fetch Data</button></p>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('#fetch-data').click(function() {
$('#model').load('test.php', {
pagina: 'ajax',
show: 'cars',
brand: 123
});
return false;
});
});
</script>
</body>
</html>
When I click the button, I can see all the request variables sent to the script
After a long long nith I've managed to resolve the problem. My JS code is good and maybe Phil's too ... I didn't try that in this version but the real problem in Chrome is that onclick attributes on option tags aren't allowed. So I made the event
<select onchange='loadData(this.value,'models')'></select>
and it is working great. Thank you Phil anyway.
because of Security reason chrome not allow cross-domain communication if request is not from a trusted sites,
if you want to use $.ajax in chrome so you need to disbale web security of chrome
use this comman.
your_chrome_path --disable-web-security
after doing this $.ajax works fine.