How to open a link which was parsed in a div? - php

My site parses a spanish dictionary and lets you search for more than one word at a time. If you look up "hola" you get the first div). Some words come up with suggestions, like "casa", instead of definitions like "hola":
And what i am looking for is this:
So, i would like to: when you click on the suggestions (like CASAR in the example I posted) to print the result in a div like HOLA. Here is the code used:
$words = array('word0','word-1');
function url_decode($string){
return urldecode(utf8_decode($string));
}
$baseUrl = 'http://lema.rae.es/drae/srv/search?val=';
$cssReplace = <<<EOT
<style type="text/css">
// I changed the style
</style>
</head>
EOT;
$resultIndex = 0;
foreach($words as $word) {
if(!isset($_REQUEST[$word]))
continue;
$contents = file_get_contents($baseUrl . urldecode(utf8_decode($_REQUEST[$word])));
$contents = str_replace('</head>', $cssReplace, $contents);
$contents = preg_replace('/(search?[\d\w]+)/','http://lema.rae.es/drae/srv/search', $contents);
echo "<div style='
//style
", (++$resultIndex) ,"'>", $contents,
"</div>";
}
I have tried with: $contents .= '' . $word . '<br/>'; But it didn't work nor I know really where/how to use it.

Okay, I'll use jQuery for the example because it will be the easiest to get the job done specially if you are new to programming.
NOTE: I DO NOT RECOMMEND USING JQUERY -BEFORE- LEARNING JAVASCRIPT -- DO IT AT YOUR OWN RISK, BUT AT LEAST COME BACK AND LEARN JAVASCRIPT LATER
First, read up on how to download and install jquery here.
Secondly, you will want something a little like this, let's pretend this is your markup.
<div id="wrapper">
<!-- This output div will contain the output of whatever the MAIN
word being displayed is, this is where HOLA would be from your first example -->
<div id="output">
</div>
<!-- This is your suggestions box, assuming all anchor tags in here will result in
a new word being displayed in output -->
<div id="suggestions">
</div>
</div>
<!-- Le javascript -->
<script>
// Standard jQuery stuff, read about it on the jquery documentation
$(function() {
// The below line is a selector, it will select any anchor tag inside the div with 'suggestions' as identifier
$('#suggestions a').click(function(e) {
// First, stop the link going anywhere
e.preventDefault();
// Secondly, we want to replace the content from output with new content, we will use AJAX here
// which you should also read about, basically we set a php page, and send a request to it
// and display the result without refreshing your page
$.ajax({
url: 'phppage.php',
data: { word: 'casar' },
success: function(output) {
// This code here will replace the contents of the output div with the output we brought back from your php page
$('#output').html(output);
}
})
});
})
</script>
Hopefully the comments will shed some light, you need to then set up your php script which will be sent a GET request. (for example, http://some.address.com/phppage.php/?word=casar)
Then you just echo out the output from PHP
<?php
$word = $_GET['word'];
// Connect to some database, get the definitions, and store the results
$result = someDatabaseFunctionThatDoesSomething($word);
echo $result;
?>
Hope this helps, I expect you have a lot of reading to do!

Related

Angular.js modal window within php echoes not working

I'm using code from this angular.js modal window tutorial by Jason Watmore: http://jasonwatmore.com/post/2016/07/13/angularjs-custom-modal-example-tutorial
I'm trying to implement an angular.js modal window within a php partial. Here is the code where I believe there's a problem:
<div id="screenings">
<?php
//MySQL database connection established
...
while ($row = mysqli_fetch_array($result)){
echo "<div class='img_div'>";
echo "<img class='modal_img img_screenings' ng-click=\"vm.openModal('custom-modal-1')\" src='images/".$row['image']."' >";
...
echo "</div>";
}
?>
</div>
<modal id="custom-modal-1">
<div class="modal">
<div class="modal-body">
<img id="popup_img" src="#">
</div>
</div>
<div class="modal-background"></div>
</modal>
<script>
$('.img_div').on("click", function() {
var source = ( $('.modal_img').attr("src") );
alert(source);
$('#popup_img').prop('src', this.src);
});
</script>
The First Problem
The while loop spits out a bunch of images. The script at the bottom should then grab the src of whichever image is clicked and then alert that src in a pop-up message. However, it only alerts the src of the first image in the while loop regardless of which image of the bunch is clicked. I've tested this script outside of the while loop on separate img elements with different src attributes, and it works fine outside of the echoed while loop.
The Second Problem
Within the while loop, there is an ng-click in the second echoed statement that just isn't working. In my app.js file, here is the controller code that ng-click=\"vm.openModal('custom-modal-1')\" should go to (the slashes are because of the echo statement):
app.controller('screeningsController', ['$scope', '$log', "ModalService", function($scope, $log, ModalService){
var vm = this;
vm.message = "Hello World!";
$log.log(vm.message);
vm.openModal = openModal;
vm.closeModal = closeModal;
function openModal(id){
ModalService.Open(id);
}
function closeModal(id){
ModalService.Close(id);
}
};
}]);
Right after the var vm = this; statement, I'm trying to output a message to the browser console as a test, but it's not working. Maybe my syntax is wrong?
here's a couple quick thoughts. In the first portion, I don't think you were actually capturing the correct click. I added a variable to pass into the on click function to select the one that was actually clicked.
As far as the php, sometimes its easier to toggle out of php and do a chunk of html. If you're passing a lot of html chunks you might want to consider doing output buffering.
<?php
while ($row = mysqli_fetch_array($result)){ ?>
<div class='img_div'>";
<img class="modal_img img_screenings" ng-click="vm.openModal('custom-modal-1')" src="images/<?php echo $row["image"]; ?>" />
</div>
As far as the jquery on the page:
you need to grab the actual node with the click event - the "e" is a common convention for that, but its really just a variable
$('.img_div').on("click", function(e) {
var source = $(e).attr("src"); // here you grab the actual attribute
alert(source);
$('#popup_img').attr('src', source);
});
i'm assuming you actually want to set the img src attribute in your target modal here.

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.

echo <body> doesn't activate jquery script

So I have a url from where I extract the data with extracthtml.php:
<?php
include("simple_html_dom.php");
$html = file_get_html($url);
$body = $html->find('body', 0);
$title = $html->find('title', 0);
echo $title;
echo $body;
?>
<script src="extract.js" type="text/javascript"></script>
Then with jquery I put a box around all the p elements to see if this communication works (test, am going to add more css manipulation later). My jquery starts with:
$(document).ready(function(){
$('p').css("border", "2px solid black");
});
Im guessing document.ready is the problem, because there appears to be no boxes around the p elements.
The issue is that you are echoing the jquery line to the browser after you close the page.
Since you echo the $body first, I would guess your page ends up looking something like this:
<body>
...
</body>
<script>
jquery here
</script>
Without seeing your page output this is only a guess, but if it is correct the browser will not run any code after the </body> tag. I would advise checking the source of your output to see if this is the case.

jquery load a specific #Div content from multiple html files

I am trying to make a Content Slider for my site. I have multiple HTML files and the structure of these files is like this:
<div id="title"><h2>Title of the Slide</h2></div>
<div id="image"><img src="image.jpg" width="600" height="300" alt="image"</div>
<div id="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</div>
I have been trying to use the following script get content (but no success):
<?php
function render($position="") {
ob_start();
foreach(glob("/slides/*.html") as $fileName) {
$fname = basename( $fileName );
$curArr = file($fname);
$slides[$fname ]['title'] = $curArr[0];
$slides[$fname ]['image'] = $curArr[1];
$slides[$fname ]['content'] = $curArr[2];
foreach($slides as $key => $value){
?>
<div id="slide-title">
<?php echo $value['title'] ?>
</div>
<div id="slide-content">
<?php echo $value['content'] ?>
</div>
<div id="slide-image">
<?php echo $value['image'] ?>
</div>
<?php
}}
?>
<?php
return ob_get_clean();
}
But then I came to know about a jQuery function.... (again no success)
jQuery.noConflict();
(function($){
$(document).ready(function () {
$('#slide-title').load('slides/slide1.html #title');
$('#slide-content').load('slides/slide1.html #content');
$('#slide-image').load('slides/slide1.html #image');
});
})(jQuery);
Now My questions are.....
Am I using the right syntax.
How do I get the content from multiple files using jQuery.
Please Note : My knowledge on Programming is almost '0'. I have just started learning it.
$('#slide-title').load('slides/slide1.html #title');
$('#slide-content').load('slides/slide1.html #content');
$('#slide-title').load('slides/slide1.html #image');
This will work, but not very quickly. You are doing three separate requests to the same page. You can combine them all into one fairly easily using $.get and its callback argument:
$.get('slides/slide1.html', function(html) {
var $html = $(html);
$('#slide-title').html($html.find('#title'));
$('#slide-content').html($html.find('#content'));
$('#slide-image').html($html.find('#image'));
});
Note that I have corrected slide-title to slide-image in the last line, since I hink that's what you need.
Jquery has no intuitive knowledge of files on the remote file system. You could, however, do something like this:
$(document).ready(function () {
for(var i = 1; i < 5; i++) {
$('body').append('<div id="slide-content-'+i+'"></div>');
$('#slide-title-'+i).load('slides/slide'+i+'.html #title');
// ...and so on
}
});
This will do something akin to what you were trying to do with PHP. I don't know PHP very well but that could be a better way to go (depending on it's DOM processing abilities) since the above will create one request for each file.
Your jquery code seems to be correct. What is the output you are getting?
Here's a pointer to what you are trying to accomplish..
http://www.electrictoolbox.com/load-content-jquery-ajax-select-element/
Let me know whether this helps....

Categories