Parsing php values to javascript Uncaught ReferenceError [duplicate] - php

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript echo’d by PHP doesn’t run
In the following code I am parsing values from a php table into a javascript function, however I am getting an Uncaught ReferenceError: "the php text" is not defined (anonymous function)
<html>
<script type="text/javascript">
function draw(name ) {
alert(name);
}
</script>
<body>
<canvas id="mycanvas" width=800 height=400></canvas>
</body>
</html>
<?php
$query = 'SELECT * FROM graph_table';
$result = mysql_query($query);
while($val = mysql_fetch_array($result)) {
$name = $val['test_name'];
echo '<script type="text/javascript"> draw('.$name .'); </script>';
}
?>

You need to add quote's between draw since you're passing text to it. draw(\''.$name.'\'); will make your problem go away.

Try this
<script type="text/javascript">
<?php
$query = 'SELECT * FROM graph_table';
$result = mysql_query($query);
while($val = mysql_fetch_array($result)) {
$name = $val['test_name'];
echo "draw('$name');";
}
?>
</script>

Try the php script inside . Mainly you should add js script just before .

Related

Using PHP to determine what HTML to write out

This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>

reading Json from PHP with javaScript

My PHP code is:
<?php
class Sample{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) ){
echo "Starting to read ";
$req = $_GET[ 'request' ];
$result = json_decode($req);
if( $result->request == "Sample" ){
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}else{
echo "Not Supported";
}
}
?>
Is there anything wrong
I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!
I tried using
$.getJSON('server.php',request={'request': 'Sample'}) )
but php can't read this input or it's wrong somehow
thank you
try this out. It uses jQuery to load contents output from a server URL
<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(event) {
$('#responce').load('php_code.php?request={"request":"Sample"}');
});
});
</script>
</head>
<body>
<p>Click on the button to load results from php_code.php:</p>
<div id="responce" style="background-color:yellow;padding:5px 15px">
Waiting...
</div>
<input type="button" id="button" value="Load Data" />
</body>
</html>
Code below is an amended version of your code. Store in a file called php_code.php, store in the same directory as the above and test away.
<?php
class Sample
{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) )
{
echo "Starting to read ";
$req = $_GET['request'];
$result = json_decode($req);
if( isset($result->request) && $result->request == "Sample" )
{
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}
else
{
echo "Not Supported";
}
}
Let me know how you get on
It would be as simple as:
$.getJSON('/path/to/php/server.php',
{request: JSON.stringify({request: 'Sample'})}).done(function (data) {
console.log(data);
});
You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.
You're on the right path; PHP outputs a result and you use AJAX to get that result. When you view it in a browser, it'll naturally show you an HTML result due to your browser's interpretation of the JSON data.
To get that data into JavaScript, use jQuery.get():
$.get('output.html', function(data) {
var importedData = data;
console.log('Shiny daya: ' + importedData);
});

Pass a php var to jQuery Function

How do I pass a variable in a php file that is loaded into a page (DOM) to a jQuery function??
Iv'e tried various method's while searching online but I haven't figured out how to use them correctly.
I need the var navHeaderTitle to be passes to the jQuery load() callback function so it sets the HTML tag, #navHeaderTitle, to the variable called in the php file.
Thnx for you help.
php:
<?php
$con = mysql_connect("localhost","user","pw");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result = mysql_query("SELECT * FROM some_list");
$navHeaderTitle = "MY NEW TITLE";//<--I NEED 2 INJECT THIS!!
while($row = mysql_fetch_array($result))
{
echo "<div id='navItem' title='$navHeaderTitle'>";
echo "<h1>" . $row['label'] . "</h1>";
echo "<h2>" . $row['title'] . "</h2>";
echo "<p>" . $row['description'] . "</p>";
echo "</div>";
}
mysql_close($con);
?>
JavaScript in the HTML Head:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function() {
$('#navHeaderTitle').text($(html).find('div#navItem').attr('title'));//<--GET THE VAR FROM LOADED PHP FILE!!
});
});
</script>
<body>
<div id="navPanel">
<div id="navHeader">
<img src="images/ic_return.png" style="float: left;"/>
<img id="listSortBtn" src="images/ic_list_sort.png" style="float: right;"/>
<h4 id="navHeaderTitle"></h4>//THIS IS WHAT NEEDS THE VAR DATA!!
</div>
<div id="navScrollContainer" class="navContentPosition">
<div id="navContent">HTML CONTENT from PHP GETS DUMPED IN HERE</div>
</div>
</div>
</body>
Ive tried using this but not sure how to:
$.get('scripts/my_list.php', {}, function(data){
data = split(':');
})
I would have the php file return a json object that contains two parts, the html you want to echo and the title you want to use.
Then I would use jQuery's .ajax() function instead of .load() to get the return value from your php script in a javascript variable instead of dumping it directly as .load() does.
replace echo("$navHeaderTitle"); with
echo("<script> var navHeaderTitle = $navHeaderTitle </script>");
and remove var navHeaderTitle = ''; from the <head> script..
that will setup a JS variable like you're using, but you have to do that before the code in the <head> loads...
EDIT
ok don't echo("$navHeaderTitle"); you can put it into the HTML like:
echo "<div id='navItem' title='$navHeaderTitle'>";
then in the JS you can do:
<script type="text/javascript">
var navHeaderTitle = '';
$(document).ready(
function() {
$("#navContent").load('http://url/my_list.php', function(response) {
$('#navHeaderTitle').text($(response).attr('title'));
});
});
</script>
here's a jsfiddle demo: http://jsfiddle.net/JKirchartz/hdBzF/ (it's using fiddle's /echo/html/ so the load has some extra stuff to emulate the ajax)
It would be cleaner to pass the var in a custom attribute (data-var), then fetch it width JQuery
$(some_element).attr("data-var");
I hate to mess my JS code with php.

