I have a jquery function that controls some css that sets state to active or not. It runs on a click event. I need to have a similar function run when a php function runs (when the user searches with a form). The search term goes through a php function which will match the term with an id. How can I set the state to active with the php function?
Here is a link to a test area
http://vtour.dev4.webenabled.net/tester/index.html
If you click an area, the selection remains active. if you type a name in the lavender search box, and click the search icon, the corresponding area does not become selected.
(attaching the search functionality file. i know there is a bunch of junk in there but the section that corresponds to this example starts around line 149
The small lavender box next to the input line is the click/search icon
Thank you
You can't do this from PHP, you do everything through Javascript (and see Ohgodwhy's comment, especially the note about using jQuery or not using jQuery - you should use .ajax() or .post() for example).
To do it, the AJAX would return some flag to tell Javascript what blocks to turn on/off, as well as the text response. You can wrap all this up in a JSON object.
<?php
$returnArray = array('html' => 'HTML TO DISPLAY', 'blocks'=>array(1,3,4));
echo json_encode($returnArray);
?>
and in javascript use the JSON object elements to display the text, and then also turn on/off the right blocks. This bit will be easier in jQuesry as it handles the JSON object for you, so you'd only need response.html for the html bit, and response.blocks for the blocks.
You can execute a javascript function by outputting a html script tag.
ie.
<?php
echo "<script type=\"text/javascript\">runJavascriptFunction()</script>";
?>
So you could technically drop that into the response from your FetchData.php - but if it were me, I would do it all with jQuery:
$('#woodward-title-search-button').click(function() { //on button click
var term = $('#searchTerm').val(); //the search term
$('#room-'+term).css('background','red'); //or more nicely: .addClass('highlighted');
//load the response of fetchdata into #myDiv
$('#myDiv').load('FetchData.php?searchTerm='+term);
});
I would suggest communicating with your PHP in json and providing an ID of some kind to better target your div.. but this should work as a down and dirty solution.
Related
I would like to download content of certain page and get one number from it (still not sure how, probably using PHP DOM interface). I opened the page, started Firefox's debugging, picked the element with number and found out that is in <div id="lblOptimizePercent" class="wod-dpsval">98.4%</div> (98.4% is what I am looking for). So I opened its source code, Ctrl - F for lblOptimizePercent and all I found is this <div id="lblOptimizePercent" class="wod-dpsval"></div> without any content. What I've done wrong? Or is it some site's protection not to steal contents?
Link to the original site
Normally, to scrape the page from PHP, you would have to
save the page
extract the value you want from HTML via a regular expression
alternatives include using SimpleXML for DOM querying...
The piece of HTML we are look at is:
<div id="lblOptimizePercent" class="wod-dpsval">DATA</div>
<?php
$text = file_get_contents('http://www.askmrrobot.com/wow/optimize/eu/drak%27thul/Ecclesiastic');
$regexp = '^<div id=\"lblOptimizePercent\" class=\"wod-dpsval\">(.*)<\/div>^';
preg_match($regexp, $text, $matches);
$percentage = $matches[1];
echo $percentage;
This should give you DATA - the percentage value. But this doesn't happen! Why:
The data is dynamically inserted by a Javascript on client-side.
The id or class selector is used for DOM querying (element selection), then the data value is added.
http://api.jquery.com/id-selector/ - http://api.jquery.com/class-selector/
jQuery example
On this site they deliver <div id="lblOptimizePercent" class="wod-dpsval"></div>to the client and then they use an update query like this: $("#lblOptimizePercent").text("100%"); to update the percentage value.
If you want to query it on client-side, you might use $("#lblOptimizePercent").text();**
Try this in your console. It returns the percentage value.
How to scrape this page?
If you want to scrape this page with dynamic data, you need something like a Browser Environment for scraping: PhantomJS or SlimerJS are your friend.
Open the page with PhantomJS, launch the jQuery cmd from above and done.
This snippet should get you pretty close. You might save it as scrape.js then execute it with Phantom.
var page = require('webpage').create();
page.open('http://www.askmrrobot.com/wow/optimize/eu/drak%27thul/Ecclesiastic', function() {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
alert(
$("#lblOptimizePercent").text()
);
});
phantom.exit()
});
});
You can also save the "evaluated page" (now with data) and do the extract with PHP.
That's exactly like: Save Page in your browser and working on the saved HTML file.
In Firebug or another webdeveloper tools you see the generated content, in Source code there is a blank element only.
First time, blank element is shown (during rendering site) and than using JS the content is filled.
Googlebot etc. can´t see this JS-generated content, but it´s no problem in this case.
Code:
document.getElementById('lblOptimizePercent').innerHTML = '94%';
Or similarly using jQuery:
$('#lblOptimizePercent').html('94%');
// need to load jQuery before, of course
I’m trying to store the content of a div to a variable.
Example:
<div class="anything">
<p>We don't know the content of this div</p>
</div>
I want to search for <div class="anything"> and store everything between opening and the end tag.
We also want to avoid using absolute pathnames, so that it only searches the current HTML/PHP file for this div where the code is present.
Is this possible with PHP, or is this only possible with JavaScript ?
PHP is not that intelligent. He doesn't even know what he says.
PHP is a server-side language. It has absolutely NO clue about what the DOM (ie. what is displayed in your browser's window) is when it delivers a page. Yeah I know, PHP rendered the DOM, so how could it not know what's in there?
Simply put, let's say that PHP doesn't have a memory of what he renders. He just knows that at one particular moment, he is delivering strings of characters, but that's all. He kind of doesn't get the big picture. The big picture goes to the client and is called the DOM. The server (PHP) forgets it immediately as he's rendering it.
Like a red fish.
To do that, you need JavaScript (which is on the client's computer, and therefore has complete access to the rendered DOM), or if you want PHP to do this, you have to retrieve an full-rendered page first.
So the only way to do what you want to do in PHP is to get your page printed, and only then you can retrieve it with an http request and parse it with, in your case, a library such as simpleHtmlDom.
Quick example on how to parse a rendered page with simpleHtmlDom:
Let's say you know that your page will be available at http://mypage.com/mypage.php
$html = file_get_html('http://mypage.com/mypage.php');
foreach($html->find('div.anything') as $element)
echo $element->src . '<br>';
you probably need a combination of those.
In your Javascript:
var content = document.getElementsByClassName("anything")[0].innerHTML();
document.getElementByID('formfield').value(content);
document.getElementByID('hiddenForm').submit();
In your HTML/PHP File:
<form id="hiddenForm" action="path/to/your/script">
<input type="hidden" name="formfield" value="" />
</form>
In the script you defined in the form action:
if(!empty($_POST)){
$content = $_POST['formfield'];
// DO something with the content;
}
Alternatively you could send the data via AJAX but I guess you are new to this stuff so you should start slowly :)
Cheers!
steve
You could use JS to take the .innerHTML from the elements you wan and store them in .value of some input fields of a form and then use a submit button to run the PHP form handling as normal. Use .readOnly to make the input fields uneditle.
When a user selects a word in a text on my website (PHP), and then right clicks, i want a jQuery context menu to come up, this can be done by using one of the already existing jQuery context menu plugins.
But besides the options like copy / paste / cut, etc. I also want something to be done with the selected word using PHP. Which, i think, is a little harder.
For example using this script:
$selection = //the selected word or text
$target = //fetch from MYSQL database
$output = array();
while ($row = //fetch $target) {
If ($selection == $row->input) { array_push($output,$row->output); }
}
echo '//menu '.print_r($output).''; // of course not print_r! Just for the example's sake.
Databse example:
(Sorry for the oversized image)
Ok so selecting the word 'lazy' in the example text, and then right clicking, the jQuery box should pop up showing the results from the database extracted by PHP.
Example:
Ok, so i know you can't just combine javascript with PHP and it can only be parsed, but i thought loading an iframe withing the menu, which does the database extraction would do the job by using javascript to set the iframe src containing the selected word in the url.
However, iFrames are not really a nice way to solve this.
The question: How can i do this effectively? Execute this script on right-click and show the database-related content in the menu?
I would need to know the plugin you're using to give you some code examples but, general, I would go about this like this:
There has to be a click handler on the items in the jQuery context menu. Use it to submit an AJAX request to the server when the "selection" term is clicked.
Make sure to give the user some feedback (a loader or spinner)
Put the results into an array server-side.
JSON encode the array and send it as the response (e.g. echo json_encode($output)
JSON.parse(response) on client-side and you now have a JS object with the results
Put those results in the context menu (again, how depends on the plugin you're using)
AJAX is a great way to do what you want.
Here is a simple AJAX example. Note that in the 2nd .PHP file, that is where you put your database lookup etc.
Whatever you echo from the 2nd script is received by the calling javascript (first script again) and can be inserted into your context menu on-the-fly. Here is another example with a very detailed, step-by-step explanation of the process at the bottom of the answer.
I think you have to use Ajax to get JSON from a PHP file, which you would process on the actual page.
I you create a PHP file called test.php, with the following in it:
<?php
echo json_encode(array('time' => time(), 'hour', date('H')));
?>
Then the Javascript:
<script>
$('#curr_menu_entry').click(function() {
$.getJSON('test.php', function(data) {
$.each(data, function(key, val) {
$('#curr_menu_entry').append('<li id="' + key + '">' + val + '</li>');
});
});
});
</script>
Would that work?
I need to make a form where client information can be added by people at the administration department. On the first form page, information like client name, address and contact details can be entered, as well as whether or not the client has children.
The form gets validated by PHP. If the client does not have children, the data is saved to the database. If the client does have children, the form data gets saved in hidden form fields, and a second form page is shown, where up to 10 children and can be added.
However, on initial page view, only one text input is visible. With a javascript button, more text input fields can dynamically be added (until the limit of 10 is reached).
The problem is the validation in PHP. If one of the text inputs contains a non-valid string, the form should be re-displayed with the right number of fields, and those containing errors in a special HTML class (in the CSS i give that class a red border for usability reasons, so the user can immediately see where the error resides). However, because the adding of fields happens with Javascript, the form gets re-displayed with only one field.
Any ideas on how to address this problem are very welcome. I'm proficient in PHP, but JavaScript is very new to me, so I'm not able to make big changes to the script i found to dynamically add fields.
I've dealt with something similar in the past. There are a couple of options that come to mind.
Since you have JS code to generate new fields at the click of the button, why not expand that JS function so it can also be called with some parameters passed. If there are parameters, it will populate the fields with existing data.
Then, if the form is being re-displayed due to errors, or for editing, from PHP, pass some information to Javascript so that when the page loads, you create the fields and populate them with data.
To illustrate, I assume you have something like this:
Add Another Child
And you have the function:
function addNewFormField() {
// create new HTML element to contain the field
// create new input, append to element container
// add container to DOM
}
Change it so it is like this:
function addNewFormField(data) {
// create new HTML element to contain the field
// create new input, append to element container
// add container to DOM
if (data != undefined) {
newFormElement.value = data.value;
newContainerElement.class = 'error';
}
}
And from PHP, add some code that runs onload:
<script type="text/javascript">
window.onload = function() { // replace me with jQuery ready() or something proper
<?php foreach($childInList as $child): ?>
addNewFormField({ value: '<?php echo $child['name'] ?>' });
<?php endforeach; ?>
}
</script>
Hope that helps, its a high level example without knowing exactly how your form works but I've used similar methods in the past to re-populate JS created fields with data from the server side.
EDIT: Another method you could use would be to create the HTML elements on the PHP side and pre-populate them from there, but that could end up with duplicate code, HTML generation from JS and HTML generation of the same stuff from PHP. As long as the JS side was smart enough to recognize the initial fields added by PHP you can go with whatever is easiest to implement. Personally I'd just extend your JS code to handle optional data like illustrated above.
I am trying to expand on some code written by someone else, but I am having trouble using one of the javascript variables. If I set it in the title of a div or something similar like so:
$("#test12").attr("title" , ccode);
then it works fine and the title of the div is 'CA', which it should be. But if I try to put it into the text area of the div, then it tries to run a function or something but I can't see where it's doing it.
Is there a way I can convert it to simple text and stop it from running any functions?
Thanks for any help
Edit:
This is all of the code I can see at the moment:
<script>
//<!--
function loadForeignOffices(ccode){
//load window with details...
$('#iframe_3').attr("src", "<?php echo $html->url("/", true); ?>erc/maps/contacts/"+ccode);
$("#test12").attr("title" , ccode);
}
//-->
</script>
Basically what I'm trying to do is use the ccode variable because I want to display CA on the screen, but when I try to do that it seems to run some other function and fails, and doesnt show CA.
You may need to brush up on your jQuery dot-operators:
.load() is an ajax call that will load the contents of () into the selected element. In one of your comments you mention you are trying to do this $("#test12").load(ccode); which is inherently silly, if ccode is the string "CA"
.attr() will change the attributes of the selected element. If you are trying to display "CA", $("#test12").attr("title" , ccode); this will clearly not accomplish that -- As "CA" is added to the title attribute. As in <div id="test12" title="CA"></div>
Perhaps what you are looking for is .html() which inserts the string into the selected element. Or even .innerText()
Why don't you spend some time reading the jQuery documentation. A little bit goes a long way!
Keep in mind your PHP code is executing first on the server, then your javascript.
Here's a JS Fiddle as a start: http://jsfiddle.net/QsFJ4/3/