Placing PHP within Javascript - php

I can't seem to get the PHP to echo out within a Javascript tag:
places.push(new google.maps.LatLng("<?php echo the_field('lat', 1878); ?>"));
What am I doing wrong?

Have you tried it without the quotes ?
places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));

PHP works when you execute the page, and it should work.
Please note that php does not execute when you run a JS function.
Please also make sure that you really have that the_field function.

I suspect you have your " quotes in the LatLng method arguments when there shouldn't be any.
Your php should output a string such as '50.123123123, 12.123144' (without the ' quotes). The LatLng method expects 2 values.
places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));
Try that.

If you're looking to populate a Google Map with markers as the result of a database query, you probably want to wrap it in a JSON web service. Something as simple as:
<?php
// file to query database and grab palces
// do database connection
$places = array();
$sql = "SELECT * FROM places";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$places[] = $row;
}
header('Content-Type: application/json');
echo json_encode($places);
exit;
And then in your JavaScript file:
// get places
$.getJSON('getplaces.php', function(response) {
for (var i = 0; i < response.length; i++) {
place[] = response[i];
places.push(new google.maps.LatLng(place.lat, place.lng));
}
});

If i understand what you are trying to do (maybe some more explanation of your problem is required for this), then this might be your answer:
places.push(new google.maps.LatLng(<?php echo '"' . the_field('lat', 1878) . '"' ?>));
EDIT: removed the ;

Related

Generating Javascript variables using php

I was trying to generate a Javascript varialbe using php. I am getting the desired result on the source page but it looks like that result is not being processed into the array. Is there any way of doing it using javascript? Here, I'm generating URLs for images that need to be displayed on my website carousel and though a for loop would save me the time of entering every url. The images are also number serially. Since I'm not well versed in javascript can you suggest me a javascript alternative?
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>
You can do it using javascript only. No reason for using PHP here.
var leftrightslide = new Array()
var finalslide = ''; // this line is not really relevant to the question
for (var i = 0; i < 34; i++){
var j = i + 1;
leftrightslide[i] = '<img src="../images/'+ j +'.jpg" border="0">';
}
echo "leftrightslide[".$i."]='<img src=\"../images/".$j.".jpg\" border=0>';";
Here's a snippet of code that I use to move data from PHP To JS
if (isset($javascriptData)) {
echo "<script>";
foreach(array_keys($javascriptData) as $jsData) {
echo "var " . $jsData . " = " . json_encode($javascriptData[$jsData]) . ";\n";
}
echo "</script>";
}
I pass in $javascriptData to my view which is an array with the structure array('JS_VAR_NAME' => 'JS_VALUE')
You can then use those variables in any scripts you've added below that
Since your example code contains no script tags, or other HTML elements for that matter, one might assume that this PHP snippet is intended to generate some JavaScript source "file" external to the page in which it is being used.
If that is the case, consider that the following additional line may just fix it:
<?php header( 'Content-Type: text/javascript' ); ?>
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>

Pass Jquery + Php search back to javascript?

I have a javascript function as follows::
//THIS IS javascript.js
function dosomething(data){
//splits and do something else
}
$(document).ready(function () {
dosomething();
}
Below is a php file from search(database search with jquery and ajax)
//THIS IS mysearch.php
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$url = $row['url'];
$text = $row['text'];
$argument = $url"."$separator"."$text";
);
How do I pass $argument to javascript function? I have tried something like this.
echo '<p>'.$text.'</p>';
What would be good way to approach this?
Any help would be appreciated! Thanks in advance!!
This should do the trick:
echo '<p>'.$text.'</p>';
// Edit:
If you run into problems with special characters like öäü… you can use json_encode()
A lot of people like using json and ajax.
http://api.jquery.com/jQuery.getJSON/
http://php.net/manual/en/function.json-encode.php

Can't show the output in html

