I have created this script to explode numbers from one data-get via php:
var n_polls=<?php echo $t_random_number;?>;
var myArray=n_polls.split(','); //explode
for (i=0;i<4;i++)
{
$("#t_sl_poll_"+myArray[i).hide();
}
The idea is to give some numbers from php for a random poll system, and I want explode this for close all in loop by the id. The problem is, I see something fail into the explode function for javascript, all time giving me nothing. How can I fix this?
Thank you.
Why explode in Javascript when you could have PHP just insert an array?
<?php
$numbers = array(1,2,3,4);
?>
<script type="text/javascript">
var n_polls = <?php echo json_encode($numbers); ?>;
for (i in n_polls) {
$("#t_sl_poll_" + n_polls[i]).hide();
}
There's further optimizations that could be done, but this'd be one place to start.
Take a look at your source. Your error console would tell you the same thing. You're not putting your array (not a number) in quotes, so it fails to compile during runtime:
var n_polls="<?php echo $t_random_number;?>";
//QUOTES! ^ ^
var myArray=n_polls.split(','); //explode
for (i=0;i<4;i++)
{
$("#t_sl_poll_"+myArray[i]).hide(); //Missing bracket
// ^
}
Now it'd compile to
var n_polls="1, 2, 3, 4";
instead of
var n_polls=1, 2, 3, 4; //Useless non-working code - not enclosed in anything
There are two things wrong here.
First: since you apparently hand over a string and not a number from php to javascript you have to write: var n_polls="<?php echo $t_random_number;?>";
Second: as pointed out in the comments already, you have to write $("#t_sl_poll_"+myArray[i]).hide(); to acutally address and element of your array.
your code should work as
var myArray= [<?php echo $t_random_number;?>];
for (i=0;i<4;i++)
{
$("#t_sl_poll_"+myArray[i]).hide();
}
Related
I have an SQL database (I know for sure it includes remote access, if that's necessary to access a database through php). It definitely has at least one record in it, and I need to get each record and create a corresponding button that links to a php file, taking the first field for that record as a/n argument, variable, parameter, or whatever you call the whatever.php?variable=value.
For some reason, this code just gives me a blank page. Why?
<?php
$connection=mysqli_connect("myhost","myusername","mypassword","mydatabase");
$result=mysqli_query($connection, "SELECT * FROM myTable");
$resultArray=array();
while ($row = mysqli_fetch_array($result)) {
array_push($resultArray, $row['ID']);
}
$resultArrayImplode = implode(",", $resultArray);
?>
<script>
var resultArray = <?php echo $resultArrayImplode; ?>
arrayEntries = new Array();
arrayEntries = resultArray.split(",");
function CreateButtons(element, index, array) {
var button = document.createElement("input");
button.type = "button";
button.value = element;
button.onclick = function() {
document.location.href = "ButtonClicked.php?id=" + element;
}
document.body.appendChild(button);
}
arrayEntries.forEach(CreateButtons);
</script>
Thanks!
Your javascript assignment to resultArray is probably not syntactically correct due to quote characters, etc. Luckily, PHP's JSON functions automagically create good javascript for you.
Try this for the javascript output:
var arrayEntries = <?php echo json_encode($resultArray)?>;
Your problem is $resultArrayImplode; is a string, so
var resultArray = <?php echo $resultArrayImplode; ?>
renders as:
var resultArray = 1,2,3,4,5
Which is a syntax error.
What you can do is use JSON. JSON syntax is JavaScript syntax, so all you need to do is:
var arrayEntries = <?php echo json_encode($resultArray); ?>;
This should render as something like:
var arrayEntries = [1,2,3,4,5];
Which is perfect JavaScript syntax. Then the rest of your code should work.
I just don't see why do you need to use javascript for this, cant you just do the following :
<?PHP
foreach($resultArray as $result)
{
?>
Im a button click me</div>
<?PHP
}
?>
in my opinion, i see no real need for you to use javascript for this.
I had a weird problem here. Please check the code below. I do not understand how this code below is created by somehow part of it is working, considering mixture of php variables and javascript variables.
First, let us see what the alert() outputs (take note that $lat and $lng is different from the array $vlat):
In Line 8 of the code below, alert(eventlocation) properly displays the coordinates of the GoogleMap latlng (so the implementation is correct)
In Line 13, alert(s) was able to display incrementing values (i.e. 0,1,2,3,4,..) based on the for loop in the previous line so it is also correct.
In Line 14, alert($vlat[0]) was able to display the latitude of the first element of that array (declared before this set of codes) so it is also correct
In Line 15, alert($vlat[1]) was able to display the latitude of the second element of that array so it is also correct
But in Line 16, alert($vlat[s]) displayed undefined.
Can anyone explain that? Thanks
echo "<script src= 'http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA2jrOUq9ti9oUIF0sJ8it1RTNr3PHi_gURF0qglVLyOcNVSrAsRRu2C3WQApcfD0eh9NLdzf9My0b9w' type='text/javascript'> </script>
<script language='javascript' type='text/javascript'>
function getabc(){
var eventlocation;
var volunteerlocation;
var s;
eventlocation = new GLatLng($lat, $lng);
//alert(eventlocation);
var volunteerDist = new Array();
s = $ctr;
var tvid = new Array();
for(s=0;s<$numrows;s++){
//alert(s);
//alert($vlat[0]);
//alert($vlat[1]);
//alert($vlat[s]);
}
}
a = getabc(); < /script>";
alert($vlat[0]);
alert($vlat[1]);
alert($vlat[s]);
$vlat[0], $vlat[1] and $vlat[s] are parsed on the server before they is sent to the client. The first two can be resolved, but PHP does not know what s is, since s is only defined once the client side is reached.
Edit from chat discussion
$json = json_encode($vlat);
echo "<script language='javascript' type='text/javascript'>
function test(){
var obj = JSON.parse('$json');
alert(obj);
}
< /script>";
The variable s that you are using to index the PHP array vlat is a variable that you declared in JavaScript. You cannot use it to index a PHP array.
What your code tries to do is to have PHP access a JavaScript variable, which it cannot. You can have PHP echo JavaScript, yes, but it doesn't work both ways.
All,
I have the following bit of code:
function addPoints() {
newpoints[0] = new Array(41.45998, 87.59643, icon0, 'Place', 'Content to open');
for(var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
There is other code around this to display the marker on my map. However this value is hardcoded. I have a PHP/mySQL database that has lat/long coordinates along with some other values. Say I have like three entries that I want to create markers for. How would I pass the addPoints function the lat/long that I got from my database so I can use it in this function correctly?
I updated my code to look like the following for the addPoints:
function addPoints(num, lat, long) {
newpoints[num] = new Array(lat, long, icon0, 'Place', 'Stuff name');
alert("The newpoints length is: "+newpoints.length);
for(var i = 1; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1],newpoints[i][0]);
var popuphtml = newpoints[i][4] ;
var marker = createMarker(point,newpoints[i][2],popuphtml);
map.addOverlay(marker);
}
}
I call this function by doing this:
<script>
addPoints('<?php echo json_encode($num_coordinates); ?>','<?php echo json_encode($lat_coordinates); ?>', '<?php echo json_encode($long_coordinates); ?>');
</script>
It doesn't work though. When I try not to pass it to javascript and just output the lat coordinates for example. I get the following output:
{"1":"40.59479899","2":"41.4599860"}
Which are the correct coordinates in my array. No markers get created though. Any ideas on what to do next or what I'm doing wrong?
An easy and clean way to pass an array from PHP to JavaScript is to simply echo the json_encode version of the array.
$array = array(1,2,3,4,5,6);
echo 'var values = '.json_encode($array).';';
PHP executes on the server before getting sent to the the client. Therefor, if you can do things like this:
newpoints[0] = new Array(<?php echo $lattitude;?>, <?php echo $longitude;?>, icon0, 'Place', 'Content to open');
Where $lattitude and $longitude are values that you pulled out of you database with PHP.
When this page is requested by the client, your php code executes, real values get plugged in where those php tags are making it look like the example you provided, and then it gets sent to the client.
If you want to change these values using JS on the client, or fetch new ones from the server, let me know and I'll add an example of that.
EDIT:
Okay, in light of your comments, it sounds like you've got a few options. Here's one:
When the user selects a category (restaurants, bars, etc) you pass that category as a url parameter and reload either the whole page, or just the map part of it (depends on your set up but might be worth investigating). Your link would look something like this:
http://www.your-domain-here.com/maps.php?category=bars
Maps.php is ready to catch the category using the $_GET array:
$category = $_GET['category']; //'bars'
Your php then grabs the appropriate location data from the database (I'll leave that part to you) and sticks it in a variable that your JS-controlled map will be able to use:
//JS in maps.php - you could add this var to the window object
// if you have separated js files...
var locationCoords = <?php echo json_encode($arrayOfCoordinatesFromDB);?>;
When you page loads on the client machine, it now has an array of coordinates to use for the map ready to go in the locationCoords variable.
Then, depending on which coordinates you need to display on the map, you pass them as arguments to your addPoints() using standard Javascript (nothing tricky here).
That's how I'd do it. Hope that helps!
It is as simple as echoing the php values.
new Array(<?php echo $php_lat;?>, <?php echo $php_long;?>, icon0 etc...
I made a dynamic banner with this javascript array initialization. It works fine when the javascript is embedded in php.
<?php
// This is our php array with URLs obtained from the server
$urlsPHP = ["img/img01.jpg","img/img02.jpg","img/img03.jpg"];
return = "
//...Some HTML...
<script type='text/javascript'>
// Now we use this inside the javascript
var urlsJavaScript = ".stripslashes(json_encode($urlsPHP)).";
//...Some javascript style to animate the banner...
</script>
";
// if we print this:
echo stripslashes(json_encode($urlsPHP));
// We obtain:
// ["img/banner/bak01.jpg","img/banner/bak02.jpg","img/banner/bak03.jpg"]
// This is a good syntax to initialize our javascript array
// if we print this:
echo json_encode($urlsPHP);
// We obtain:
// ["img\/banner\/bak01.jpg","img\/banner\/bak02.jpg","img\/banner\/bak03.jpg"]
// This is not a good syntax to initialize our javascript URLs array
?>
I have this little php snippet:
// $test='test';
$test='just a test';
echo "<a href=javascript:myfunction($number,$src_req,\"".$test."\")><img style='z-index:$z; src='images/$src'/></a>";
And i have this little ajax snippet...
function myfunction(param1,param2,param3)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse2(xmlHttp.responseText);
}
}
var p1=param1;
var p2=param2;
var p3=param3;
xmlHttp.open("GET", "config/ajax_pop.php", true);
xmlHttp.send(null);
$( '#ResponseDiv2' ).dialog({
height: 140,
modal: true,
position: [490,140],
title:param3,
});
.....
I like to pass my $test php variable to my javascript function, but unfortunatelly if my $test variable contain space character then the JS script doesnt work. If my $test variable contain only one word, then work well.
In the browser when i check the link i see:
a, if $test variable contain only one word, then: javascript:myfunction(1,1,"test")
b, if $test variable contain more then one words then: javascript:myfunction(1,1,"just
Thank you for the help...
Use json_encode(): http://php.net/json_encode
Update: Here's a usage example:
<?php
$number = 1;
$src_req = 2;
$z = 3;
$src = 4;
$test = 'just a test
with spaces and new lines';
echo "<a href=javascript:myfunction($number,$src_req," . json_encode($test) .")><img style='z-index:$z; src='images/$src'/></a>";
If it doesn't work, try to find out in what exact way it's not working. A "Does not work" question is as useful as a "Then fix it" answer.
In any case, mixing PHP, HTML, JavaScript and CSS in one single line of code is not worth the effort even for quick testing. Separarte stuff in functions and files you'll make your life easier.
You must wrap the href itself with double quotes then the value with single quotes:
href=\"javascript:myfunction($number, $src_req, '".$test."')\"
You can escape the string with php function urlencode and can use javascripts unescape to unescape.
you have to parse the third parameter in your js function with unescape ...
as well you can use json as Álvaro G. Vicario mentioned.
I have the following line of code:
My Tweets!
Now while this is working perfectly fine the following line is not:
My Tweets!
Can anyone help me out why it is not working and suggest any changes? The variable I want to pass to the Javascript function is a PHP variable. I have tried the PHP with single quotes and double quotes but it is not working.
You need quotes for both the php side and the Javascript side. You've only got php quotes there.
My Tweets!
looks weird but it should work, though I'm no php expert. Note that if there's any chance that "myid" (on the php side) might contain user-supplied data (like, something that came from an <input> field at some time), or if it's otherwise unpredictable, then it has to be put through something on the server side to make sure that the resulting tag is "clean".
I usually do as following:
<script>
var jsvar = <?=json_encode($php_var)?>;
</script>
After that I can use jsvar under the javascript codes. And for readability I usually place all those assignments in an own script tag.
What you gain by using <?=json_encode($php_var)?> is that you won't need to go on escaping, and it works for arrays and hashes as well as strings, numbers etc...
For example, following php code:
<?php
$php_string = "hello";
$php_array = array( 'a', 'b', 'c' );
$php_hash = array( 'a' => 1, 'b' => 16, 'c' => 42 );
$php_number = 123;
$php_bool = false;
$php_null = null;
?>
<script type="text/javascript">
var js_string = <?=json_encode($php_string)?>;
var js_array = <?=json_encode($php_array)?>;
var js_hash = <?=json_encode($php_hash)?>;
var js_number = <?=json_encode($php_number)?>;
var js_bool = <?=json_encode($php_bool)?>;
var js_null = <?=json_encode($php_null)?>;
</script>
produces the following result:
<script type="text/javascript">
var js_string = "hello";
var js_array = ["a","b","c"];
var js_hash = {"a":1,"b":16,"c":42};
var js_number = 123;
var js_bool = false;
var js_null = null;
</script>
You forgot to Quote your answer. You are echoing the string OK, but you need to ' ' the response so JavaScript will know it's a string. You can use ' or \"
My Tweets!
Uses short echo thing.