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?
Related
I've been looking around for solutions for this for quite sometime and sadly, haven't found a proper solution for it.
Here's the situation.
I have a Bootstrap modal that displays text ( let's call it 'header' ) depending on which button was clicked. The header value is picked up from the data-attribute of the button and using jQuery, I update the text for the respective modal. I hope I've been clear enough about this.
Now, I want to use the same header text in a PHP Script that queries my MySQL table with this 'header' value in the LIKE clause of my query as '%header%'.
Seems simple enough but I can't get my head around it.
Here are some issues that I face:
The header value is empty in the PHP script when I try to pass it to the script. I tried using script_tags to strip the tags around the HTML of the header and just extract the text and also tried PHP DOM but it did not work.
Here are the basic steps for further clarity:
I have a PHP script that needs to get a text value from the HTML on the same page.
This text value was picked up from a data-attribute of a button and updated via jQuery to the HTML.
This text value must be included in the LIKE clause of MySQL query in the PHP script for any updates to the table.
I can handle everything else except the extraction of text and sending it to the PHP script part.
Thank you.
Adding Code for reference:
This is the HTML code that houses the data-attribute:
The $project_title variable was set previously and appended to the button.
echo "<a class='delete_icon' data-project_title='$project_title'><i class='fa fa-trash'></i></a>";
This is the jQuery code:
$('#project_profile_modal').on('show.bs.modal', function (event) {
var del_icon = $(event.relatedTarget);
var project_title = del_icon.data('project_title');
modal.find('h4').text(project_title);
}
This is the excerpt of the PHP script that is relevant:
<?php
$result = "SELECT content FROM my_table WHERE content LIKE '%$project_title%';
?>
Question is: how do I get the text contained in h4 to $project_title/my LIKE clause.
Assuming button looks something like:
<button class="modal-button" data-text="..." data-row_id="...">
Then in click handler you gather all the data and send to server:
$('.modal-button').click(function(){
var data = $(this).data();
// send to server
$.post(url, data, function(response){
// update modal header and content
$('modal-header-selector').text(data.text);
$('modal-content-selector').html(response);
})
})
I had implemented multiple checkbox filtering for a job portal using jQuery where in I was calling a function every time a checkbox is checked and that function contained an ajax call which would send the request with the checked values and I would do the querying of database and return the result.
But one of the developers I meet told me you should not hit the database continuously for filtering, it should be done client-side.
He also suggested to use AngularJS or Knockout(js) for the purpose, as they work on content, whereas jQuery works on DOM elements.
But if it has to be done client-side, all of the data must be loaded at once during the first visit to the page, which in turn would slow down the page.
And I cannot use class on each element and show/hide them based on the checkbox ID or value something like that, because there are a lot of checkboxes, which I think will be hectic to handle.
How to achieve the desirable result with good performance?
I'm a Newbie to jQuery, so if I have gone wrong anywhere bear with me.
Below is the sample way in which I have actually done:
HTML:
<input type="checkbox" name="location[]" value="Bangalore" onclick="loadresult()">Bangalore
JS:
function loadresult() {
location array value accessed and passed to ajaxcall
//ajax call to processresult.php
Displaying the DB returned Data
}
PHP (processresult.php):
<?php
//dbconnection + querying db and returning result
?>
There is significant difference. Angular is a framework and jQuery is a library.
With jQuery it much simpler to modify DOM elements deal with events and do some more cool stuff. But you define how you deal with data on your own. You can easily move your data to Js object or array of objects and render this data to your DOM tree.
For example:
//let's presume that you are searching something
var someUsers = [{id: 1,name:'User 1'},{id: 2,name:'User 2'},{id: 1,name:'User 3'}];
var usersTemplate = _.template("<h1>User name: <%= user.name %></h1>");
var $container = $('#someRenderContainer');
someInputFeild.on('keypress', function(){
var searchText = someInputFeild.text();
var foundUsers = someUsers.filter(function(item, index){
item.name.indexOf(searchText) !== -1
});
render($container,foundUsers);
})
function render($container,users){
users.forEach(function(item){
$container.append(usersTemplate(item));
})
}
Here is simple example where you can see that your manipulate with data in the memory but not in DOM. Similar things you can do with your checkboxes.
I would just make one ajax request in the beginning, fill the page with data, marking every row with class name
jQuery.each(d, function(i,data) {
$("table.content").append("<tr class=\""+data.city+"\"><td>" + data.tag + "</td><td>" + data.city + "</td><td>" + data.num + "</td><td>" + data.state + "</td></tr>");
});
and use checkboxes to hide and show marked rows using jQuery hide(), show() methods.
Rows can have multiple classes meaning filtered by multiple columns, but logic will get more complicated.
see example http://jsfiddle.net/elshnkhll/czdongkp/
I would use cache technique to improve my performance.
We can't load our full record on a single page. It will slow down the main page loading.
But we can save loaded data in a variable with some key combination for different filter and page no..
eg. if we are loading data fir index page with no filter, the my key will be index and my variable will be like var cachevar = {"index":{1:"<my response>"}}, here "1" is page number
And if data is using filter, then my variable index key will be combination of filter ids saperated by '-'.
eg var cachevar = {"index":{1:"<my response>"}, "index-2-5-3":{1:"my response"}}
If user request a page, I just have to check if that page is available in cache or no, if it's available in cache variable, then show it, else request it from server.
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 have a page called test.html. This HTML page will contain 2 JavaScripts file. I need to pass a variable value to a PHP file using the first JavaScript file. The user can copy this javascript on as many pages as he wants for displaying output.
The PHP file that receives the variable from the JavaScript file retrieves some data from database depending upon the variable's value. This retrieved value can contain HTML content. This PHP file will always reside on my server.
All of the retrieved content (from the PHP file) needs to be passed to the second JavaScript file so that the data can be displayed in browser. This JS file will need to stay together with the first JS file in order for the data to be displayed.
So I have this:
JavaScript File
<script type= "text/javascript" src="http://www.myserver.com/custom_script.php?unique_id=12"></script>
PHP FILE
//custom_script.php
<?php
$unique_id= (int)$_GET['unique_id'];
$res = db_res(" SELECT col1, col2, col3, .... col10 FROM table WHERE unique_id = $unique_id
LIMIT 1 ");
$rows = mysql_fetch_array($res);
?>
<div id="1"><?php echo $rows['col1']; ?></div>
<div id="2"><?php echo $rows['col2']; ?></div>
<div id="3"><?php echo $rows['col3']; ?></div>
.
.
.
<div id="10"><?php echo $rows['col10']; ?></div>
I need to send all the HTML above from the PHP file to the second JavaScript file so that the output can be displayed. Please note that the CSS styling is also applied using Div ID, so I am expecting those styles would show up too. Please note that there may be more than 10 columns, so an efficient way of passing data is highly appreciated.
So what would be the easiest and the best way to send all the HTML data from the PHP file in one go to the 2nd javascript file residing in test.html page, so that the HTML data can be displayed in test.html file?
EDIT 1:
I apologize to everyone if my question has been confusing. I just thought of an example and hence wanted to add it my edit. I hope you are all aware of what Google Analytics (GA)(or any other Website Visits Stats Tracker) does. Right? You register for a Analytics account and Google gives you a piece of JS code that you copy and paste in your website. And after couple of days, you can login into your GA account to see the stats. Correct? What I am trying to do here is just the same.
Users come to MY WEBSITE and register for an account and I give them JS files that they can paste in their website. The only difference between GA and my website is that GA is personal to you and no one else, but you, the account holder can see it. Whereas in my case, your data can BE SEEN by others as well, as long as you include the JS file on your website. Because users can't just take my PHP file and run it on their server, I am trying to access MY PHP file by giving the full path to it in the JS file.
For example:
<script type= "text/javascript" src="http://www.myserver.com/custom_script.php?unique_id=12"></script>
This is not an actual JS file, rather it is just a medium for my custom_script.php script to receive the unique_id of the user, query MY database and send back the HTML data related to this requesting user. And I am stuck with this part. Hope this clairifies what I am trying to do.
The jQuery documentation actually gives an example almost identical to your problem:
http://api.jquery.com/jQuery.get/
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
This will get an html page and insert it under an html element with class 'result'.
You should be able to replace your php script url and specify where the output should be displayed.
If youre worried about conflicts with other jQuery instances, have a read of this:
http://api.jquery.com/jQuery.noConflict/
If you want to write your own AJAX handler check out this page :
https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest
Essentially you will do something like this (taken from the link):
function reqListener () {
console.log(this.responseText);
};
var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "yourFile.txt", true);
oReq.send();
I think its worth doing if you've never had to do it before, but you will open yourself up to lots of potential problems that have been solved for you.
Ideally if I were doing this I would return json from the handler and allow the user to decide how to display it, but thats your call.
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.