I have a function wich prints a number of credits:
<?php
function selectCredits()
{
include 'sqlvars.php';
$con = mysql_connect("localhost","bbbb","bbbb");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("bbbb", $con);
$result = mysql_query($selectCredits);
while($row = mysql_fetch_array($result)){
echo $row['credits'];
}
}
?>
When I'm calling it from a php file by using:
<?php
include 'sql.php';
selectCredits();
?>
I can see the output, but when I'm inside of a HTML document I can't get the result using this code:
<center><b>Your credits: </b></center> <?php include 'sql.php'; selectCredits(); ?>
The output is always: Your credits: without the query result.
For sure I'm missing somthing really small. I'm not a php guy, but I'm willing to learn it, already lost an hour without any success.
If you really want html files to execute php code, try to add this line to htaccess:
AddType application/x-httpd-php .html
check your query statement '$selectCredits'. check table name and attribute name-'credits'. The $row['credits'] is not getting its value.
You have a problem in your code. You have written
while($row = mysql_fetch_array($result)){
echo $row['credits'];
}
You have used mysql_fetch_array and you have echoed $row with attribute value directly. If you are using mysql_fetch_array, then use $row[0], $row[1] or $row[2] etc. All the attributes come as an array. Thats why you should treat it as array index value. So, if "credit" attribute is at the 5th column in your database, then you should echo it as
echo $row['4'];
If you use mysql_fetch_assoc() instead of mysql_fetch_array, then you can write the attribute name directly.
E.g. then you can write
echo $row['credits'];
I hope, this will solve the issue. Please ask me if you have any further questions.
You should use a JavaScript tag to implement the PHP file like this:
<script type="text/javascript" src="credits.php"></script>
credits.php would have to output:
echo "document.write('" . $row['credits'] . "');";
Simple :)

PHP array to echo javascript array that I can access?

I have a php array called $user.
At the minute I am getting the variables across to javascript by manually adding them like so.
var username = ' . $user['username'] . ';
And so on is there a way I can make php echo a javascript array that I can access?
You're looking for json_encode
PHP:
$json_user = json_encode($user);
JavaScript:
var user = JSON.parse('<?php echo $json_user; ?>');
That's untested code but the idea behind it is sound
Have you tried json_encode ?
<?php echo json_encode ( $array ); ?>
See the documentation here.

Jquery to parse HTML in a string

I tried searching the related posts, and having a hard time figuring out how to fix my query - I'm pretty close, any help is much appreciated (new to Jquery).
I program in PHP, and trying to pull either the HREF value from a tag, or the text. Either will work.
I basically have my HTML code in a string, might contain multiple tags, and would like to load the text of the tags into either a PHP array or variable (right now just trying to ALERT the results, I can dump it later).
My PHP Code:
<?php
$info = '<li><strong>I want this text</strong>';
echo '<script type="text/javascript">';
echo '$("document").ready( function () {';
echo 'alert($("a", $("' . $info . '")).html());';
echo '});';
echo '</script>';
?>
The above doesn't alert anything. Putting in
echo 'alert("yes")';
does work, so I'm guessing there's something basic wrong with my syntax, but 4 hours later still unable to find it! :)
Thanks in advance.
You aren't Javascript-escaping the quotes in your string.
Your code creates Javascript that looks like
$("<li>...<a href="http..."...")
The quotes in the attribute end the Javascript string, creating a syntax error.
You need to call json_encode.
SLaks has the rest of your problem. But also, it's not:
$("document").ready();
It's:
$(document).ready();
The former is a selector for a tag named <document>.
This should work the way you want it to:
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready( function () {
alert($("a", $("<?php echo $info; ?>")).html());
});
</script>
You are not closing your li Tag
$info = '<li><strong>I want this text</strong>';
should be
$info = '<li><strong>I want this text</strong></li>';
You should escape info. It's breaking because you've got double quotes inside of double quotes:
$info = addslashes($info);
or
$info = json_encode($info);
or just
$info = str_replace('"', '\\"');
Try to save the HTML is a JS variable first, then use it. Also, heredocs are your friend.
<?php
$info = '<li><strong>I want this text</strong></li>';
echo <<<END
<script type="text/javascript">
$(function(){
var HTML = '$info';
alert($('a', $(HTML)).html());
});
</script>
END;
?>
echo '<script type="text/javascript">
$(document).ready( function () {
var info = \''.$info.'\';
$("a").html(info);
alert(info);
});
</script>';

Categories