Get values from hidden <input> and use in jQuery function - php

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.

Related

How can I re-parse an XML document at set intervals?

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

PHP and JavaScript: Getting a HTML value in PHP

I have a span, it looks like this:
<span class="price" id="product-price-167">€47.00</span>
The 47.00 is set dynamically using JavaScript. Now when the user clicks a button, a request to a PHP script is being triggered. I need the 47.00 in that script. How could I do that? I know JS is front end and PHP is server side, but is there some way?
Thanks :)
Solution: I am using a hidden field and read that using
$price = $_POST["price"];
You can use jquery to retrieve the value of the element:
var value = $('#product-price-167').text();
I think that should give you the 47.00.
Using JQuery:
You can get the price inside the span:
var price = $('#product-price-167').text();
You can then parse price accordingly to get rid of the Euro sign. Without knowing exactly where your button will be placed or how it will work, it's kind of difficult to tell you how to get it to your PHP script.
Note that you shouldn't parse as Float if this is a serious application: Use
var parsedNumber = Number(price.replace(/[^0-9\.]+/g,""));
you can easily use jquery to post that value to php page using ajax
<script type="text/javascript">
// i m assuming that 167 in id product-price-167 comes from database in a loop
function buttonClick(pid){
var price=$("#product-price-"+pid).text();
$.ajax({
type : "POST",
data : "price="+price,
url : "yourphppage.php",
success :function(data){
//return something from php page
}
});
}
</script>
and your input button
<input type="button" onclick="buttonClick('167')" />
var path = 'path-to-script.php';
var data = 'price='+Number($('#product-price-167').replace(/[^0-9\.]+/g,"")); // to remove redundant [currency] characters
$.post(path, data, function(returnText){
// do stuff here
});
That should do.

Pass a PHP variable dynamically to an AJAX JavaScript function

I have a JavaScript function (which users on this forum graciously helped me construct) that passes variables via POST to a PHP file with a query for inserting the data to a MySQL database.
The function is invoked "onchange" for a series of 2000+ rows that are spit out from a MySQL database. I use the ID of the row to give each form field a unique name/id, like this:
echo "=<select name='$AdvertisersSQLResult[id]geolocation' id='$AdvertisersSQLResult[id]geolocation' onchange = 'insertAdvertiser()'>";
The JavaScript function looks like this:
function insertAdvertiser() {
var data = $('#<?php echo $AdvertisersSQLResult[id]?>dataid,#<?php echo $AdvertisersSQLResult[id]?>industry,#<?php echo $AdvertisersSQLResult[id]?>geolocation').serialize();
$.post('/database/InsertAdvertiserRelationship2.php', data);
return false;
}
As you can see, I'm attempting to pass PHP variables as part of the form id values. However, this doesn't work, as the function is written to the page once (in the section) without any variables yet populated.
In other words, I'd like to have this JavaScript function utilize whatever PHP variable is being passed to it dynamically. I've looked at other threads about passing a PHP variable to a JavaScript function, but I can't find any reference to how this can be done dynamically, such that the JavaScript function changes to use a different PHP variable each time (if that makes sense).
Thanks for any help...
Well yes because you'd need a seperate insertAdvertiser() method for every advertiser on the system.
A better way to do it would be to do this:
Javascript:
// This line turns your PHP array into a Javascript object
var advertisers = <?php echo json_encode($AdvertiserSQLResult); ?>;
function insertAdvertiser(id) {
$.post('/database/InsertAdvertiserRelationship2.php', advertisers[id]);
}
// Try not to use attributes to bind events, use handlers like this instead.
$(document).ready(function() {
$('select').on('change', function() {
// Reads the advertiser id from the data attribute
insertAdvertiser($(this).data('advertiserid'));
});
});
HTML:
<select data-advertiserid="<?php echo $AdvertiserSQLResult['id']; ?> class="advertiser-select">...</select>
I wrote this as I went along so apologies if I've overlooked something.
See:
jQuery Data
jQuery .on()
You can make a global JavaScript variable and use it in your scripts.
<script type="text/javascript">
myVariable = <?php echo $x; ?>;
</script>
You can store your variables someplace and then access them via JavaScript.
<input type="hidden" class="myVariable" value="<?php echo $x; ?>"
<script type="text/javascript">
var myVar = $('.myVariable').val();
</script>
After you have your data in JavaScript you can do what ever you want to do with it.

How to get element id into PHP variable

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.

Best way to transfer an array between PHP and Javascript [duplicate]

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

Categories