I am trying to use jQuery's fancy autocomplete function but I have a problem with speed of executing my script. Code snippet:
var data = <?php if(isset($names)) { echo json_encode(implode(" | ", array_unique($names))); } else { echo "null"; } ?>;
if (data != null) {
data = data.split(" | ");
$("#search_names").autocomplete(data);
}
My data comes from some MySQL table and is processed by PHP before jQuery pass it to input field. When I view source of such page there's enormous amount of text there (obviously) and the page itself loads between 5-10 seconds...
So I wonder is there a way to speed up my script somehow? I understand that there will be always so much text to process, whether in same file or in some other included file, but I just wonder am I stuck with 10sec loading page because of so much data or can I somehow make it more awesome? :)
Thanks for any help!
You should definitely use the remote autocomplete mechanism instead of filling all the data into the document every time.
The first argument can be an URL for remote data or an an array for local data.
For remote data: When the user starts typing, a request is send to the specified backend ("my_autocomplete_backend.php"), with a GET parameter named q that contains the current value of the input box and a parameter "limit" with the value specified for the max option.
if the lookups still take a lot of time, you will probably need to look into optimizing your PHP script instead of the jQuery part. Things like is the database using indexes, etc....
Looks like your using the following scritp: http://docs.jquery.com/Plugins/autocomplete
You should be using Ajax for this sort of thing, example:
$("#search_names").autocomplete('/ajax/autocomplete.php');
and then within your auto complete html you should do something like:
<?php
//Database
//Do Query: SELECT item FROM content WHERE {$escaped_q} ORDER BY item_hits DESC LIMIT {$escaped_limit}
//echo json_encode($results);
?>
Print the results as a JSON Object and it should work MUCH MUCH Faster.
Related
I am writing a inline-PHP snippet that is grabbing values out of a query.
Here is the code I use:
$(".menu-price-slider").each(function(index) {
console.log(timeToMinutes("<?php echo $query_results['d'.(++$d).'_o']?>"));
});
This code is giving me $query_results[1] every time, what I want is a counter that is increasing everytime this code gets executed.
$query_results[1], $query_results[2], $query_results[3], $query_results[4], etc.
Thanks in advance
OK. If you are expecting to get a different value for parameter of timeToMinutes with each iteration, then you are mistaken. I think you need to get a better understand for how PHP and javascript work. PHP is only working at the time of page render. One the page is rendered, javascript would work within the browser. If you didn't put all the values you need from PHP into the javascript source, you have no way to get to them after the page is rendered, short of using AJAX techniques you pull the data in after initial page render.
I might suggest a technique like this:
// pre-populate array of values from PHP
// here PHP $query_results must be numerically indexed array
// there should be equal number of elements in this array and
// .menu-price-slider DOM elements
var timeToMinutesParams = <?php echo json_encode($query_results); ?>;
// iterate through DOM elements,
// using index of element to get matching value from timeToMinutesParams
$(".menu-price-slider").each(function(index) {
console.log(timeToMinutes(timeToMinutesParams[index]));
});
You could make a file initialize it with 0 if it does not exist and if it exists read from it and at the end increase the number in the file.
what i'm trying to do is get a variable to update every 5 seconds doing this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>",5000);
but what happens is the inner html is set but doesn't update every 5 seconds like it should.
my guess is that the php only executes once, but i have no idea if that's the case or not.
and i'm aware i should make a function to do the stuff inside setInterval... i'll clean up the code once i figure out how to make it work.
thanks in advance.
ok... ajax was 'the best' answer since no more than 2 people would be logged in at a time here so server requests isn't such a big deal.
here's how i got it to work:
function lCount(){
$.get("../includes/shoutcaststuff.php",{Count: "TRUE"}, function(data){
document.getElementById('listeners').innerHTML = data;
});
}
setInterval(lCount,5000);
and added this to the end of the php:
if(isset($_GET["Count"])){
echo $dnas_data['CURRENTLISTENERS'];
}
now it works fine.
thanks for the suggestions guys :)
<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>
This code only executes once when the page is built. For the rest of the times this javascript is called whatever is first echoed will be the value.
Instead of using a static value here, you are going to need to use an ajax request (or a websocket if you want to use html5). The request will then hit your server once every 5 seconds. Keep in mind that this can cause undue load on your server.
Ratchet is a commonly used PHP WebSocket implementation that allows for data to be sent to the client using push technology. This is probably more preferable than using your polling approach.
PHP code is run on the server generating the HTML/JS. Use ajax if you need to run php code once the page has loaded.
Take a look at this for example;
Using this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php echo "1";?>",5000);
Will output this to the browser:
setInterval(document.getElementById("listeners").innerHTML =
"1",5000);
So, I'm not sure if I can do this. If not, then any suggestions would be appreciated. Sorry in advance if the question is ridiculous...
I have an array that I created in php which is holding different user names populated off the database. When a user submits a form I want to use jQuery to check that the user name being submitted does not already exist in the array already created. I'm not quite sure how to do this. This is where I'm heading.
PHP section:
$existing_users = array();
$existing_users[] = $users; //this is reiterating in a while loop
HTML section:
<input type='text' name='user_name' id='user_name' />
jQuery section:
function checkAllFieldsForm() {
if (jQuery.inArray($('#user_name').val(),$existing_users) == -1) {
alert('no way this worked');
}
};
Not sure if maybe I should be using $.each instead or something else...
It seems like I would need to access the array $existing_users by an id but I haven't given it one. Do I need to give it a division id?
What you want to do is create this as a javascript array while still on the server side. I.e. have php output it as a javascript array (by looping over the array values and emitting them into a javascript array, or by outputting the array in JSON encoding). Then it will be available to javascript on the browser side, and all is well. PHP variables themselves are NOT available on the browser side, since PHP does not run there and was finished running before the server sent the web page.
Take a look at: Generating a JavaScript array from a PHP array.
You'll have to print the array into the javascript source, so the javascript can read it.
Should be like this:
var client_side_existing_users = <?php echo json_encode($existing_users); ?>;
if (jQuery.inArray($('#user_name').val(), client_side_existing_users) == -1) {
alert('no way this worked');
}
(I called it client_side_existing_users to make it very clear that the variable exists on the client side / in the browser, and has left the server-side world)
Keep in mind, the user will be able to see the contents of existing_users by looking at the page source. This could also make the page size massive if there are a ton of users. I would love to know why you're doing this, because there's probably a better way.
As the title describe, the speed of jquery display data is 1 to 2 seconds slower than pure php. Demo at http://plekz.com/test-slow3.php . How to make jquery display data as fast as pure php?
Codes :
<div id="jqryd">
</div>
<script src="javascripts/jquery-1.5.js" type="text/javascript" language="javascript"></script>
<script type="text/javascript">
var jqryd = $('#jqryd');
jQuery.get("sale-show-month2.php", function(data) {
jqryd.html(data);
});
</script>
<?php
$sql = "SELECT payment_date, SUM(price) FROM sale WHERE seller_id=? && Year(payment_date)=? GROUP BY Month(payment_date) DESC"; //this is loged-in user.
$q = $conn->prepare($sql);
$result = $q->execute(array($user_id, $selected_year));
if(!$result){
die("Error Select user table query : ". implode(" : ", $q->errorInfo())); //if don't use implode, output of errorInfo() will be "Array".
}
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$price_db2 = $r['SUM(price)'];
$payment_date_db = $r['payment_date'];
$payment_month_db = date("F", strtotime($payment_date_db));
$payment_month_db2 = date("m", strtotime($payment_date_db));
echo "This is pure php : " . $payment_month_db . " - " . $money_currency . $price_db2 ."<br>";
}
?>
Analyzing the traffic in your site example, I see that, other than result, in your sale-show-month2.php page you return even the jquery javascript. This slow down a lot the whole page: for some reason the network tracer see a querystring in the call like http://plekz.com/javascripts/jquery-1.5.js?_=1337691808625, that doesn't allow the cache to be used.
Simply avoid to return the link to jquery will improve performance.
Even after that you'll see jquery loaded data to come later, but this is due to the fact that the get method is called afeter the first page is loaded. You can see it very clearly with firebug or other tool (chrome and IE has their own).
With regards to the amount of data transfered between server and client I would always just transfer the minimum data required (probably using Plain text / XML or JSON depending on the data) and use the most efficient method to append it to the DOM
No matter how big the data is using the best (in your case fastest) method for appending to the DOM .. check out this jsperf for an indicator which method is fastest
And you will see that using the inbuild DOM creation methods are always faster, for example
var li = document.createElement('li');
li.innerHTML = i;
li.setAttribute('title', 'Element number ' + i);
li.setAttribute('class', 'list-item');
container.appendChild(li);
So in your case I would pass the data as JSON and then loop the nodes and append as required. If there is a lot of data returned then i would paginate the data - or show some initial data then add a "Show more" function that retrieved the next portion of data to be displayed.
With regards to the backend - I would ensure that my query was optimised and was using the correct indexes.
Your question doesn't really make sense. Check the network transfers with firebug or chrome - you'll see you spend about the same time waiting for data in both scenarios. However, after receiving the php'generated data the page takes ages to download jquery - and only then can it request the new data.
The only noteworthy thing is that it takes half a second to connect to your server with jquery - this lag will always be present if the connection is bad. With server-side generated data you'll get it once, with ajax you'll get it twice.
So in your scenario, you cannot speed up the fetch - unless you switch servers to something with proper throughput and proper response times.
While there are some ways to optimise the result, the answer to your question
How to make jquery display data as fast as pure php?
is: It is impossible.
Your Javascript will not be able to load anything into the DOM, until it is parsed and ready. This implies that the "pure PHP" data is already loaded, as it is delivered by the server as part of the main page.
It is only then, when the browser has to do another request to the server, taking another round-trip time, in order to get the AJAX version. So: no matter how good your server and your JS are, the AJAX version will never be as fast as the server-side version.
Note: This applies only for your setup with both version competing. Of course it could make sense to speed up the initial delivery of the HTML page by not using PHP and a database request, then loading some stuff later with AJAX.
I am working on my personal site, where I want to store my customers recent search result limited to that particular session.
I am using PHP platform and Javascripts.
Here is an example of what I am exactly looking at :
It stores your previously searched domain name for that particular session so that user can make decision by comparing those results.
Thanks.
EDIT- Well Thanks for all of your answers and suggestions.
But If you have noticed
above example
It looks like some kind of script loading a new content on the same page without refreshing it and keeping previous search content <div> as it is.
How to achieve this using javascripts or some sort of div layer ????
UPDATE START
This example uses page reload. If you want to do it without page reload, you can but you'll have to use AJAX to load new search results. But then, it's not a PHP question. I suggest looking at jquery library, as it makes it easy. Tutorials: http://docs.jquery.com/Tutorials and e.g. this one ( http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax ).
When loading data via AJAX, the page rendering result (in my example search.php) should return only HTML for results part, not whole HTML page. This is generally a first part of my tutorial (without session).
But I really think that AJAX in here is not really needed. Session is more reliable and allows access to your page from older / mobile browsers where not always JS works correctly.
UPDATE END
Ok then. Let's try the simple tutorial then. Sorry if too simple, but I don't know your exact level.
PHP has mechanism called sessions. In reality they are just bytes stored on server. Server knows which session is for each client by reading session cookie from client browser.
Not every page uses sessions (not every page needs it, and session uses server space, even if only temporarily), session is not enabled by default. To turn on session you use command
<?php session_start(); ?>
In most cases this is either run by PHP framework you use, or put near the top of your site. Session is definitely needed if you want to authenticate user somehow. Or in your case :)
To access session you can use superglobal $_SESSION variable (superglobal means that you can access it anywhere). It's an array, so session element will be e.g. $_SESSION['search'] etc.
As example, let's assume that your page looks like that
<html>
...
<form action="search.php" method="post">
Search: <input type="text" name="searchQuery" />
<input type="submit" value="Search" />
</form>
...
</html>
this very form will send user search to file named search.php. It can be the same file where the form resides - in simplest case when you put both your code and HTML in one file. Beginners often use this schema, although it's not advisable as result is a mess and hard to further change.
In search.php then, you'll use similar code:
<?php
if (!empty($_POST['searchQuery'])) //we have a new search
{
$result = do_search($_POST['searchQuery']);
}
?>
Then, somewhere below you'll display your search result ($result variable). do_search() function is your search mechanism, I guess you have it somewhere. You may have it not 'wrapped' in a function, then I advise to create it like that, it's much more useful.
function do_search($searchQuery)
{
...
return $result;
}
mind it, the above code doesn't use sessions yet. Let's add saving previous search results in session. The code may then look like that:
<?php
session_start(); //Starting session
//let's create session variable used to store results
if (!isset($_SESSION['searches']))
$_SESSION['searches'] = array();
if (!empty($_POST['searchQuery'])) //we have a new search
{
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value, delete previous result from sesion
{
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
$result = do_search($_POST['searchQuery']);
//Let's add new search on the begining of session array to make iterations easier.
$result = array($_POST['searchQuery'] => $result); //convert result to same format as session table
$_SESSION['searches'] = array_merge($result, $_SESSION['searches']);
}
?>
In display you'll now not iterate on $result variable as before, but instead you will do something like
foreach ($_SESSION['searches'] as $query => $result)
{
...//display of single result
}
I haven't tested following code and it's not a full program. Parts to display result and to do actual search are not described but I guess you have them already prepared. Also, this is only one possible approach of countless possibilities. But I hope this helps :)
Possible modification - now I always perform search, even if user already searched on this term. You may want to receive the result from cache without second search. Then the code will look like
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value
{
$result = $_SESSION['searches'][$_POST['searchQuery']];
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
else
{
$result = do_search($_POST['searchQuery']);
}
For more in-depth information about sessions and some other constructs used in my example I suggest PHP manual
http://pl.php.net/manual/en/book.session.php
and various tutorials over the network. Or you can add a comment here :)
Put this code near the beginning of your script(s):
if (!isset($_SESSION['previous_searches']) || !is_array($_SESSION['previous_searches'])) {
$_SESSION['previous_searches'] = array();
}
[edit]
This code snippet checks if if there is already an array with prevous searches and if not it will be created.
[/edit]
Then when the user hits the search page put this code in the receiving script of the search:
$_SESSION['previous_searches'][] = $_GET['what_ever_your_search_value_might_be'];
[edit]
This code snippet adds the current search value to the and of the array with previous search values
[/edit]
Now you have all previous search values in $_SESSION['previous_searches']
If your website is a web application where you never reload the page nor change the page, you can keep it JavaScript in a global store (declare at top level something like var StoredSearch = []; and use it). If not, then use $_SESSION to store this and AJAX to save/load searches from JavaScript to PHP.