Jquery to parse HTML in a string - php

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

Related

Read data from mysql and pass variable to jquery function, write in a textarea, not work

I am a beginner in jquery. I'm sorry for my english.
I read data from mysql:
$id=($row["ID"]);
$name=($row["Name"]);
$note=($row["Note"]); *// note set to textarea*
send function:
onclick= modP($id,$name,$note);
<script>
function modP(id,name,note){
$("#NoteP").val(note);
}
</script>
----- PROBLEM -------
NoteP is textarea.
if $note has one line the function work. all OK.
if $note has many lines the function modP is not called.
I tried with:
$note = str_replace("\n","<br />", $row["Note"]);
Not work!
Please help me. Thank you.
Try to encode your string to JSON in the PHP part then decode in JS part.
PHP :
$note= json_encode($row["Note"]);
JS :
$("#NoteP").val( JSON.parse(note) );
use nl2br on $note to break multines as below.
$id=$row["ID"];
$name=$row["Name"];
$note=$row["Note"];
$note=nl2br($note);
You can call onclick function on your html element as below.
<button onClick="modP('<?php echo $id ?>','<?php echo $name ?>','<?php echo $note ?>');">Click</button>
And the modP function will be as shown below.
<script type="text/javascript">
function modP(id,name,note) {
$("#NoteP").val(note);;
}
</script>
I hope this helps.
I found this suggestion
Link
Jquery function does not accept variables on multiple lines.
$note=str_replace("\n","<br />",$row["Note"]);
Now the function is called correctly.
($note) is one line.
How can I write textarea restoring original text, with many lines?
$note = json_encode($row["Note"], JSON_HEX_QUOT | JSON_HEX_TAG);
// note set to textarea - multiline
pass $data to the function modPaziente:
echo("<td><input name=\"imgmodifica\" id=\"imgmodifica\" type=\"image\" src=\"image/modifica2.png\" width=\"24\" height=\"24\" title=\"Elimina ".$row["ID_P"]."\" onclick=\"return modPaziente('$id','$nom','$ind','$comID','$citta','$prov','$tel','$cf','$ese','$cons','$nato','$sesso','".$note."','$eta')\"> </input></td>");
JS - /* alert(note) NOT work */
<script type="text/javascript">
function modPaziente(id,nom,ind,comID,citta,prov,tel,cf,ese,cons,nato,sesso,note,eta){
alert(note);
}
</script>
why modPaziente does not read note?
I solved that with htmlspecialchars and json_encode :
$note = htmlspecialchars(json_encode($row["Note"], JSON_HEX_QUOT | JSON_HEX_TAG));
...without quotes $note
onclick="return modPaziente($note);"
....
<script type="text/javascript">
function modPaziente(note){
alert(note);
}
Thank you all for the suggestions

using javascript quotes in php code

i'm having some trouble using javasript in php code, I'm confused in using double quotes and single quotes.
echo 'Delete';
or how to do the above code in php ?.
Thanks
use this code
echo 'Delete';
you have to escape the quotes.
http://viper-7.com/F6uI0L
You need to escape the quotes with htmlspecialchars (for HTML):
echo '<a href="..." onclick="return confirm('
.htmlspecialchars('"Are you sure"') . '">Delete</a>';
(alternatively you could just write ")
...but don't do that. Use JS event registration:
document.getElementById('a-id').addEventListener('click', function (e) {
if (!confirm("Are you sure...")) {
e.preventDefault();
}
});
Do that in JS file. It requires that the <a> have an ID (you could also do it with a host of other selectors, but ID is the simplest).
Change like following
echo "Delete";
Why don't you put the HTML outside of PHP tags? For example you could do:
...
?>
Delete
<?php
...
Another way to echo HTML is:
echo <<<HTML
Delete
HTML
Error in confirm("Are you sure you want to delete?")"> you need to escape double quote.
You need to call the javascript function using php echo
echo 'href_link';
...but you have to use JS function
<html><head><script type="text/javascript">
function fun()
{
if(confirm('are you sure')) return TRUE;
else return FALSE;
}
</script>
</head>
<body></body>
</html>

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

weird error of loading mysql data to javascript variable using php

I have accessed a database and fetched data (to make it simple, let's assume only one data), the data is an array and has one field 'link', which is a url.
I pass the value of $data['link'] to a php variable $l1; to compare, I also pass the actual url to another varibale $l2.
Then the next two lines try to pass the value to javascript variable. If I remove the first line (echo "var link1 = \"$l1\";";), it works; if I keep the first line, it doesn't (alert dialog not shown). I think it is the problem of the url, but the value of $l2 is exactly the same as $data['link'], the next two lines also appear the same in the source code of the html page.
Code is here:
<script type="text/javascript">
function readData() {
alert('haha1');
<?php
$l1 = $data['link'];
$l2 = "http://upload.wikimedia.org/wikipedia/commons/1/17/Affenpinscher.jpg";
echo "var link1 = \"$l1\";";
echo "var link2 = \"$l2\";";
?>
alert('haha2');
}
</script>
<body onload="readData();"></body>
Anyone have any idea why this happen? Thanks for helping!
I'm not sure whether I've understood your doubt. At any case, from intuition, I'd try out something like this:
<script type="text/javascript">
function readData() {
alert('haha1');
<?php
$l1 = json_encode($data['link']);
$l2 = "http://upload.wikimedia.org/wikipedia/commons/1/17/Affenpinscher.jpg";
echo "var link1 = ".$l1.";";
echo "var link2 = \"$l2\";";
?>
alert('haha2');
}
</script>
<body onload="readData();"></body>
Your URL might be "malformed" for javascript; and cause a parse error.
Let us know if this was the case...

echoing a jquery animation function with php

I am trying to echo this jquery function, with php. basically if the script detects a field of a form is not filled in then it will echo this and make the input text box turn red.
It works fine when it is not being echo'd.
echo('
<script type="text/javascript">
$(document).ready(function() {
$(\'input\').animate({backgroundColor:\"#F00\"},200);
});
</script>
');
any ideas?
I don't think you have to escape your quotes when the string is within single quotes. PHP won't parse the string, it will be output literally.
You're over-doing it on the string escape. To keep it simple, just use single quotes around the echoed string, and use double quotes inside it. Something like:
echo('
<script type="text/javascript">
$(document).ready(function() {
$("input").animate({backgroundColor: "#F00"}, 200);
});
</script>
');
When you're echoing stuff, there are indeed some cases when you need to escape the quotes, but most of the times you can simply get away with it by using different types of quotes. For example, I'll never get it why people still do something like:
echo "<input type=\"text\" name=\"username\">";
as opposed to
echo '<input type="text" name="username">';
which makes your life a whole lot easier when you have to modify it.
Hope this helps !
You shouldn't use \" there, just "
Furthermore: a hex-color-value is no numeric value you can use for animate() .
By this, the error is fixed by removing the backslashes from the doublequotes, but your animation wouldn't show any effect.
i didnt test it, but try that:
$nl = "\n";
echo '<script type="text/javascript">'.$nl;
echo ' $(document).ready(function() {'.$nl;
echo ' $("input").animate({backgroundColor:"#F00"},200);'.$nl;
echo ' });'.$nl;
echo '</script>'.$nl;
the $nl="\n" is only for linebreak (I prefer to use singlequotes in echos, so php didn't have to parse the content - just echo out).

Categories