PHP javascript call with PHP variable - php

Good day, I am having a very odd error with my PHP code. I am attempting to dynamically change the content of my webpage by reading from an xml file. I read in some data and assign the data to a PHP variable called $course_title and then attempt to call some Javascript that will update the "innerHTML" of a DOM element. Note: on the line "echo $course_title;' that prints out the correct data to the screen.
$fn = dirname(__FILE__)."/course.xml";
$xml = simplexml_load_file($fn);
$course_bookimagelocation = "";
foreach ($xml->children() as $child)
{
if($child[0]->getName()=="book")
$course_bookimagelocation = $child;
if($child[0]->getName()=="title")
$course_title = $child;
}
//Problems start here...
echo $course_title;
echo '<script type="text/javascript">document.getElementById("heading").innerHTML = "';
echo $course_title;
echo '";</script>';
What is very unique is that the first echo statement prints the correct information, but the next three lines, the .innerHTML does not get changed to that same value. Does anyone know what that is? What is also weird is that if I replace the second "echo '$course_title';" with something like 'Hello world!' then "Hello World!" appears as the innerHTML of the "heading" id object.
EDIT
In the XML file called course.xml, the title element is IC 210 Fall 2010 and the contents of $course_title is IC 210 Fall 2010 so the parsing of the php file appears to be correct and there does not seam to be any special characters like a " or '
I also tried putting everything on the same line and not luck... (I even made sure in the xml file that the <title> element had the text on the same line...

Make sure that .innerHTML = "Some text" are on the same line because .innerHTML = "\nSome Text\n" won't work in javascript.
If you want to have something like this:
.innerHTML = "
Some String
";
try:
.innerHTML = ""+
"Some String" +
"";

"call some Javascript that will update the "innerHTML" of a DOM element." for that we use AJAX, no?
well you can do that way but i think it would be simpler to have the text preloaded in some hidden DIV's and use your functions just to change content's of the DIVS or even toggle visibility of the DIV (as you prefer). That way you will avoid many escaping problem's referred in the comments.
that's the way i would do it if not to use AJAX

Related

use selector search on html code(string) on PHP variable or ways alike

what im currently doing is i have a text area for user to copy and paste the html code.
i want to get a certain element of that html file.
in pure html, this can be done via jquery selector
but i think its a whole different thing when html code is on a variable and considered as a string.
how can i get a certain element location in that way?
code is:
function searchHtml() {
$html = $_POST; // text area input contains html code
$selector = "#rso > div > div > div:nth-child(1) > div > h3 > a"; //example - the a element with hello world
$getValue = getValueBySelector($selector); //will return hello world
}
function getValueBySelector($selector) {
//what will i do here?
}
searchHtml();
You can look at SimpleHTMLDom Parser (manual at http://simplehtmldom.sourceforge.net/manual.htm). This is a powerful tool to parse the HTML code to find and extract various elements and their attribute.
For your particular case, you can use
// Create a DOM object from the input string
$htmlDom = str_get_html($html);
// Find the required element
$e = $htmlDom->find($selector);
Oh, and you've to pass the provided input value to the getValueBySelector() function :-)

Weird passing php string to javascript sometimes not work

how i what it to work:
goal: make a album viewer without reload the page, with a img html element, change img SRC dynamically with javascript, but image url's stored in php variables and what copy to javascript array.
Problem: example have album where have 17 picture, if i echo in php then $i count from 1-17 but in javascript count to 2-12 and 15-17 so ignore 1,13,14 etc. have no ideea why because no difference in data, so DataPicId[13] is undefined but 15th index or 12th index got value normally.
while($row = mysql_fetch_array($SQLpic))
{
$i=$i+1;
$PicId=$row['id'];
$Url=$row['url'];
$Desc=" ".$row['description'];
$UpUser=$row['uploader'];
$Update=$row['udate'];
echo"<script>
nr=Number('".$i."');alert(nr);
DataPicId[nr]=Number('".$PicId."');
DataPicUrl[nr]='".$Url."';
DataPicDesc[nr]='".$Desc."';
DataPicUser[nr]=Number('".$UpUser."');
DataPicDate[nr]='".$Update."';
alert(DataPicUrl[nr]);
</script>";
$ThumbUrl=GetNameOnly($Url);
echo "<div id='PicBoxOut'>
<div id='PicBoxIn' onclick=SelectSrc('".$i."');>
<a href='javascript:void(0);'>
<img src='".$ThumbUrl."' border='0'></a>
</div></div>";
Without seeing the generated html / javascript, I would guess that your variables are breaking your javascript. That could be for example a single quote in the description of a photo.
To make sure that you output valid javascript, it is better to send your complete row-set to javascript as json and build your html in javascript using that json.
So something like:
<?php
// Note that normally you would have done this already in a controller
// and not when you are outputting html
$rows = array();
while($row = mysql_fetch_array($SQLpic))
{
$rows[] = $row;
}
?>
<script>
var json = <?php echo json_encode($rows); ?>,
object = JSON.parse(json);
// now `object` will contain all your rows in a javascript object / array
</script>

Save the contents of manipulated div to a variable and pass to php file

I have tried to use AJAX, but nothing I come up with seems to work correctly. I am creating a menu editor. I echo part of a file using php and manipulate it using javascript/jquery/ajax (I found the code for that here: http://www.prodevtips.com/2010/03/07/jquery-drag-and-drop-to-sort-tree/). Now I need to get the edited contents of the div (which has an unordered list in it) I am echoing and save it to a variable so I can write it to the file again. I couldn't get that resource's code to work so I'm trying to come up with another solution.
If there is a code I can put into the $("#save").click(function(){ }); part of the javascript file, that would work, but the .post doesn't seem to want to work for me. If there is a way to initiate a php preg_match in an onclick, that would be the easiest.
Any help would be greatly appreciated.
The code to get the file contents.
<button id="save">Save</button>
<div id="printOut"></div>
<?php
$header = file_get_contents('../../../yardworks/content_pages/header.html');
preg_match('/<div id="nav">(.*?)<\/div>/si', $header, $list);
$tree = $list[0];
echo $tree;
?>
The code to process the new div and send to php file.
$("#save").click(function(){
$.post('edit-menu-process.php',
{tree: $('#nav').html()},
function(data){$("#printOut").html(data);}
);
});
Everything is working EXCEPT something about my encoding of the passed data is making it not read as html and just plaintext. How do I turn this back into html?
EDIT: I was able to get this to work correctly. I'll make an attempt to switch this over to DOMDocument.
$path = '../../../yardworks/content_pages/header.html';
$menu = htmlentities(stripslashes(utf8_encode($_POST['tree'])), ENT_QUOTES);
$menu = str_replace("<", "<", $menu);
$menu = str_replace(">", ">", $menu);
$divmenu = '<div id="nav">'.$menu.'</div>';
/* Search for div contents in $menu and save to variable */
preg_match('/<div id="nav">(.*?)<\/div>/si', $divmenu, $newmenu);
$savemenu = $newmenu[0];
/* Get file contents */
$header = file_get_contents($path);
/* Find placeholder div in user content and insert slider contents */
$final = preg_replace('/<div id="nav">(.*?)<\/div>/si', $savemenu, $header);
/* Save content to original file */
file_put_contents($path, $final);
?>
Menu has been saved.
To post the contents of a div with ajax:
$.post('/path/to/php', {
my_html: $('#my_div').html()
}, function(data) {
console.log(data);
});
If that's not what you need, then please post some code with your question. It is very vague.
Also, you mention preg_match and html in the same question. I see where this is going and I don't like it. You can't parse [X]HTML with regex. Use a parser instead. Like this: http://php.net/manual/en/class.domdocument.php

Copying a Word and saving it as a Variable

I am building an online spanish dictionary. I obtain the definitions legally from another site. For specific words the user may search for, a list of suggestions comes up.
If you click on any of those suggested words, error page pops up: http://verbum.xtrweb.com/verbumpost.php?word=boedo&word0=hola . How can I make those listed words run through the code pasted below: (1) retrieve definition (2) change style.
I know that a unique URL exists for every one of those suggested words (inspect element). If you paste together that code with the original site's URL parameters, you get what I need.:
"http://lema.rae.es/drae/srv/search?id=AVNYdnea1DXX2EH9E2mb"
up to "srv/" belongs to site
the rest is from the specific word (in this case, the first suggested, "bordar"
The Process:
<?php
$words = array('word','word0','word1','word2','word3','word4','word5','word6','word7','word7','word9',
'word10','word11','word12',
'word13','word14','word15');
function url_decode($string){
return urldecode(utf8_decode($string));
}
// we'll use this later on for loading the files.
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
// string to replace in the head.
$cssReplace = <<<EOT
<style type="text/css">
//blabla
</style>
</head>
EOT;
// string to remove in the document.
$spanRemove = '<span class="f"><b>.</b></span>';
$styleRemove =
// use for printing out the result ID.
$resultIndex = 0;
// loop through the words we defined above
// load the respective file, and print it out.
foreach($words as $word) {
// check if the request with
// the given word exists. If not,
// continue to the next word
if(!isset($_REQUEST[$word]))
continue;
// load the contents of the base url and requested word.
$contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));
// replace the data defined above.
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = str_replace($spanRemove,"", $contents);
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $data);
// print out the result with the result index.
// ++$resultIndex simply returns the value of
// $resultIndex after adding one to it.
echo "<div id='results' style='
//bla bla
}
?>
I don't think I understand your question, but I do see that you are calling preg_replace on an uninitialized variable - $data.
Maybe you want this instead?
$data = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/\1', $contents);
Like I said, I don't fully understand your question, but I do see that as a potential problem.
EDIT:
From your comment, it looks like you want to append the href of the link being clicked to a base url and request that page's data. Can you use jQuery? Like this:
var baseUrl = "http://lema.rae.es/drae/srv/"; // base url
//click function that binds to all anchors within a list item within a ul. in order
//to get more precise, you may need to add some classes or ids
$('ul li a').click(function(){
var src = $(this).prop('href'); //this grabs the href property of the anchor
$(this).find('span').css('propery', 'change to this'); //change css property of span child of this anchor
//or if you want to add a class with styles to the element
$(this).find('span').addClass('class name');
//ajax request to get page data
$.ajax({
type: 'POST',
url: baseUrl+src //appending the query to the base url
}).done(function(data){
//append the returned html to a div, or any element you desire
$('#myelement').append(data);
});
});
Hope this helps. If you need any help with jQuery just let me know.

Having trouble passing text from MySQL to a Javascript function using PHP

So here's the problem. I have data in a MySQL DB as text. The data is inserted via mysql_real_escape_string. I have no problem with the data being displayed to the user.
At some point I want to pass this data into a javascript function called foo.
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{$someText}')\">";
If the data in $someText has line breaks in it like:
Line 1
Line 2
Line 3
The javascript breaks because the html output is
<img src=someimage.gif onclick="foo('line1
line2
line3')">
So the question is, how can I pass $someText to my javascript foo function while preserving line breaks and carriage returns but not breaking the code?
===========================================================================================
After using json like this:
echo "<img src=someimage.gif onclick=\"foo($newData)\">";
It is outputting HTML like this:
onclick="foo("line 1<br \/>\r\nline 2");">
Which displays the image followed by \r\nline 2");">
json_encode() is the way to go:
$json = json_encode($someText); # this creates valid JS
$safe = HtmlSpecialChars($json); # this allows it to be used in an HTML attribute
echo "<img src=someimage.gif onclick=\"foo($safe)\">";
You can see a demo here: http://codepad.org/TK45YErZ
If I'm not interpreting badly you may do this:
// This is a PHP block of code
// $someText is text retrieved from the database
echo "<img src=someimage.gif onclick=\"foo('{".trim( preg_replace( '/\s+/', ' ',$someText ) )."}')\">";
You'll save yourself a lot of headaches by pulling the JavaScript out of the HTML:
<img id="myImage" src="someimage.gif"/>
<script type="text/javascript">
var str = <?php echo json_encode($json); ?>;
document.getElementById('myImage').addEventListener(
'click',
function() {
foo(str);
}
);
</script>
Or something similer...
Only json_encode() is enough to escape the new line
echo "<img src=someimage.gif onclick=\"foo(".json_encode($newData).")\">";

Categories