I'm setting an array to a hidden field using JavaScript. However, the issue is that the array gets converted to a string on form submit when I catch it using PHP.
This is the code that sets the hidden input field value:
document.getElementById("hiddenFieldId").value = arrayFromJS;
Is there any workaround for this?
Actually the problem is earlier I had a select box which sent it's values nicely on form submit. But now I've got a custom select box using JS which sets comma separated values in a hidden field... So in a nutshell I want that input field to act like a pseudo-select box
You should JSON encode/decode the value:
On the client side you use JSON.stringify to encode the array:
document.getElementById("hiddenFieldId").value = JSON.stringify(arrayFromJS);
And then on the server side you can use json_decode:
$arr = json_decode($_POST['hiddenFieldId']); // Fetch the data from POST / GET
foreach ( $arr as $value ) {
// iterate the array on the server side.
}
unset($arr); // Remember to unset the $arr variable
If you know you are handeling a simple array (with string only) you can join the string in javascript and explode/split it php:
document.getElementById("hiddenFieldId").value = arrayFromJS.join('/:/');
PHP:
$arr = explode('/:/', $_POST['hiddenFieldId']);
To support older browser you can use this JSON plugin to the front end: https://github.com/douglascrockford/JSON-js
Related
I see many questions about passing an array as a query string in PHP, and it seems the prevailing way is using brackets as in key[]=foo&key[]=bar.
However I cannot find a straight answer about how to send an object (or a key=>value associative array - same thing) as a query string.
Currently, however I do it is:
STRING
?foo=bar&hello=world
Then on the server side, I would do:
<?php
$array = array();
$array['foo']=$_GET['foo'];
$array['hello']=$_GET['hello'];
?>
Of course when using $_POST, this is very simple with an ajax request. Any object you send automatically serializes and isn't a problem.
Is this the best way to handle it, or is there some other standard for sending an object in a query string using PHP?
You can use an associative array in a form and in the query string:
object[foo]=bar&object[hello]=world
To build it URL encoded:
$data['object']['foo'] = 'bar';
$data['object']['hello'] = 'world';
echo http_build_query($data);
Yields:
object%5Bfoo%5D=bar&object%5Bhello%5D=world
You can go many levels and/or use dynamically added elements. In general, in text form, it looks just like a PHP array
object[foo][more][even more][]
Or:
object[foo][][more][even more]
I am POSTing a form input with value:
http://www.domain.com/script.php?var1=1120&var2=254949&url=http%3A%2F%2Fwww.domain2.com%2Ffile%2Bname%3Fvar1%3Dvalue1
on the server (PHP) I get this value:
http://www.domain.com/script.php?var1=1120&var2=254949&url=http://www.domain2.com/file+name?var1=value1
is there anyway to receive the original un-decoded value?
You need to encode only part of your string. In order to achieve that, use function explode to make array of two elements, encode the second one and put them again together. Something like could be helpful.
$str ='http://www.domain.com/script.php?var1=1120&var2=254949&url=http://www.domain2.com/file+name?var1=value1';
$url = explode('url=',$str);
$str2 = $url[0].'url='.urlencode($url[1]);
echo($str2);
I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517
I am passing a jquery array called 'selected' full of ids along with the opening of an ajax modal.
$('#dtDelete').on('click', function () {
$('#modal-ajax').load('/modals/m__delete.php?selected='+selected);
$('#modal-ajax').modal('show');
});
On the modal php page count($_GET['selected']); always returns 1 no matter what. I am trying to get an actual count of the number of values in the array. Turns out this is because the array is a string as noted below.
var_dump($_GET['selected']); returns something along the lines of string(69) "187419,187420,187413,187414,187415,187416,187417,187418,187421,187422" which is something I am not accustomed to (sort of new to jquery). I need to do processing in php using foreach on this array. Can I 'convert' this to a 'normal' php array so count() will work as expected and I can process it normally in php?
Lastly, this array may or may not be extremely large at times. The jquery function above opens an ajax modal (I am using the modal as a confirmation box for the user whether they really want to delete the entries in the selected array) and I know the $_GET method has limits to the amount of data it can pass. I can't do $_POST because this is a modal and I need to load it then show it... how else can I pass this data?
$_GET['selected']
returns the STRING after the attribute 'selected', and count(string) is 1 not matter what ( it's not a multi-dimension array to be greater than 1).
As for the comma separated string example you gave, you may use the following :
$selected = $_GET['selected'];
//test wether the string has contents
if(strlen($selected)!=0) {
$selected_array = explode(',',$selected); //this is the new array that you want
}
else {
//the string is empty
}
There are many string functions you may check at : http://www.php.net/manual/en/ref.strings.php
Is there no way of submitting a serialized parameter without ajax?
I want to access, like, an json encoded parameter when I process the POST from the form, something like: $params = json_decode($_GET['params']);
Any ideas, besides iterating each input and append it to a hidden one that will contain all parameters in an encoded form, ?
Update
I'm using codeigniter, so I would rather do something like
$search = json_decode($this->input->get('params'));
updateName($search['name']);
updateGender($search['gender']);
Than
updateName($this->input->get('name'));
updateGender($this->input->get('gender'));
Not sure if I am missing something here but you can only do a json_decode() on a json object/array.
$this->input->get() will return the whole $_GET array AS A PHP ARRAY, so you dont need to do anything JSON'ick with it to be able to use it as an array.
so would this not do what you want?
$search = $this->input->get();
updateName($search['name']);
updateGender($search['gender']);
If you want to pass it through the XSS filter first just use
$search = $this->input->get(NULL, TRUE);