Echo javascript function - php

I am tryaing to to make this echo work, but i cant get the grip of it
echo '<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class="sml" src="$1" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);';
echo "</script>";
What am i doing wrong? i think i got something wrong with my " ' .

There was a couple of issues. I started by just running it in JavaScript until I got it to work, then moved it into PHP (for the sake of sanity).
<?php
print '
<script>
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9#:%_\+.~#?&\/\/=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&\/\/=]*)?(?:jpg|jpeg|gif|png))/gi;
return txt.replace(linkRegex, "<img class=\"sml\" src=\"$1\" /><br />");
}
var newHTML = replaceWithImgLinks($(".ms").html());
$(".ms").html(newHTML);
</script>';
?>

Shouldn't the regex be something like:
(^|\b)((https?:)?\/\/[^\s]*?\.(jpe?g|png|gif))(\b|$)
Debuggex Demo

You shouldn't be echo'ing scripts, especially scripts in script tags. I would seriously look into just using your back end to fetch, then use an asynchronous technology that fetches data parsed JSON. That way you can call your scripts normally.

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>

PHP/JQUERY- Can't return data from a query

I'm doing a project for an exam. I'm stuck with that and I hope someone of you could help me (I'm italian, so sorry for my bad english!).
I have to query an existing database stored in phpmyadmin with a PHP script. Then, the query result need to be parsed with a jquery script and printed to an HTML page.
Here is the PHP script:
<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Errore di connessione: ' . mysql_error());
}
mysql_select_db("progetto_lpw", $con);
$sql="SELECT denominazione FROM farmacia";
$result = mysql_query($sql) or die(mysql_error());
$num=mysql_numrows($result);
while($row = mysql_fetch_array($result)){
print json_encode($row['denominazione']);
print "<br />";
}
?>
I've already tested the PHP script calling it via browser and it works.
Then, I parse the result with this jquery script (the use of this combination is a requirement of the project):
$("#button").click(function(){
$.getJSON('json.php', function(data) {
$.each(data, function(index,value){
$("#xx").append("<p>"+value+"</p>")
})
})
})
Here is the problem: when I open the HTML page and I click the button on firefox, consolle says "no element found" referring to PHP script.
"xx" is the id of the div in which elements are printed.
Where is the error?
Thanks to everyone.
Replace below code
while ($row = mysql_fetch_array($result)) {
print json_encode($row['denominazione']);
print "<br />";
}
With below code and try
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row['denominazione'];
}
header('Content-type: application/json');
echo json_encode($rows);
HTML
<button id="button">Fetch JSON</button>
<div id="xx"></div>
JS
$("#button").click(function() {
$.getJSON('json.php', function(data) {
$.each(data, function(index, value) {
$("#xx").append("<p>" + value + "</p>")
});
});
});
Response from json.php should be in below format
["AGGERI","ALCHEMICA 1961"]
The reason your code isn't working is that it's producing output like this:
"foo"<br />
"bar"<br />
That's not valid JSON. To be valid, you have to not have the HTML <br /> in there (this is JSON, not HTML), and you have to have commas between the elements you want to return.
json_encode will handle formatting the array correctly for you.
jsFiddle Demo with post request to send and get json output
'print' works differently then 'echo'. At least i am sending JSON packages with echo from php.
Can you replace it ?
// in php
echo json_encode($row['denominazione']);
// in jquery script, best to place "<br />" tag here
$("#xx").append("<p>"+value+"</p><br />")

best way to encode javascript with php for ajax?

The following PHP function outputs JS:
function dothething( $data ){
$res = "
<div id=\"blah\">
Here's some stuff, ". $data['name'] ."
</div>";
echo "$('#container').html('". $res ."');";
}
This function is called via jQuery's $.ajax(), using dataType: 'script' ... so whatever is echoed runs like a JS function. There's more to it of course, but my question has to do with encoding. The ajax will fail when $res contains newlines or apostrophes. So adding this above the echo seems to be working for now:
$res = str_replace("\n", "\\n", addslashes($res));
Is this the best way to format the PHP variable $res to yield valid javascript for ajax?
Is there anything else I should add in there?
In your case I would use json_encode() over anything else:
echo "$('#container').html(" . json_encode($res) . ");";
When applied to a string value, it will automatically encapsulate it with double quotes and escape anything inside that would otherwise cause a parse error.
Try this,
if(count($result)>0) {
$status = 0;
} else {
$status = 1;
}
$json['status'] = $status;
$json['result'] = $output;
print(json_encode($json));

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

very simple javascript failing

Working Example:
This is almost identical to code I use in another places on my page but fails here for some reason.
<?php
//$p = "test";
?>
<script>
alert('posts are firing? ');
parent.document.getElementById('posts').innerHTML = "test";
</script>
Failing example: (alert still works)
<?php
$p = "test of the var";
?>
<script>
alert('posts are firing? ');
parent.document.getElementById('posts').innerHTML = '<?php $p; ?>';
</script>
Try
'<?php echo $p; ?>';
or
'<?= $p ?>';
Debugging 101: Start checking all variable values.
alert(parent);
alert(parent.document);
alert(parent.document.getElementById('posts'));
as well as the value rendered by: '<?php $p; ?>'
Make sure your 'posts' object (I guess it is DIV or SPAN) loads before you fill it using javascript.
You're trying to generate javascript with php, here I use a simple echo:
<?php
$p = "test of the var";
echo"
<div id='posts'></div>
<script type='text/javascript'>
var posts = document.getElementById('posts');
posts.innerHTML = '$p';
</script>
";
?>
Note the $p and that the div is printed before the javascript!
You are not outputting the variable data is why it isn't working. You need to echo or print the variable $p.
In your example the $p is being evaluated, not printed.
To print it you should use print, echo, or the syntax <\?=$p;?>. without the \

Categories