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.
Related
I have a function that creates an array that contains the return value from the HTML DOM method : window.document.getElementById()
function makearray1(){
var array1=[1,window.document.getElementById('divID'),['a','b'],[1,2]];
}
then I pass the array into another function
use(array1)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
and 'a' is written in the appropriate div
later I decided to put the array in a form and post it to a txt file on the server using php and:
JSON.stringify(array)
So now I use AJAX to call the data from the txt file after the rest of the page has loaded etc... and the original function used to make the array is not included at all.
so my php is basically this:
$a1='use(';
$data1 =file_get_contents("text_file.txt") ;
$a2=')';
echo $a1.$data1.$a2;
and the response text:
var n= XMLHttpRequestObject.responseText;
eval(n);
which pretty much means this:
use(text_file)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
the problem is that the array in the text file looks like this:
[1,null,['a','b'],[1,2]]
instead of:
[1,window.document.getElementById('divID'),['a','b'],[1,2]]
My question: Is there any way that I can do the equivalent of what I'm trying to do here, which is immediately replicate the return value of the HTML/DOM method in an array using AJAX/php?
To clarify: this is a simple example. I actually have a huge, multidimensional array that already has established pointers, or prefetched DOM nodes in it. Now I'm trying to replicate the array when a text version is loaded using ajax. I'm looking for a recursive approach to changing all of the null assignments with something that will immediately fetch the appropriate DOM node. Most likely I will need to do it with the response text, but was hoping I could do it with the php portion.
You're trying to stringify a reference to a javascript object in the memory of whatever computer is evaluating getElementById first, and that has no chance to represent something on the end client's computer.
Send the id instead:
function makearray1(){
array1=[1,'divID',['a','b'],[1,2]];
}
then, in the client:
function use(xxx){
window.document.getElementById(xxx[1]).innerHTML=xxx[2][0];
}
If you really want to eval it at the end, you can use this, I guess
function makearray1(){
array1=[1,"window.document.getElementById(\"divID\")",['a','b'],[1,2]];
}
I've no idea why you would want to do that though
Assuming the dom element exists in the second page, it should look something like this.
JS:
function packDomData(){
return {
"MySpecificYetBriefProperty0":1,
"DomID":"divID",
"MySpecificYetBriefProperty1":['a','b'],
"MySpecificYetBriefProperty2":[1,2]
};
}
function useDomData(domData){
document.getElementByID(domData.DomID).innerHTML=domData.MySpecificYetBriefProperty1[0];
}
PHP:
//Make sure the contents of this file is the json from packDomData. use json_encode in php or JSON.stringify in js
echo file_get_contents("text_file.txt");
var myData = JSON.parse(XMLHttpRequestObject.responseText);
useDomData(myData);
I used to code like you. Here are some tips that have helped turn my coding horror into a fun job:
Use objects with descriptive properties instead of arrays whenever you aren't actually looping through the array - I promise it will save you and others headache! "DomID" is much more flexible than 1, and if you change the order in the array, javascript gods help you that array is everywhere - including however many random text files on your server!
Also use descriptive names for functions
Always return a value from a function instead of using globals whenever possible, even where the result is then used as a nasty global. Trust me.
Never put javascript function names in an ajax call. Use JSON instead and keep the functions and other script in the javascript file where it belongs.
Mysql will save your life!!
Disclaimer - I didn't run this code but it should basically work when you get everything hooked up right.
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.
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.
I would like to know how can I access or read the array from another page. I am working on a PHP page which contains the array, and I want to display the content of that array on another PHP page.
For example, I used the following method in a PHP file and I want to get the content of the array in another PHP file. what is the method that is going to receive the array's content in the second page.
<?php
$r = new HttpRequest('http://localhost/sameh.php', HttpRequest::METH_POST);
$r->addPostFields(array("n" => 'heba')) ;
$r->send();
?>
This code is in the first page but I don't know what to write to receive it on the second one.
Maybe my question was not that clear and sorry about that ,, I want to find a way to access the array that is defined inside the HttpRequest() class on another page. So that the array "n" that include value "heba" will be displayed on another.php page. this is what make me thinking that the problem is on how to access the content of the array on the second page.
I tried the session and It sends the array to another page ,, but when I tested with the
httpRequest() method it doesn't send the content of the array "heba" to the second page.
Thanks for your help.
Sounds like this is a job for Sessions.
You can read the complete session guide here
In the script that has the array you can do something like:
session_start();
$_SESSION['array'] = $array;
In the next script you access it similarly:
session_start();
print_r($_SESSION['array']);
Include that file in your php file where you want to use that array. This should solve your issue PHP - How to send an array to another page?
I'm not sure what the HttpRequest class is, but at a guess, it's POSTing variables to the sameh.php file. You should be able to access the variable on the next page by doing this:
echo $_POST['n'];
Which should print "heba".
Note that to work with serialized arrays, you need to use POST as the form's transmission method, as GET has a size limit somewhere around 1024 characters.
I'd use SESSIONs wherever possible.
You can use serialize() and unserialize() on your array to represent it as a string and pass it via POST.
I'm trying to display some content in real time to my visitors using a loop. Problem is that the content is added to the output instead of being replaced with the new one. Here's an example of code which counts from 10 to 0. The output shows the whole set of results instead of counting backwards. I mean, I don't want to see all numbers shown just each number as the counter goes.
ob_end_flush ();
//start buffering
ob_start ();
echo str_pad ( '', 1024 ); // minimum start for Safari
for ( $i = 10; $i > 0; $i --) {
echo str_pad ( "$i<br>\n", 8 );
ob_flush ();
flush ();
sleep ( 1 );
}
die ();
This can not be achieved with PHP alone, as to alter what is rendered in the browser requires some client side intervention.
How you go about this division of labour depends upon what is needed.
If your code is all of it, then you would be far better off writing a JS routine to count down the numbers in a timed fashion.
If PHP is required in some other fashion to generate the numbers then the decision needs to be taken as to whether you can split the generation of the update in to multiple PHP calls or if it has to be from within the single PHP call due to actions taking forth within that call.
If the former, you can separate it, which is the ideal situation - then the procedure is to setup AJAX calls to retrieve updated information periodically.
If the latter and it must be from a single page, then the connection must be kept open with new content generated.
In this case, to get new content to replace old, JS code must handle this. Either code running periodically upon the page can check for new content and update accordingly, or a little trick can be played injecting code that performs the update.
Sending inline <script> content that performs the update instead of new display elements works well, if a little untidy, as the browser receives the new <script> element it is run. This is the only way I am aware of that a push-update can be made to a web page without plugins.
There might be a trick or something (just thought of one or two) but the most appropriate way to do it is with an ajax autoupdate from the browser. Like this pattern description.
We didnt do this in PHP, in fact using js. ( with Stacker help ) you can reverse the count
But am sure you could adopt, sorry if this doesnt answer your question.
Demo here on our dev site < link >
You can also ( again may not be pertinent, use jquery to refresh a div element )