Retrieve data from PHP file using $.getJSON - javascript

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

Related

Deconstructing a JSON object

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.

Pass php array values as JavaScript array values

I have a PHP array like this.
Array
(
[0] => hal([[br,1],[cl,4]])
[1] => alk([[nc(1),1,2],[nc(1),3]])
)
How to pass to JavaScript like below.
var hal=[["br",1],[cl,4]];
var alk=[[nc(1),1,2],[nc(1),3]];
I write some code
<script>
var data = <?=json_encode($input);?>; //$input is name of the php array
var hal=[data[0].substring(5,data[0].lastIndexOf(']'))];
var alk=[data[1].substring(5,data[1].lastIndexOf(']'))];
document.write(hal[0]);
</script>
The output is [br,1],[cl,1] and my expected output is like the one below.Any ideas? Thank you.
document.write(hal[0]); => ["br",1]
document.write(hal[0][0]); => ["br"]
If you want multiple variables, you'll want to loop through the array; you can grab the names using a regular expression. If you're trying to turn this into valid data you can parse, like a JSON string, you're going to have to do an awful lot of work; likely wherever you're getting this string from would be a better place to look to. Have them pass you a valid JSON string instead.
<script>
<?php foreach($input as $v) {
preg_match("/(\w+)\((.*)\)/", $v, $matches);
$var = $matches[1];
$val = str_replace("'", "\\'", $matches[2]);
echo "var $var = '$val';\n";
} ?>
</script>
There's a package called Transform PHP Vars to JavaScript by Jeffrey Way that you can use to transfer your variable easily to your Javascript.
First, create an implementation of the Laracasts\Utilities\JavaScript\ViewBinder interface. This class is in charge of inserting the given JavaScript into your view/page.
<?php
class MyAppViewBinder implements Laracasts\Utilities\JavaScript\ViewBinder {
// $js will contain your JS-formatted variable initializations
public function bind($js)
{
// Do what you need to do to add this JavaScript to
// the appropriate place in your app.
}
}
Next, put it all together:
$binder = new MyAppViewBinder;
$javascript = new PHPToJavaScriptTransformer($binder, 'window'); // change window to your desired namespace
$javascript->put(['foo' => 'bar']);
Now, you can access window.foo from your JavaScript.
I found an answer for my problem.Here i pass value from php as string.Then that string convert it to an object.
<?php
$input="hal([[br,1],[cl,4]])";
preg_match('#^([^[]+)?([^)]+)#i',$input, $hal); //get string as '[[br,1],[cl,4]]'
?>
<script>
var hal1 = <?=json_encode($hal[2]);?>; //'[[br,1,2],[cl,1,2]]' pass to javaScript
function toJSObject(str){
str = str.replace(/([a-zA-Z]+)/g, '"$1"');
return (JSON.parse(str))
}
var hal = toJSObject(hal1); // pass to JS object [['br',1,2],['cl',1,2]]
document.write(hal);
</script>
And also get this as right.
document.write(hal[0]); => ["br",1]
document.write(hal[0][0]); => ["br"]

Overwriting Original Values In Collections

I am fetching data from database and storing it on $groups. It has different created_at for each entry.
I want to overwrite on created_at field in collection, just before returning it to the view, and have nice ->diffForHumans() version.
$groupsArray = $messages;
foreach($groupsArray as $key => $group) {
var_dump($groupsArray[$key]['created_at']); // works: 2015-10-17 21:55:46.000000'
var_dump($groupsArray[$key]['created_at']->diffForHumans()); // Error: A two digit month could not be found Data missing
$groupsArray[$key]['created_at'] = $groupsArray[$key]['created_at']->diffForHumans(); // Not Working
}
return $groupsArray->toJson();
If I change groupsArray = $messages->toArray();, the '// Error' bit of above chunk changes to Call to a member function diffForHumans() on string.
Eventually, I need to return it as json as it is ajax request. I want to overwrite on created_at, so I can use group[i]['created_at'] in javascript part in the view, after returning and get Carbon versions.
First, make sure 'created_at' is in your $dates array in your model.
Like described on http://laravel.com/docs/5.1/eloquent-mutators#date-mutators
Second, you can iterate and update over a collection by doing the following:
$messages->transform(function ($item, $key) {
$item->difference = $item->created_at->diffForHumans(); // 10 hrs ago
return $item;
});
$messages->toJson();
use &you can replace the original value !
foreach($groupsArray as &$key => &$group) {
var_dump($groupsArray[$key]['created_at']);
var_dump($groupsArray[$key]['created_at']->diffForHumans());
$groupsArray[$key]['created_at'] = $groupsArray[$key] ['created_at']->diffForHumans(); // Not Working
}

Send multiple base64 to php

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!

passing array of objects from javascript to php

So I built an array of objects for passing to PHP, but I am wondering wether this is the cleanest way to pass them and will be the easiest to deal with in PHP.
I am partly thrown off by the fact that the number of group components are variable based on what my google maps reverse-geocoder returns.
Each group will be inserted as a separate row into MySql with the parameters of 'name' and 'type'
var neighborhood = extractLongFromAddress(results[0].address_components, "sublocality");
var town = extractLongFromAddress(results[0].address_components, "locality");
var stateShort = extractShortFromAddress(results[0].address_components, "administrative_area_level_1");
var stateLong = extractLongFromAddress(results[0].address_components, "administrative_area_level_1");
var country = extractLongFromAddress(results[0].address_components, "country");
var groups=[];
if(town && stateShort){
groups.push({name: town+", "+stateShort,
type:"city"
});
}
if(neighborhood && stateLong){
groups.push({name: neighborhood+", "+stateShort,
type:"neighborhood"
});
}
if(stateLong){
groups.push({name:stateLong,
type:"state"
});
}
if(country){
groups.push({name:country,
type:"country"
});
}
console.log(groups);
sincere thanks for any help. It is greatly appreciated.
Just convert the array to a JSON string by JSON.stringify() and send it to php; In PHP you'll do json_decode()

Categories