A JSON encoded array is passed from PHP to an HTML document. It is not at all clear how to deconstruct that array into javascript-usable pieces. For example, consider the following HTML:
<div id="options">{"foo":[{"id":1},{"id":3}], "bar":[{"id":2},{"id":4}]}</div>
The only a priori known element of this array is that the key id exists. The indices, I know, can be found with
var data = JSON.parse($("#options").text());
$.each(data, function(index) {
// index will be foo & bar
});
The use case is to use the index and id to add an attribute to elements in a document. I have not yet stumbled upon the technique to return the ids associated with each index. How best can that be done?
Edit - a clarification of the use case - the long story
I want to re-enable some options on a form based on properties of an entity (in a Symfony application). Disabled options cannot be modified, but are also not not persisted - their values are set to null. I've built a service to determine the option elements that are disabled and send those elements to the form document as a JSON object. I'm assuming for now that the specific options are not known until the form is created. In the example above, foo & bar represent possible options, and the ids correspond to the option. For example, a Household entity might have Reason options selected but disabled of "Low wages" (id = 3). This would show up in as ...id="options">{"reasons":[{"id":3}]}<.... I would the use this information to remove the disabled="disabled" attribute from the set of checkboxes for the Reason, id=3 (i.e., id="household_reasons_3") field. I hope this makes sense.
Edit #2, by request - the PHP code creating the object.
The result of getMetatData() appears in the document at #options. From the above edit, the Household entity is $object.
public function getMetaData($object) {
$data = array();
$className = get_class($object);
$metaData = $this->em->getClassMetadata($className);
foreach ($metaData->associationMappings as $field => $mapping) {
if (8 === $mapping['type']) {
$data[$field] = $this->extractOptions($object, $field);
}
}
return json_encode($data);
}
private function extractOptions($object, $field) {
$data = [];
$method = 'get' . ucfirst($field);
$itemName = substr($field, 0, -1);
$getter = 'get' . ucfirst($itemName);
$entity = $object->$method();
foreach ($entity as $item) {
if (method_exists($item, 'getEnabled') && false === $item->getEnabled()) {
$data[] = ['id' => $item->getId()];
}
}
return $data;
}
Long before the infinite monkey limit was reached I stumbled on a method to create the results I was looking for. My thanks go out to all who pushed for clarifications. So, for the object
{"foo":[{"id":1},{"id":3}], "bar":[{"id":2},{"id":4}]}
the script
var data = JSON.parse($("#options").text());
var i = 0
var output = [];
$.each(data, function(index, item) {
$.each(item, function(k, v) {
output[i] = "household_" + index + "_" + v.id;
i++;
});
});
output;
produces this:
["household_foo_1", "household_foo_3", "household_bar_2", "household_bar_4"]
I get the strings I need; I can take it from here.
Related
So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0] });
the variable "ids" is sent by post method
$.post( "deleterow.php", { v1: ids });
but it didn't worked so i try to see the response from post method and it says
"notice array to string conversion in C on line ... "
the line is of php page where i am writing the delete query
$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";
The whole php page works fine when trying with other values.
Because you send an array here:
$.post( "deleterow.php", { v1: ids });
so v1 contains an array of elements. But in your php code you treat it as a single element:
$id = $_POST["v1"];
Hence the notice array to string conversion.
If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:
$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
if ($first) {
$first = false;
} else {
$query += " OR";
}
$query += " `id` = '$id'"
}
This way you loop the array and append a id = ID for each array element.
Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?
I am using jquery ajax to get some data from server and I get them back in this format:
however when I print this data in javascript it gets printed ascending by id instead of descending like the data I recieved.
when I print it here it is how it looks:
it self orders everything in ascending order by letter and number, why does it do this?
Here is my code:
$.ajax("{{route("backend.blog.categories.getparents")}}", {
method: 'GET',
dataType:'json',
success: function(result) {
console.log("result.categories: " + result.categories);
I use this data to populate a select box and I need it to be in the same order I recieve it in and not ordered by javascript automatically. How do I do this?
$.each( result.categories, function( key, value ) {
console.log("key: " + key);
if(key != exclude){
parentCategories += '<option value=' + key + '>' + value + '</option>';
}
});
code on the server side:
$parentCategories = array();
foreach ($categories as $category) {
$parentCategories += [$category->id => $category->title];
}
if($categories){
return response()->json([
'status' => 'success',
'categories' => $parentCategories,
JSON - the notation you're using - doesn't have an order. If you want to give it a specific order you will have to save that explicitly or use an array. Either way, although according to the spec the order is not guaranteed, modern browsers in general do keep the order. Numeric looking keys however form a weird exception that you found now.
let orderKept = {"a2": "a", "a1": "b"};
let orderNotKept = {"2": "a", "1": "b"};
console.log(orderKept, orderNotKept);
Example way how this would typically be done properly (guaranteed to work by the spec and not just browser implementations) is an array of objects where every object has its own id property.
Of course you could move away from JSON, but keep the same notation and build your own parser, however I would definitely not recommend that.
I want to send multiple base64 strings via jquery's $post(). The number of strings are not always the same. How can I do this and fetch it in php?
Is it a good option to have all strings in an array and add them in $post()?
var items = [
"data:image/png;base64,i.....",
"data:image/png;base64,i....",
"data:image/png;base64,i...."
] //the number od these strings varies on each post
$.post("../send.php",
{
for(i=0;i<21;i++){
'item'+i: items[i]
}
},
)
php:
if($_POST['item1']){
$item1 = $_POST['item1'];
}
I would go with the following steps:
1) Create a form with the input fields that contain all these base64 strings. (the form and all its fields can all be hidden in html)
2) In my form all the input text fields can have the same name like in this case
<input type="text" name="text1[]">
2) When I need to add a new string, I shall add an input field in that form by using jQuery.append()
3) in my jquery post i will set the data to
$.post('../send.php',$('#myFormId').serialize(),function(){
// what i want to do with the response
})
4) in my php page I can easily loop over
foreach($_POST['item1'] as $item){
// do what you want with data
}
that's it!
Try this
JS :
$.post("../send.php",{items:items}); //send to server
PHP:
$_POST['items'] // catch in server
I would create a regular array of strings, and then iterate to the array of strings and add them as properties of an object using a for loop. Here's an example.
var items = []; // Empty array.
items.push(item1, item2, item3); // Add Base64 strings.
var postdata = {}; // An object for our postdata.
// Iterate through the array and add items as properties to the object.
for (var _i = 0, _j = items.length; _i < _j; _i++) {
postdata['item_'+_i] = items[_i]; }
// POST the object to the PHP file.
$.post("../send.php", postdata);
Then, in PHP, you get $_POST['item_1'] until $_POST['item_n'] from jQuery. :)
UPDATE
You can process the postdata in PHP like below.
<?php
foreach($_POST as $k => $v) {
// Do things for each item POSTED.
// This will end after the last POSTed item is reached.
// $k is the 'key', as in what's inside the square brackets of $_POST[]
// $v is the 'value', as in $_POST[key] = "THIS STUFF";
}
?>
Hope that was helpful!
I'm trying to set up a comments system on photos.
I understand how to use $.getJSON when the array is like this:
get.php:
$var = 5;
echo json_encode(array('var'=>$var));
main.php:
$.getJSON("get.php",function(data){
number = data.var; // number = 5
});
But I have a more complex thing.
My comments table has these 4 columns: id | photo_id | comment | date
For example let's say we're trying to retrieve the comment data from the photo with
photo_id == 1.
We don't know how many comments there might be.
In getcomments.php:
$photoid = 1;
$comment = mysqli_query($conn,"SELECT * FROM comments WHERE photo_id='$photoid'");
while($commentrow = $comment->fetch_assoc()) {
$comments[] = $commentrow;
}
Then you encode it:
echo json_encode($comments);
Which prints something like this (the photo has 2 comments):
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
How do I declare variables for the comments array?
$.getJSON("getcomments.php",function(data){
// how do I declare variables for the comments array, especially since you don't know how many there might be?
});
Additionally, I have two json arrays that need to be echoed within the same PHP file. i.e. echo json_encode(array('img1'=>$img1link)) and echo json_encode($comments); need to be echoed within the same PHP file, but it made the code stop working altogether.
If you want to display the comments you need to loop over the array. You can use for loop or forEach function.
$.getJSON("getcomments.php",function(data){
data.forEach(function(comment) {
$('div').append('<span>' + comment.comment + '</span>');
});
});
To display two JSONs you need to combine them into one JSON object.
echo json_encode(array('img' => $img1link, 'comments' => $comments));
[{"id":"1","photo_id":"1","comment":"text","date":"23858556"},{"id":"2","photo_id":"1","comment":"text","date":"23858561"}]
Using this JSON, data is an array and you should manage it as an array. You can loop through it using simple loops (for, while...) or using new functional methods like forEach, map, filter....
Please try with this example:
$.getJSON("getcomments.php",function(data){
data.forEach(function(item, index, all) {
console.log(item.comment);
});
});
Declare an object, and push it to the array.
var commentsArr = [];
for (var i = 0; i < data.length; i++) {
var objToPush = {
id: data.id,
comment: data.comment,
date: data.date
}
commentsArr.push(objToPush);
}
so I have a JSON object returned from a webservice. Now I want to:
get a subset which matches a categoryTitle i pass as parameter (this seems to work)
from my filtered resultset I want to get another array of objects (helpsubjects), and for each of this subjects I want to extract the SubjectTitle.
Problem: It seems my Array of HelpSubjects does not exist, but I can't figure out why and hope you could help.
Perhaps this piece of commented code makes it more clear:
$.fn.helpTopicMenu = function (data) {
that = this;
var categoryContent = contents.filter(function (el) {
return el.CategoryTitle == data.categoryTitle;
});
debug('categorys Content: ', categoryContent); //see below
var container = $('#subjectList');
var subjectList = categoryContent.HelpSubjects;
debug('Subjects in Category: ', subjectList); // UNDEFINED?!
$.each(subjectList, function (i, item) {
container.append(
$('<li></li>').html(subjectList[i].SubjectTitle)
);
});
the line debug('categorys Content: ', categoryContent); returns the following object as shown in the picutre (sadly I can't add a picture directly to the post yet, so here's the link): http://i.stack.imgur.com/0kKWx.png
so as I understand it, there IS actually a HelpSubjects-Array, each entry containing a SubjectTitle (in the picture there actually is only one entry, but I need to have the Artikel einfügen as my html.
Would be great if you can help me.
The variable categoryContent set is an array of objects.
Try debugging categoryContent[0].HelpSubjects and see if you can access the property. If so, you can also loop this array if need be.