Using MYSQL query data with jQuery Autocomplete - php

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};";

Related

How to use values (PHP) in JavaScript

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.

Why php functions or classes cannot work like jquery plugins?

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

JSON object "undefined" error in Javascript

I am uploading a file using PHP and want to return the file name and the file status to javascript. In PHP I create the json object by:
$value = array('result' => $result, 'fileName' => $_FILES['myfile']['name']);
print_r ($value);
$uploadData = json_encode($value);
This creates the json object. I then send it to a function in javascript and recieve it as a variable called fileStatus.
alert (fileStatus);
It displays
{"result":"success","fileName":"cake"}
which should be good. But when I try and do
fileStatus.result or fileStatus.fileName
I get an error saying that they are undefined. Please help I'm really stuck on this. Thanks.
The fileStatus is just a string at this point, so it does not have properties such as result and fileName. You need to parse the string into a JSON object, using a method such as Firefox's native JSON.parse or jQuery's jQuery.parseJSON.
Example:
var fileStatusObj = jQuery.parseJSON(fileStatus);
If the alert displays {"result":"success","fileName":"cake"} then you probably still have to turn the string into a JSON object. Depending on the browsers you are developing for you can use the native JSON support or the JSON.org implementation to turn your string into an object. From there on it should work as expected.
When you are setting the variable, do not put quotes around it. Just set the variable like this:
var fileStatus = <?php echo $uploadData; ?>;
or:
var fileStatus = <?=$uploadData?>;
Do not do this:
var fileStatus = '<?php echo $uploadData; ?>';

Suggestive Search From JS Array, Possible?

Ok so what i want to be able to do is to perform a suggestive style search using the contents of an array instead of a doing a mySQL database query on every keyup.
So imagine a javascript object or array that is full of people's names:
var array = (jack,tom,john,sarah,barry,...etc);
I want to then query the contents of this array based on what the user has typed into the input box so far. So if they have typed 'j',both jack and john will be pulled out of the array.
I know this is possible via php mysql and ajax calls, but for reason of optimization I would like to be able to query the js array instead.
Hope someone can help me with this!
W.
as the name suggests, this finds elements of an array starting with the given string s.
Array.prototype.findElementsStartingWith = function(s) {
var r = [];
for(var i = 0; i < this.length; i++)
if(this[i].toString().indexOf(s) === 0)
r.push(this[i]);
return r;
}
// example
a = ["foo", "bar", "fooba", "quu", "foooba"];
console.log(a.findElementsStartingWith("fo"))
the rest is basically the same as in ajax-based scripts.
http://wwwo.google.com?q=autosuggest+using+javascript
AJAX calls fetch the contents from another serverside script files. You already have your data in the JS. Read a AJAX tutorial doing this. Then, just remove the parts where AJAX calls are made and replace it with your array's contents, and you're good to go.
I ended up using the following function to build my AJAX free instant search bar:
Example JS object being searched:
var $members = {
"123":{firstname:"wilson", lastname:"page", email:"wilpage#blueyonder.co.uk"},
"124":{firstname:"jamie", lastname:"wright", email:"jamie#blueyonder.co.uk"}
}
Example of function to search JS object:
$membersTab.find('.searchWrap input').keyup(function(){
var $term = $(this).val(),
$faces = $membersTab.find('.member'),
$matches = [];
if($term.length > 0){
$faces.hide();
$.each($members,function(uID,details){
$.each(details,function(detail,value){
if(value.indexOf($term) === 0){//if string matches term and starts at the first character
$faces.filter('[uID='+uID+']').show();
}
});
});
}else{
$faces.show();
}
});
It shows and hides users in a list if they partially match the entered search term.
Hope this helps someone out as I was clueless as to how to do this at first!
W.

serialize/unserialize in jQuery [closed]

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;
}

Categories