I have built an area on my client's website that displays a song that is currently playing, as parsed from an XML file via PHP. However, my client wants the song to auto-refresh itself instead of him having to manually refresh the page.
I played around with parsing the file using jQuery.get() and also .ajax(), but because of the way the XML file is structured, it seems as though I can only get the artist and the name squashed into one string, or when I try to be specific it only returns [object Object].
I haven't even tried to tackle having the song's length be calculated and then refresh the feed based on that length. I may not seeing as this is apparently such an issue for me.
Any help or general guidance would be greatly appreciated.
Example working PHP code (obviously, non-AJAX):
<?php
$recentlyPlayed = simplexml_load_file('http://publicapi.streamtheworld.com/public/nowplaying?mountName=ABCDFM&numberToFetch=1&eventType=track');
$trackTitle = $recentlyPlayed->{'nowplaying-info'}[0]->property[1];
$trackArtist = $recentlyPlayed->{'nowplaying-info'}[0]->property[0];
echo "<h6>" . $trackArtist . "<span class=\"song-title\">" . $trackTitle . "</span></h6>";
?>
I've tried several different things to get this to work, but it seems the initial obstacle is trying to reference the data in the XML file using the attributes, rather than the node-names. The nodes are all named the same, and it's the attributes that differentiate them. So, as such this code will render correctly, unless the artist/song title are blank, then it renders the third field which is sort of cryptically-named "cue_time_start".
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
setInterval("songPull()",1000);
});
function songPull() {
$.get(
"http://publicapi.streamtheworld.com/public/nowplaying?mountName=ABCDFM&numberToFetch=1&eventType=track",
"xml",
function(data) {
$(data).find("nowplaying-info").each(function(){
var artist = $(this).find("property").eq(0).text();
var title = $(this).find("property").eq(1).text();
$('body').html("<h1>" + artist + "<small class=\"song-title\">" + title + "</small></h1>");
console.log (artist);
console.log (title);
});
}
);
}
</script>
<body>
</body>
Any guidance, advice or examples of best practices when trying to do this sort of thing would be so very greatly appreciated.
I'm not exactly sure if this is what you want, but you could simply use attribute selectors to extract the data you want out of your XML document.
http://jsfiddle.net/P8dc6/
$.get("http://publicapi.streamtheworld.com/public/nowplaying?mountName=KROXFM&numberToFetch=1&eventType=track",
"xml",
function(data) {
var $nowPlaying = $(data).find('nowplaying-info');
console.log($nowPlaying.find('[name=track_artist_name]').text());
console.log($nowPlaying.find('[name=cue_title]').text());
}
);
Also, never pass a string to setInterval or setTimeout, you can just pass the function reference directly:
setInterval(songPull ,1000);
Related
I'm using gmaps.js as an interactive map on my site. The library allows you to add new map markers using long/lat co-ordinates. These are stored in my database, which I retrieve (along with other data) and echo this data like so:
<input id="lat" type="hidden" value="'.$lat.'"/>
<input id="long" type="hidden" value="'.$long.'"/>
There is other data being echoed, which is why you cannot see any <?php ?> tags - this is not a syntax mistake!
When I inspect element on the front end of my site, I can see the corresponding values have echoed successfully.
The issue I'm having is getting the values stored in the <input> tags into my jQuery function.
I want to get each of the long and lat values into here:
map.addMarker({
lat: $lat,
lng: $long,
title: 'Lima',
}
});
However as I understand, it's bad practice to echo PHP straight into a jQuery function.
Therefore, I have tried to do the following:
$(document).ready(function(){
$("lat").val();
$("long").val();
$.each( markers, function( index, value ) {
var markers = {
lat: value.lat,
lng: value.long,
}
});
});
What do you suggest?
Thanks in advance for your time!
I'm not the most advanced programmer, but I know a cleaner solution for your problem.
JSON
I understand you use PHP to retrieve your coordination, and you want your results displayed in a manner that Javascript can understand. Well, there's a better way for communicating between languages, it's called JSON. You can use it in PHP like this:
echo json_encode(["lat"=>$lat,"long"=>$long]);
Then you can retrieve it in Javascript like this:
var LatLong = JSON.parse('{"lat":"lat","lon":"long"}');
You can then use normal Javascript to retrieve both the Lat and the Long. Simply by doing LatLong.lat or something alike.
AJAX
Normally I would use AJAX for such things, but I suppose you don't have to.
Finally, code
Here's an example of how I would do it without AJAX
var parseString = '{"lat":"lat","long":"long"}'; // <-- Your PHP echo
var LatLong = JSON.parse(parseString);
map.addMarker({
lat: LatLong.lat,
lng: LatLong.long,
title: 'Lima',
}
});
In first, in JQuery to select an element by Id you need to insert # before html id
$("#lat").val();
$("#long").val();
Then, I don't understand your code, but as I can see the two lines above don't make anything, get value from input element but don't save them to any variable.
I assume you have the lng/lat data in a Database accessible by PHP. So, then you can just pass it to your client side javascript via json_encode(). The code below assumes you have a array of row objects from your database.
<script>
// Created data from PHP
var mapData = <?php echo (!empty($data)) ? #json_encode($data) : '[]'; ?>;
</script>
Then just continue as you were, using $.each(), etc.
Hi all i know this question has been posted but being a total noob i couldnt get what answers meant. Please help. I want to pass inputbox value dynamically to a php variable . i am using javascript here please suggest if there's another way without using form submission , _GET or _POST. i want it done dynamically without any submission.
function showHint(str)
{
document.getElementById('TK').innerHTML = str;
var str = str
}
</script>
<html>
<head>Inputbox</head>
<title>TEST PAGE </TITLE>
<body>
<input type='text' id='TK' name='TK' onkeyup='showHint(this.value)'/>
<?php
$str = var str ;
echo "<a href = 'newpage.php?S=$str'/>" ; ?>
</body>
</html>
No. You can't. PHP is NOT a dynamic language, and it does NOT run client side. PHP runs once, and only once, and that's when the page is loaded. It runs its script and it stops. What you can do is get javascript to do an AJAX call. AJAX is basically a way of passing information to another page and getting the data, all in JavaScript. Do some research on it, but in short, you can't make PHP run once it's already been run
<script type="text/javascript" >
function process(){
var field1 = 'whatever';
var field2 = 'more whatever';
$.post("go.php",{field:field1,bext_field:field2},function(result){
alert(result);
});
};
</script>
This will alert out whatever you ECHO from GO.PHP.
You will also need a handler like:
onClick="process();"
on a div, button, image, just about anything you want to "initiate" your post
I would imagine the other answers you found probably would have said the following:
PHP executes before the user has a chance to see the page.
JS let you control what happens after.
Therefore, your problem is that you are trying to use PHP to do something it simply cannot.
Use those points to help guide your decisions when developing your applications. In this case, if you're trying to build a link based on what a user types in a box, your solution to the problem isn't PHP at all (the page is already loaded, you're too late!) -- your solution is JS.
Think about it like this:
/*
assumes you already have an <a> on the page. if not, you'll
have to create a new <a> element dynamically. (google "mdn createElement"
for help)
*/
function showHint (str) {
document.getElementById('TK').innerHTML = str;
var link = document.getElementById('your-a-link');
link.setAttribute('href', 'newpage.php?S=' + str);
}
Before anyone says "try searching", I have - I realize this is probably a simple solution, but I just can't get it to work. This is my first venture into AJAX - and my knowledge of javascript is slightly above a 1st grader...I know I need to get up to speed on it.
I'm trying to build a nested task manager, using AJAX. I'm getting jammed up on the AJAX implementation...the list works well otherwise. The basic concept should output like this:
Goal: Create a nested task list
Milestone: Build the basic setup - completed 2/11/12
Task: Design the database - completed 2/11/12
Task: Design the php stuff - completed 2/11/12
Milestone: Add the finesse
Task: Include AJAX functioning
Task: Include CSS
As you click on the link, it runs my MySQL update to show the item being completed. I have three nested while loops (one for goals, one for milestones and one for tasks). They are near identical. Here's the most deeply nested loop:
$query_tasks = mysql_query("SELECT * FROM task WHERE task_gid = '$task_gid' AND task_mid = '$task_mid' AND task_tid IS NOT NULL");
$t_numrows = mysql_num_rows($query_tasks);
if($t_numrows > 0){
while( $get_task = mysql_fetch_array($query_tasks)){
$task_id = $get_task['task_id'];
$task_goal = $get_task['task_goal'];
$task_due = $task_task['task_due'];
$task_due = date("m/d/Y", $task_due);
$task_complete = $get_task['task_complete'];
$task_complete_date = $get_task['task_complete_date']; ?>
Here is my link to trigger the query:
<a id="link" href="#"><?=$task_goal?> by <?=$task_due?> </a>
}
Here is my ajax query:
<script type="text/javascript">
$('#link').click(function(){
$.ajax({
type: "GET",
url: "complete.php?id=<?=$task_id?>"
});
return false;
});
</script>
I've got it to work for one link (if I click on the last rendered link, it works as desired - but no other links do). I've tried calling the javascript in the head (my preferred method) as well as calling it each time the loop passes (not sure that's a good idea, but whatever). My thought is to use the variable from the while loop for each task in the javascript function. I've tried placing the ajax script into a javascript function and calling it on the onClick behavior for the link, but no luck. Thoughts?
This is how you should do it:
http://pastebin.com/ZMCzAS5H
By setting a custom attribute (task_id) to your link you'll be able to retrieve it later in the ajax request. This way you'll use one event binder for all of the links instead of one for each link.
It's not a good idea to use the same ID for several elements within the same document; IDs should be unique. Use classes instead so try
<a class="link" href="#"><?=$task_goal?> by <?=$task_due?> </a>
and
<script type="text/javascript">
$('.link').click(function(){
$.ajax({
type: "GET",
url: "complete.php?id=<?=$task_id?>"
});
return false;
});
</script>
JavaScript and PHP do not interact. PHP is a 'pre-processor' and basically generates HTML (in this context). You can't use PHP variables in JavaScript. Period.
When generating the HTML, add the task_id to the anchor
echo "<a class=\"link\" href=\"#\" rel=\"". $task_id ."\">". $task_goal ." by ". $task_due . " </a>";
(don't use an ID for link, but use a class)
Then in jQuery:
$('.link').click(function(e){
e.preventDefault(); // use this instead of return false;
task_id = $(this).attr('rel');
$.ajax({
type: "GET",
url: "complete.php?id="+ task_id
});
});
"I've got it to work for one link (if I click on the last rendered link, it works as desired - but no other links do)"
This is probably because you have used an ID for the anchor, and you can only use an ID once on the page. You must use a class
Is it possible to get an element id into a PHP variable?
Let's say I have a number of element with IDs:
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
How do I get this into a PHP variable in order to submit a query. I suppose I would have to resubmit the page, which is OK. I would like to use POST. Can I do something like:
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post("'.$_SERVER['REQUEST_URI'].'", { id: $(this).attr("id") });
});
});
</script>
I need to pass $(this).attr('id') into $newID in order to run
SELECT * from t1 WHERE id = $newID
jQuery is a very powerful tool and I would like to figure out a way to combine its power with server-side code.
Thanks.
This is like your question: ajax post with jQuery
If you want this all in one file (posting to active file) here is what you would need in general:
<?php
// Place this at the top of your file
if (isset($_POST['id'])) {
$newID = $_POST['id']; // You need to sanitize this before using in a query
// Perform some db queries, etc here
// Format a desired response (text, html, etc)
$response = 'Format a response here';
// This will return your formatted response to the $.post() call in jQuery
return print_r($response);
}
?>
<script type='text/javascript'>
$(document).ready(function() {
$('.myElement').click(function() {
$.post(location.href, { id: $(this).attr('id') }, function(response) {
// Inserts your chosen response into the page in 'response-content' DIV
$('#response-content').html(response); // Can also use .text(), .append(), etc
});
});
});
</script>
<span id="1" class="myElement"></span>
<span id="2" class="myElement"></span>
<div id='response-content'></div>
From here you can customize the queries and response and what you would like to do with the response.
You have two "good" choices in my mind.
The first is to initiate a post request every time the ordering changes. You might be changing the ordering using jQuery UI sortable. Most libraries that support dragging and dropping also allow you to put an event callback on the drop simply within the initialization function.
In this even callback, you'd initiate the $.post as you have written it in your code (although I would urge you to look up the actual documentation on the matter to make sure you're POSTing to the correct location).
The second strategy is to piggyback on a form submission action. If you're using the jQuery Form Plugin to handle your form submissions, they allow you to indicate a before serialize callback where you can simply add into your form a field that specifies the ordering of the elements.
In both cases, you'd need to write your own function that actually serializes the element IDs. Something like the following would do just fine (totally untested; may contain syntax errors):
var order = [];
$('span.myElement').each(function(){
// N.B., "this" here is a DOM element, not a jQuery container
order.push(this.id);
});
return order.join(',');
You're quite right, something along those lines would work. Here's an example:
(btw, using $.post or $.get doesn't resubmit the page but sends an AJAX request that can call a callback function once the server returns, which is pretty neat)
<script language="JavaScript">
$(document).ready(function(){
$(".myElement").click(function() {
$.post(document.location, { id: $(this).attr("id") },
function (data) {
// say data will be some new HTML the server sends our way
// update some component on the page with contents representing the element with that new id
$('div#someContentSpace').html(data);
});
});
});
</script>
Your approach looks perfectly fine to me, but jQuery does not have a $_SERVER variable like PHP does. The url you would want to provide would be window.location (I believe an empty string will also work, or you can just specify the url on your own). You seem to be sending the ID just fine, though, so this will work.
If you want the page to react to this change, you can add a callback function to $.post(). You can do a variety of things.
$.post(window.location, {id: this.id}, function (data) {
//one
location.reload();
//two
$("#responsedata").html(data);
//three
$("#responsedata").load("affected_page.php #output");
});
I think number 2 is the most elegent. It does not require a page reload. Have your server side php script echo whatever data you want back (json, html, whatever), and it will be put in data above for jQuery to handle however you wish.
By the way, on the server side running the query, don't forget to sanitize the $id and put it in quotes. You don't want someone SQL Injecting you.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
So I have an array of records retreived from a database. The array is in the format;
$rows[0]['id']=1;
$rows[0]['title']='Abc';
$rows[0]['time_left']=200;
$rows[1]['id']=2;
$rows[1]['title']='XYZ';
$rows[1]['time_left']=300;
//And so on upto 10-20 rows
What's the best way of transferring this array over to my javascript code? I'd like the javascript to be able to loop through all of the records, and using the 'id' attribute, update the div with that id with some information.
My javascript code is in an external .js file, but i'm able to execute php code in the HTML code of my page. So I could do something like this:
In my_file.js:
var rows=New Array();
In HTML code:
<html>
<head>
<script type="text/javascript" src="js/my_file.js"></script>
<script type="text/javascript">
<? foreach ($rows as $row):?>
<? extract($row);?>
rows[<?=$id;?>]['title']="<?=$title;?>";
//And so on
<? endforeach;?>
</script>
I tend to use a JSON object for this:
On the server side, JSON encode your data: json_encode($data);
On the JavaScript side, I write a function that takes a JSON object as a parameter and unpack it.
When you unpack the object, you can print the array's contents into a <DIV> tag, or where ever you would like on the page (jQuery does a pretty sweet job of this).
If you're doing inline data, I've always been fond of doing
<script type="text/javascript">
window.sitescriptdata = {};
window.sitescriptdata.foo = ( <?php echo json_encode( $structure ); ?> );
</script>
For basic stuff, saves you doing an AJAX callback. Also, if you want to glue data to a DOM node, the "metaobject" way is something I really love.
<div id="foobar">
<div><object class="metaobject">
<param name="data" value="<?php echo htmlentities(json_encode($data), ENT_QUOTES );?>" />
</object></div>
</div>
Now this may not look great, but its an effective way of associating data directly with a DOM node without needing to know the exact unique path to that node. Very handy if you have many many datasets that need to be attached to specific screen elements.
I usually use http://noteslog.com/metaobjects/ plugin for jQuery, but its so simple I have on occasion written it myself ( there was a time I couldn't find the plugin, but new how it worked )
When done, there will be
$("div#foobar > div").get().data.($yourarrayhere)
Visible to your code.
To follow up to your question (and my reply, I ran out of space on the comment reply), here is a very simplified subset of the code I use:
Javascript AJAX handler in jQuery:
$.ajax({
type: "POST",
url: "BACKEND.php",
timeout: 8000,
data: "var1=" + myVar,
dataType: "json",
error: function(){
$("#DIVID").html("<div class='error'>Error!</div>");
},
success: function(jsonObj){
$("#DIVID").html(jsonObj.mydata);
}
});
PHP Array:
$data['mydata'] = $myData;
In an AJAX example like here you can solve this problem on this way:
.php file (ajax return function)
$myArray = array("object_id"=>1, "object_title"=>"Testobject");
return json_encode($myArray);
.js file (javascript function)
...
if(g_httpRequest.readyState == 4)
{
var jsonRes = JSON.parse(g_httpRequest.responseText);
alert(jsonRes.object_title)
}
...
im still fairly new too say maybe this method isnt the most secure, but you can always turn your javascript array into a string and then pass it through the URL for the php to GET.
so:
for(var i=0;i < jsarray.length;i++)
{
var x = jsarray[i];
urlstring += "myvalue[]="+x+"&";
}
document.location.href = "mypage.php?"+urlstring;
and then the php would be:
$phparray = $_GET['myvalue'];
hope that helps