Syntax error help

I seem to have a syntax error and can't see it myself, could someone run over it for me please?
Thanks.
<script>
var acurl_<?php echo $request_data['friendship_id']; ?> = "sn-include/create_bond_accept.php?friendship_id=<?php echo $request_data['friendship_id']; ?>&friend_id=<?php echo $fromuser['id']; ?>";
</script>
Because you got some answers that intended to show you how to improve your code, but actually don't do so (IMO), here is my attempt:
<?php
$acurl = array();
$acurl[$request_data['friendship_id']] = sprintf('sn-include/create_bond_accept.php?friendship_id=%s&friend_id=%s', $request_data['friendship_id'], $fromuser['id']);
?>
<script>
var acurl = <?php echo json_encode($acurl); ?>
</script>
I would not create dynamic variable names. This code would create a JS object, where the properties are the friendship IDs, something like:
{
'42': 'sn-include/create_bond_accept...'
}
You can access these URLs more easily from JavaScript than if you have dynamic variable names.
David, on the bright side, you don't have a syntax error.
If you're developing PHP, I would recommend two things:
Get a better IDE. Dreamweaver is TERRIBLE for working with PHP. I recommend NetBeans (it's awesome and free).
Start breaking up your code into chunks. The big ball of html and PHP is hard to debug.
Check this out:
<?php
// prepare output
$segment = '?friendship_id=' . $request_data['friendship_id'];
$segment .= '&friend_id=' . $fromuser['id'] . '";' . "\n";
$acurl = 'var acurl_' . $request_data['friendship_id'];
$acurl .= ' = "sn-include/create_bond_accept.php';
$acurl .= $segment;
$dnurl = 'var dnurl_' . $request_data['friendship_id'];
$dnurl .= ' = "sn-include/create_bond_deny.php';
$dnurl .= $segment;
?>
<script type="text/javascript">
<?php
echo $acurl;
echo $dnurl;
?>
</script>
Use here doc instead:
<?php
echo <<<JS
<script>
var acurl_{$request_data['friendship_id']} = "sn-include/create_bond_accept.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>
<script>
var dnurl_{$request_data['friendship_id']} = "sn-include/create_bond_deny.php?friendship_id={$request_data['friendship_id']}&friend_id={$fromuser['id']}";
</script>
JS;
?>
See http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc

Unable to retrieve json data using jquery

i am a newbie and am stuck at retrieving json data.
following is my index.php :
<script type="text/javascript" src="jquery-1.3.2.min_2.js">
$("document").ready(function() {
$.getJSON("data.php",function(jsondata){
$("#content").html(jsondata[0].content);
});
});
</script>
</head>
<body>
<div id="content"></div>
<div class="lg"></div>
</body>
in my data.php i am using the standard way of encoding and sending the data:
// execute query
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error());
$row = mysql_fetch_row($result);
$jsonserver[$i] = $row;
}
echo json_encode($jsonserver);
header('Content-type: application/json');
mysql_free_result($result);
// close connection
mysql_close($con);
i am using mysql database.
when i open localhost/data.php the json data is shown on the browser.
but in case if i open localhost/index.php i donot get any desired output.
Please explain.
Thanks!
you need to put all headers before any 'echo's on the page
so:
header('Content-type: application/json');
echo json_encode($jsonserver);
Hey,
u didn't close script tag properly
try
<script type="text/javascript" src="jquery-1.3.2.min_2.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$.getJSON("data.php",function(jsondata){
$("#content").html(jsondata[0].content);
});
});
</script>

Categories