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!
Related
I'm sending my mysql result to an associative array and then encoding with JSON
$showDisplayResult = $mysqlConn->query($getDisplayPage);
while($row=mysqli_fetch_assoc($showDisplayResult))
{
$rows[] = $row;
}
$showDisplays = json_encode($rows);
ANd in my main page I'm using javascript to grab this, parse it and append the correct variables into my URL. The functionality seems to work but it only shows undefined as the variables in the URL.
Here's the javascript:
<script type="text/javascript">
let obj = <?php echo $showDisplays; ?>;
//obj = JSON.parse(obj);
let params = new URL(document.location).searchParams;
params.set("pageID", obj.pageID);
params.set("display", obj.display_id);
let url = window.location.href.split('?')[0];
let nextURL = url + "?" + params.toString();
window.setTimeout(function () {
window.location.href = nextURL;
}, obj.duration * 1000);
console.log(obj);
</script>
So my URL is now showDisplay.php?display=undefined&pageID=undefined
How can I get this to parse the JSON correctly?
UPDATE:
If I echo $showDisplays, this is the JSON that prints:
[{"pageID":"104","page_type_id":"1","display_id":"3","slide_order":null,"duration":"56","active":"1","background_img":null,"panel_id":"96","panel_type_id":"1","page_id":"104","cont_id":"148","contID":"148","content":"\r\n\r\n\r\n<\/head>\r\n\r\nThis is full content<\/p>\r\n<\/body>\r\n<\/html>"},{"pageID":"116","page_type_id":"1","display_id":"3","slide_order":null,"duration":"54","active":"1","background_img":"images\/BG_spring.svg","panel_id":"113","panel_type_id":"1","page_id":"116","cont_id":"165","contID":"165","content":"\r\n\r\n\r\n<\/head>\r\n\r\nThis background should be green<\/p>\r\n<\/body>\r\n<\/html>"}]
So on page load i want the url to have display=3&pageID=104 then after 56 seconds (its duration) it should refresh and th URL should be display=3&pageID=116 for 54 seconds, and then keep the loop
If I read the code correctly, $showDisplays is an array of row objects, not a single row object. The JavaScript, however, tries to access properties of a row object as if they were on their containing array, obj.
If you want to access properties of the first row object in the array, you can do this with:
params.set("pageID", obj[0].pageID);
params.set("display", obj[0].display_id);
The next row object would be at the next index, obj[1]. So, in order to get all of the row objects in sequence, you would loop over them.
i have code above which gets data from a database and then place in in json form to make it readable in java script.
the results of the echo is
"FIAT":["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"],
"Land Rover":["Defender","Discovery","Discovery 3","Discovery 4"]
I would like the data to be converted in such a way the i can reference it in this form Var Brand=array ();
Brand["FIAT"]=["Anglia","Bronco","Capri","Cobra","Consul","Corsair","Cortina"];
Brand["Land Rover"]=["Defender","Discovery","Discovery 3","Discovery 4"];
in java script. Does Any one know how i can do this.
$query = mysqli_query($conn,"SELECT * FROM car_models");
// Loop the DB result
while(($result = mysqli_fetch_array($query))) {
// Check if this ID is already in the data array
if(!array_key_exists($result['Brand'], $data)){
// Create array for current user
$data[$result['Brand']] = array();
}
// Add the current race time to the array (do not need to use the float)
$data[$result['Brand']][] = $result['Model'];
}
//json data
json_encode($data);
I found the solution. Simply added the json object in a variable and now am able to get the echo it to the console
`
//json data
var brandAvailable =
console.log(brandAvailable);
"`
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.
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);
}
I need to store values into a Wordpress database and the use the value in a Google Chart.
The questions are:
1. What format do I use to store it into the database?
Currently I am using WP-TYPES and adding the array as follows to a Multi Line Box:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
This is what it needs to output in the Javascript for the chart.
Convert the String to a array in PHP (Not doing it correctly)
I retrieve the data with:
$graphdata = types_render_field("graph-data", array("output" => "raw","separator"=>";"));
This gives me a string value.
Then I add it to an array:
$thechartcontent[$i] = [
"name" => get_the_title(),
"chartheaders" => array($graphdata),
];
In JavaScipt:
I set the PHP Array to Java
var chart1 = <?php echo json_encode($thechartcontent[0]); ?>;
Then I get the data from the array to a var:
var chartheaders1 = chart1['chartheaders'];
This is where I get stuck. The value that I get is a string. It needs to show exactly this:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
for it to work.
Any help please.
Well, it will not be exacly like you want since it's JSON encoded in JSON format. This might be useful. Or you can convert object into array in JS.
I suspect that what you are outputting is an array containing a string, which is not what you want. You must split $graphdata into an array of arrays containing your data before adding it to $thechartcontent:
$graphdata = substr($graphdata, 1, strlen($graphdata) - 1); // trim the opening and closing brackets
$graphdata = explode('],[', $graphdata); // split $graphdata into an array of strings
foreach($graphdata as &$row) {
$row = explode(',', $row); // split the row into an array
}
$thechartcontent[$i] = array(
'name' => get_the_title(),
'chartheaders' => $graphdata
);
When you json encode the data, you should use the JSON_NUMERIC_CHECK constant, so your numbers don't get quoted as strings:
var chart1 = <?php echo json_encode($thechartcontent[0], JSON_NUMERIC_CHECK); ?>;