Replicating preloaded HTML /DOM method results in an array using AJAX/PHP - php

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.

Related

How to encode php functions

I would like to encode a php page which contains some php functions.
For example, I have a page named: code.php with this functions:
<?php
function data(){
echo "foo";
...
}
function storage(){
echo "storage files..";
...
}
?>
I use these functions in my other php pages and I would like to protect them by other users. How can I encode their code?
I read about base64_encode() but the examples only show how to encode a string: how can I use this solution to encode and decode my php functions?
Thank you!
If you want to stop others from seeing your PHP code you can either make it as hard as possible (via minifying, obfuscating, whatever you wish to call it) or encrypt it.
There's an answer right here on SO with a few suggestions and another I'd add is ion cube.
With encrypted code you're likely to need further changes to your web server such as an apache module. With obfuscation it will just make it harder for the other developers to read, for instance changing variables and functions names to something meaningless and hard to read.
You will inevitably need to keep a copy of your unobfuscated PHP so you can work on it in a sane manner, which may be hard if you're only developing on your server.
To use Base64 you're probably thinking of doing something like this:
eval(base64_decode('ZnVuY3Rpb24gZGF0YSgpew0KZWNobyAiZm9vIjsNCn0NCmZ1bmN0aW9uIHN0b3JhZ2UoKXsNCmVjaG8gInN0b3JhZ2UgZmlsZXMuLiI7DQp9DQokZGF0YSA9ICdkYXRhJzsNCiRzdG9yYWdlID0gJ3N0b3JhZ2UnOw=='));
What's happening here is the Base 64 string is actually valid PHP, and you first decrypt it the eval it. An example of what the decoded string might look like:
function data(){
echo "foo";
}
function storage(){
echo "storage files..";
}
$data = 'data';
$storage = 'storage';
After the above eval call you would then do something like:
// call the data function
$data();
// call the storage function
$storage();
As stated from the documentation:
PHP supports the concept of variable functions. This means that if a
variable name has parentheses appended to it, PHP will look for a
function with the same name as whatever the variable evaluates to, and
will attempt to execute it.
So, calling $someVariable() will try to run a function named whatever $someVariable contains. If you set $someVariable to foo, it would try to run foo(), if you set $someVariable to sausage, it would try to run sausage() and so on.
Obviously bear in mind that you need to make sure these function variables' names aren't going to be used elsewhere.

PHP: Storing the array returned by a function

I have a below function structure
//function 1 definition
function1(data1) {
function2(data2);
}
//function2 definition
function2(data2){
return array();
}
Here all the user in another php file are calling my function1 and passing some data to it,which in turn enriches it and passes it to function2 which returns an array whose length differs depending upon the data passed.
So now I need to pass this array returned by function2 to function1 and then store entire array into a variable.
Is it possible ?
Posting my comments here in answer section due to the limitation of characters
First thing....yes I am new to PHP.....
Second thing.....I have tried this....using different methods...storing it into an array...using json_encode() to print it...but did not work.
Third thing....I read many things about using list() but examples always talk about accessing particular element of array and not about the entire array....so asking for help....Fourth thing....sentence "all the user in another php file are calling my function1" was a bad choice of words...Actually the mention was not necessary in the question...Here all users means....in other php I am getting data for all of my users from a database and then that data is being passed to function1 and then in turn function2.....

PHP int increase one row

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.

Jquery trying to access a php array and check what's inside of it

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.

.load() html content into a container in a loop

I have a container $('#container') and I want to dynamically load several elemtents into the container. I have a php layout called subElement.php. So my code looks like:
for(i = 0;i<10;i++){
$('#container').load('subElement.php?id='+i,function(data){});
}
Only one subElement.php layout is loaded in to the container. How can I do this in a better way?
Ideally, you should rewrite your PHP script to get all the data at once, so you only need one .load. Doing so will be faster and much gentler on the user's network connections.
However, since you asked us to work with what you have:
for(i = 0;i<10;i++){
$('#container').append($('<span>').load('subElement.php?id='+i));
}
If those <span> elements are going to mess up your code, though, you should go with a solution like Explosion Pills' instead.
.load will overwrite the contents each time. Instead, you have to append them, possibly like so:
$.get('subElement.php?id=+1', function (data) {
$("#container").append(data);
});
Each time through the loop, load() replaces the contents of $('#container') with the new thing that you've requested.
For efficiency, the best thing to do would be to ajax for all of the sub elements in one gulp, instead of making 10 separate HTTP requests.
Another way to do it, if for some reason you can't change the api to support getting multiple elements, is to use .get() and collect all of the answers before doing a single replacement.
You can use $('#container').append('some content') to add to #container.

Categories