Why php functions or classes cannot work like jquery/ javascript plugins?
For instance,
a jquery plugin,
(function($){
// Attach this new method to jQuery
$.fn.extend({
// This is where you write your plugin's name
popup: function(options) {
// Set the default values, use comma to separate the settings, example:
var defaults = {
widthPopup: 500,
absoluteLeft: '500px'
}
var options = $.extend(defaults, options);
var o = options;
var $cm = this.click(function(e){
...
return false;
});
}
});
})(jQuery);
and then here is how you can use the plugin,
$('.click-me').popup();
or
$('.click-me').popup({widthPopup:300,absoluteLeft:'50%' });
or
$('.click-me').popup({absoluteLeft:'50%' });
as for a php function,
function test($parameter_1 = 100, $parameter_2 = false) {
....
}
and you have to call the function like this,
echo test();
or
echo test($parameter_1 = 50, $parameter_2 = true);
or
echo test(10, true);
and it won't work if you call the function like this,
echo test($parameter_2 = true);
Can you see what I find that php is arbitrary and a bit 'falling behind'??
Or maybe there is some advanced level of php I haven't learned yet??
You are mixing a hash as an argument with normal arguments. You can still do this in PHP:
echo test(array('parameter_2' => true));
echo test(array('parameter_1' => false, 'parameter_2' => true));
But I doubt that you find this pretty.
What you are describing are two different things. In the JavaScript example, you're passing associative array (hash, map, JSON, whatever ...), but in PHP, you're using named parameters.
So the matching code in PHP would be
function test($parameters) { ... }
and calling it via
test(array('parameter_1' => 50, 'paramater2' => true));
it's not as beautiful as the JavaScript version, but it does the same thing. Basically the only difference here is, that in JavaScript, you don't have to use the array() function to create an associative array, you can just type
{ javascript: "is", cool: true }
and it will work. The PHP alternative here is
array("javascript" => "is", "cool" => true)
The biggest reason is jQuery is javascript which is a prototype language. PHP simply is not a prototype language.
Or maybe there is some advanced level of php I haven't learned yet??
Yea, there is some basic level of php you haven't learned yet
Related
I'm trying to query data with MYSQL,
then link it to an <input> with jQuery's Autocomplete.
I'm still not used to using PHP inside Javascript, so I'm not sure how to get contents
inside an array. When every I console.log my PHP for debugging, it says Array.
Here is my JS code:
var SOMETHING = ["<?php echo $SOMETHING; ?>"];
//console.log(SOMETHING);
$( "#input_add_album" ).autocomplete({
source: SOMETHING
});
Here is my PHP code:
global $SOMETHING;
$SOMETHING = array();
$sql = "
select B from A
";
$stmt = $dbh->query($sql);
$result = $stmt->fetchAll();
foreach ($result as $SOME_CONTENT) {
array_push($SOMETHING, $SOME_CONTENT["SOME_CONTENT"]);
}
This question is old but I'm going to go over the 2 most likely solutions. The problem your having is that your trying to echo an Array to see it's contents and that isn't possible. It's also not possible for the JavaScript interpreter to interpret PHP. PHP processes .php files on your host and then serves them to the clients machine. The client end should never see any PHP, it would not know what to do with it. So the end result after the PHP files are run from server, must be a well formatted document to fit the guidelines of a file type the browser can handle, in this case html and JavaScript. So then in order to log the contents of a PHP variable to the console with JavaScript, it must be in a form JavaScript understands. Luckily for you, there is a format that JavaScript understands and most other languages support. The way to move any string, number, array or associative array to JS is with JSON. JavaScript Object Notation. Just remember, that associative arrays in PHP become objects in JavaScript.
$regular_array = json_encode(array( 'words', 'to', 'send' ));
$php_assoc = json_encode(array(
'assoc' => 'arrays',
'become' => 'JavaScript',
'objects' => array(
'this','will','be',1,array()
),
));
echo "
<script>
/** Check that window.console.logs isn't undefined, if we were just
* using JavaScript I wouldn't be so verbose. Since our PHP variable is
* traveling so far from home, I want to make sure we get the right address
*/
if (window && 'console' in window ) {
window.console.log({$regular_array});
window.console.log('JS object with array inside', {$php_assoc});
}
</script>";
That will log the values out to the browsers console. It would be the equivalent of logging the following array and object to the console with regular old JavaScript.
var regularArray = [ 'words', 'to', 'send' ];
var phpAssoc = {
assoc : 'arrays',
become : 'JavaScript',
objects : [ 'this', 'will', 'be', 1, [] ]
};
In Google Chrome, the phpAssoc object looks like this in the console. It can be fully expanded, looked through, and used like any other JavaScript object.
Object {assoc: "arrays", become: "JavaScript", objects: Array[5]}
*In this example I didn't save the PHP output into a JavaScript variable, but you can see how to inject the value into console.log so you can do the same exact thing with echo "var something = {$some_other_thing};";
I've language files like "en.lang.php":
/* english language */
return array(
"random.key.one" => "random value one",
"random.key.two" => "random value two);
Usage (the quick & dirty way):
/* random_template.php */
$language = "en";
$file = $language . ".lang.php";
$text = include($file);
echo $text["random.key.one"]; // "random value one"
Question:
How is it possible to use this values in JavaScript?
Idea:
Generate en.lang.js with a function that returns the needed value, usage:
alert(get_text("random.key.one"));
Problem: I've to flush the cache everytime the *.lang.php-file was changed. Not that user-friendly.
Thanks in advance!
If you're using PHP >= 5.2.1 (.0, technically), the easiest way I can imagine is as follows:
Have a file that generates a JSON-array with
echo 'set_text(' . json_encode(include($file)) . ')';
JavaScript-wise:
var texts = [];
function set_text(languageTexts){
texts = languageTexts;
}
function get_text(key) {
return texts[key];
}
Try to cache control the page and set it to no cache so it will load from origin.
And if you want to play with PHP and JS you have to keep in mind that PHP is server side and JS is client side. So best thing i can suggest is to use Ajax. Its prety easy to use JS on the page and get JS to query the server that process data with php.
I'm writing a unit testing platform and I want to be able to dynamically generate a function based off of each function in the web service I am testing. The dynamic function would be generated with default(correct) values for each argument in the web service and allow them to be easily traded out with incorrect values for error testing.
$arrayOfDefVals = array(123, 'foo');
testFunctionGenerator('function1', $arrayOfDefVals);
//resulting php code:
function1Test($expectedOutput, $arg1=123, $arg2='foo')
{
try
{
$out = function1($arg1, $arg2);
if($expectedOutput === $out)
return true;
else
return $out;
}
catch ($e)
{
return $e;
}
}
This would allow me to quickly and cleanly pass one bad argument, or any number of bad arguments, at a time to test all of the error catching in the web service.
My main question is:
Is this even possible with php?
If it's not possible, is there an alternative?
EDIT: I'm not looking for a unit test, I'm trying to learn by doing. I'm not looking for advice on this code example, it's just a quick example of what I would like to do. I just want to know if it's possible.
I would not try that first as PHP has not build-in macro support. But probably something in that direction:
function function1($param1, $param2)
{
return sprintf("param1: %d, param2: '%s'\n", $param1, $param2);
}
/* Macro: basically a port of your macro as a function */
$testFunctionGenerator = function($callback, array $defVals = array())
{
$defVals = array_values($defVals); // list, not hash
return function() use ($callback, $defVals)
{
$callArgs = func_get_args();
$expectedOutput = array_shift($callArgs);
$callArgs += $defVals;
return $expectedOutput == call_user_func_array($callback, $callArgs);
};
};
/* Use */
$arrayOfDefVals = array(123, 'foo');
$function1Test = $testFunctionGenerator('function1', $arrayOfDefVals);
var_dump($function1Test("param1: 456, param2: 'foo'\n", 456)); # bool(true)
Probably this is helpful, see Anonymous functionsDocs, func_get_argsDocs, the Union array operatorDocs and call_user_func_arrayDocs.
Well, for starters, you can set default parameters in functions:
function function1Test($expectedOutput, $testArg1=123, $testArg2='foo') {
...
}
Beyond that, I'm not really sure what you're trying to achieve with this "function generator"...
Read about call_user_func and func_get_args
This example from the manual should get you on the right track:
<?php
call_user_func(function($arg) { print "[$arg]\n"; }, 'test'); /* As of PHP 5.3.0 */
?>
If it's a function you have file access to (i.e., it's not a part of the PHP standard library and you have permissions to read from the file), you could do something like this:
Assume we have a function like this located in some file. The file will have to be included (i.e., the function will have to be in PHP's internal symbol table):
function my_original_function($param1, $param2)
{
echo "$param1 $param2 \n";
}
Use the ReflectionFunction class to get details about that function and where it's defined: http://us2.php.net/manual/en/class.reflectionfunction.php.
$reflection = new ReflectionFunction('my_original_function');
Next, you can use the reflection instance to get the path to that file, the first/last line number of the function, and the parameters to the function:
$file_path = $reflection->getFileName();
$start_line = $reflection->getStartLine();
$end_line = $reflection->getEndLine();
$params = $reflection->getParameters();
Using these, you could:
read the function out of the file into a string
rewrite the first line to change the function name, using the known function name as a reference
rewrite the first line to alter the parameter defaults, using $params as a reference
write the altered function string to a file
include the file
Voila! You now have the new function available.
Depending on what it is you're actually trying to accomplish, you could also potentially just use ReflectionFunction::getClosure() to get an closure copy of the function, assign it to whatever variable you want, and define the parameters there. See: http://us.php.net/manual/en/functions.anonymous.php. Or you could instantiate multiple ReflectionFunctions and call ReflectionFunction::invoke()/invokeArgs() with the parameter set you want. See: http://us2.php.net/manual/en/reflectionfunction.invokeargs.php or http://us2.php.net/manual/en/reflectionfunction.invoke.php
First off, I do not want what is in the URL query. I want what PHP see's in the$_GET array.
This is because the URL query will not show all the params if mod_rewrite has been used to make pretty URLs
So is there a way to get the query string that would match exactly what is in the php $_GET array?
--
I came up with a way myself using PHP and JavaScript like so:
function query_string()
{
<?php
function assoc_array_to_string ($arr)
{
$a = array();
foreach($arr as $key => $value)
{
$str = $key.'='.$value;
$a[] = $str;
}
return implode("&",$a);
}
?>
return '<?=urlencode(assoc_array_to_string($_GET))?>';
}
...but I need to do this with just javascript if possible because I can't put PHP code in a .js file.
Won't JavaScript "only see" the query string? How would client-side script know about any rewrite rules?
The only way I can think of is to use PHP -- echo it into a variable in an inline script in your main page rather than the JS file.
In your page <head>:
<script type="text/javascript">
var phpQueryParams = <?php print json_encode($_GET); ?>
</script>
Assuming at least PHP 5.2, otherwise use an external package
The query string is found in window.location.search, but that's the raw query string. So if you run something like this:
(function () {
QueryStr = {}
QueryStr.raw = window.location.search.substr(1);
var pairStrs = QueryStr.raw.split('&');
QueryStr.val = {}
for(var i=0,z=pairStrs.length; i < z; i++) {
var pair = pairStrs[i].split('=');
QueryStr.val[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
})();
You'd have something very much like $_GET in QueryStr.val.
Of course, you mention that you've mixed things up a bit using mod_rewrite, which is cool, but since we don't know your rewrite scheme, we can't help specifically with that.
However... you know your rewrite scheme, and you could probably modify the code I gave above to operate on some other part of window.location. My bet is that you'd want to split window.location.pathname on the / character instead of &.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Is there something like serialize/unserialize PHP functions in jQuery?
These functions return a string representations of an array or an object which can than be decoded back into array/object.
http://sk2.php.net/serialize
jQuery's serialize/serializeArray only works for form elements. I think you're looking for something more generic like this:
http://code.google.com/p/jquery-json/
This plugin makes it simple to convert to and from JSON:
var thing = {plugin: 'jquery-json', version: 2.2};
var encoded = $.toJSON(thing);
//'{"plugin":"jquery-json","version":2.2}'
var name = $.evalJSON(encoded).plugin;
//"jquery-json"
var version = $.evalJSON(encoded).version;
// 2.2
Most people asked me why I would want
to do such a thing, which boggles my
mind. Javascript makes it relatively
easy to convert from JSON, thanks to
eval(), but converting to JSON is
supposedly an edge requirement.
This plugin exposes four new functions
onto the $, or jQuery object:
toJSON: Serializes a javascript object, number, string, or arry into JSON.
evalJSON: Converts from JSON to Javascript, quickly, and is trivial.
secureEvalJSON: Converts from JSON to Javascript, but does so while checking to see if the source is actually JSON, and not with other Javascript statements thrown in.
quoteString: Places quotes around a string, and inteligently escapes any quote, backslash, or control characters.
Why, yes: jQuery's serialize. To unserialize, you'd have to code a function yourself, esentially splitting the string at the &'s and then the ='s.
I was trying to serialize a form and then save it, and when the user returned to the form unserialize it and repopulate the data. Turns out there is a pretty sweet jQuery plugin for doing this already: jQuery autosave. Maybe this will help out some of you.
I personally like Chris' unserialize function for handling jQuery's serialized strings, however, don't forget to also urldecode() them on the server-side as data such as 'email' => 'me%40domain.com' will be coming in if you use the function as-is.
Updated:
function _unserializeJQuery($rubble = NULL) {
$bricks = explode('&', $rubble);
foreach ($bricks as $key => $value) {
$walls = preg_split('/=/', $value);
$built[urldecode($walls[0])] = urldecode($walls[1]);
}
return $built;
}
You should use the native JSON library. For IE less than 8, you'll also need to use Crockford's JSON.js.
Follow the variable "formdata" and look at the supporting code to see how I got this to work in a wordpress environment.
I'm using this on the client side (js):
// bind button, setup and call .ajax
jQuery('#submitbutton').click(function() {
jQuery('#response_area').html('');
// put all name-values from form into one long string
var serializedformdata = jQuery('#submitform').serialize();
// configure array of options for the ajax call (can use a different action for each form)
options = {
type: 'POST',
url: sv_submitform_global_js_vars.ajaxurl,
datatype: 'json',
data: {
clienttime: getnow(),
sv_submit_form_check: jQuery('#sv_submit_form_check').val(),
// this data:action:'value' is specifically required by the wordpress wp_ajax_<value> action hook to process the received data on the php/server side
action: 'sv_submitform_hook',
formdata: serializedformdata,
},
beforeSend: beforesendfunc,
// process returned json formatted data in function named below
success: successfunc,
}
// execute the ajax call to server (sending data)
jQuery.ajax(options);
});
... and this on the server side (PHP) to get the data back out and into a nice associative array for server side database work.
/////////////////////////////////////
// ajax serverside data handler ///
/////////////////////////////////////
// Add AJAX actions for submit form
// Serves logged in users
add_action( 'wp_ajax_sv_submitform_hook', 'sv_submitform_handler' );
// Serves non-logged in users
add_action( 'wp_ajax_nopriv_sv_submitform_hook', 'sv_submitform_handler' );
// this is the function that processes the input from the submit form
function sv_submitform_handler(){
date_default_timezone_set('EST');
$servertime = date('h:i:s a').' Server Time';
// fda = form data array can be used anywhere after the next statement.
// example: if ($fda['formfieldbyname'] == 'something'){...};
parse_str($_POST['formdata'],$fda);
// this is how the nonce value is read
// form side is wp_nonce_field('sv_submitform','sv_submitform_check');
if (!check_ajax_referer('sv_submitform', 'sv_submitform_check', false )){
$data = $servertime . ' (Security Failed)';
} else {
$data = $servertime . ' (Security Passed)';
};
$returndata = array('data' => $data);
exit(json_encode($returndata));
};
And for the WordPress coders out there, it took me a while to realize that the wp_ajax_ hook had to be in either a plugin file or my child theme's functions.php. It will not work in a normal page template!
As of version 1.4.1 of jQuery there is a jQuery.parseJSON() function built in.
http://api.jquery.com/jQuery.parseJSON/
I had the same problem recently, I was using jQuery's .serializeArray() to post form data for validation via an AJAX call. On the server side I needed to split this object down into an associative array that would replicate the original $_POST data structure, so I wrote this little function:
function unserializeMe($obj) {
$data = array();
foreach($obj as $arr) {
$data[$arr['name']] = $arr['value'];
}
return $data;
}
Then all you have to do is cast the input object to an array type before passing it in the funciton call:
$objData = (array) $_POST['data'];
$data = unserializeMe($objData);
Use function parse_str.
$array = array();
$string = "title=Hello&desc=World=&s[]=5&s[]=6&s[]=7";
parse_str($string, $array);
description on php.net
I also wrote a function to parse the jQuery .serialize() function:
function createArray($rubble) {
$bricks = explode('&', $rubble);
foreach($bricks as $key => $value) {
$walls = preg_split('/=/', $value);
$built[$walls[0]] = $walls[1];
}
return $built;
}