serialize/unserialize in jQuery [closed] - php

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

Related

Using MYSQL query data with jQuery Autocomplete

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

Best way to output datas after insert record on database with ajax / JSON / php

I'm working on a project and I would like know which is the best way for show the data after having insert a record on the database having an complex structure html between use the structure in php or jQuery and why?.
Example of scenario:
I'm building a system of posts and comments. When the user write the post and publish it an call ajax trigger the function php and it insert the information on the database. until here all ok, but then I have to display the message insert on the wall of the user, so which the best way for display that post insert?
There are so many different way, but which is the best keeping attention on speed, security, and compatibility?
some example, suggest are welcome:
<script> // default example of call ajax
$.ajax({
type: "POST",
url: 'http://localhost/ajax_ouput_post',
dataType: 'json',
data: { id_user : 1, title : "Hello everyone", content : "Good morning" },
success: function(html) {
// output under php example
},
error: function(){
alert('Error on ajax call');
}
});
</script>
1- I create the template for the output in php.
<?php
function ajax_output_post() {
$title = $_POST['title'];
$content = $_POST['content'];
$id_user = $_POST['id_user'];
// all the check for the input
$query = // insert data on mysql #return id_post;
$select_last_post_mysql = // select the last query from the db using id_user and id_post
foreach ($select_last_post_mysql as $post) {
$template = // html structure;
$template .= // continue html structure;
if ($post->photo == 1) {
$template .= // <div>photo user</div>
}
$template .= // ecc...
}
echo json_encode(array('template' => $template));
}
?>
jquery output
<script>
$(#wall).append(html.template);
</script>
php second example with output jQuery template
<?php
function ajax_output_post() {
$title = $_POST['title'];
$content = $_POST['content'];
$id_user = $_POST['id_user'];
// all the check for the input
$query = // insert data on mysql #return id_post;
$select_last_post_mysql = // select the last query from the db using id_user and id_post
foreach ($select_last_post_mysql as $post) {
$title_json = $post->title;
$content_json = $post->content;
if ($post->photo == 1) {
$photo_user_json = $post->photo_user;
} else {
$photo_user_json = "";
}
$id_post = $post->id_post;
}
echo json_encode(array('title' => $title_json, 'content' => $content_json, 'id_post' => $id_post));
}
?>
jquery
<script>
// in jquery
var Template = {
main_container: "<div class='post_container' data-post='" + html.id_post + "'>",
title: "<div class='title'>" + html.title + "</div>",
content: "<div class='content'>" + html.content + "</div>",
close_main: "</div>",
run: function() {
return Template.main_container + Template.content + Template.close_main;
}
};
$('#wall').append(Template.run());
</script>
Well, there is not really a 'best' way to do this, it always depends on the concrete situation.
In your case you could:
simply attach the user post to the DOM via javascript, without knowing whether it was inserted to the database or not (because you have all data of the post at client side available, you do not need to select it again)
attach the user post by javascript (like in the point above) after you know it was inserted (in the success handler, but still no data in response from php)
I would recommend not to select the inserted data again anyway, except you need an auto generated value like id or inserted-timestamp, instead you could simply return the values of the request in your response after the insert.
Hope this helps.
There are a few ways to accomplish this, and there are tradeoffs to be made for each of them.
The simplest way to accomplish this is to retain the user input in javascript as answered by Nico above. The pro for this method is it is very simple to accomplish and move on to other problems and due to this simplicity, has few moving parts to be misused. The major con for this method is that it means the frontend is making blind assumptions about what is going on when the backend logic processes the data, which presents the risk of misinforming the user about what happened if the backend silently fails, and this sort of bug is often difficult to catch until it bites someone and they complain. This is probably your best answer for simple use cases, but if you intend to scale it or introduce significant complexity this makes the likelihood of bugs high and should be replaced.
As per your given example, you seem to be on this frame of thought already. So to address each of your given concerns, first I would say that compatibility is best addressed by being generally unopinionated. This is appropriate for a library meant to be used for general consumption, but is not necessarily preferable for a private project or internal business logic, which require opinion to execute a specific desired result. The major caveat in terms of compatibility is that templating is handled by the frontend at least as often as the backend. It may in some cases be done in ReactJS or Angular, or it may be done on the backend by Twig, or any number of other things. If you want wide compatibility, then this should have some configuration for whether to pass response in raw format or accompanied by a template. In the case of private business logic or an app you are building with a specific purpose, the underlying point is to accomplish a specific result, and either using the existing templating structure of the system or picking one and sticking to it is preferable so you are focusing on the end goal and not getting distracted. But either way a github library author and a app developer would likely solve this same problem in completely different ways, and neither of them are wrong.
In terms of security, the typical concerns all apply. Individual approach is mostly arbitrary, provided you cover these bases if user input is being output, entered into template content, or stored in a database.
In terms of speed, the javascript DOM option is always going to be the fastest. However you can make it almost as fast depending how much tolerance for optimization you have. You could perhaps use client side storage to cache unmodified templates client side, and just use a hash of the template content as its identifying key so it automatically flushes when you change the template on the server. If you then send the key to the server and it matches, you don't need to serve the template in the response body because the client already has the correct one. If the template hash on the backend is different, you serve the new one, bust the storage cache for that template and replace the key and value with the new one. This will make the template body, which is almost certainly the longest part of the response, only need to be sent when changes are made. You would need to inject the values into the static template clientside to do it this way, and still obtain those from the server on each request. On the backend, you do not want to make a separate SELECT statement. You want to store the values in an array and just return those if your INSERT query is successful, like maybe something like this:
<?php
// List of keys that MUST be present for the query to succeed. Don't bother calling the db if any of these did not come in the request.
$expected_keys = [
'id_user',
'title',
'content' // add whatever else has to be passed
];
// key/val for db insert
$vals = [];
try {
// verify expected keys are provided
foreach ( $expected_keys as $k => $expected ) {
if !(array_key_exists ( $expected, $_POST ) ) {
// not a valid post, return an error
throw new \InvalidArgumentException( sprintf( 'Expected field [%1$s] was not provided. ', $expected ) );
}
// retain the field in $vals for insert
$vals[ $expected ] = $_POST[$expected];
}
$dsn = "mysql:host=localhost;dbname=myDatabase;charset=utf8mb4";
$options = [
\PDO::ATTR_EMULATE_PREPARES => false,
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC
];
$pdo = new \PDO($dsn, "username", "password", $options);
$stmt = $pdo->prepare(
'INSERT INTO `myTable` ( `:' .
implode( '`, `:', array_keys( $vals ) ) .
'` ) VALUES (' .
implode( '", ":', $vals ) .
');'
);
$stmt->execute( $vals );
$stmt = null;
}
// User error
catch \InvalidArgumentException $e {
// return 400 Bad Request and $e->getMessage() as the error message
}
// Server error
catch \Exception $e {
// log or whatever and return a 500 error
}
// return success with whatever you need to send back from $vals or $_POST

Searching within JSON with PHP for server side implementation of autocomplete jQuery plugin

I am trying to use jQuery Autocomplete Plugin in my PHP web application.
I have a JSON file on the server that has the data for the search. It looks like this:
{
"_E161": {
"keggId":"rn:R05223",
"abbrev":"ADOCBLS",
"name":"Adenosylcobalamin 5'-phosphate synthase",
"equation":"agdpcbi[c] + rdmbzi[c] -> h[c] + adocbl[c] + gmp[c] ",
},
"_E163": {
....
}
}
I would like to go through this JSON file (has 3500 entries) with PHP script that gets search term from the jQuery autocomplete plugin. Then return the entries that contain search term back to client side to populate autocomplete.
What would be a better way to implement this? My first guess is to loop through the JSON file and use strpos() But I suspect that might be slow?
You can make use on preg_grep (Return array entries that match the pattern),
// sanitize, and perform some processing to ensure is a valid regex pattern
$pattern = ...;
$json = json_decode( ... );
$arr = array();
foreach ($json as $key=>$arr)
{
$arr[$key] = $arr['name'];
}
$matches = preg_grep("/$pattern/i", $arr);
// $matches will hold the matches
// and you refer back to the $json using associate key

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

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.

Categories