I have the following in my js script :
cats = []; cats.push(cat1); cats.push(cat2);
$.post( URL+"/edit-article.php", { id: artId, title: "PZujF0 wxKLCW", content: "ILEn3o oU9Ft6oU5", author: author, cat_id: cats } ).done(function( data2 ) {......}
cat1 and cat2 are some random generated integers, so i send to my php script an array of integers. How do i retrieve them inside my php script ? Currently i have something like this:
$cat_id=array();
$cat_id=array_map('intval',explode(',',$_POST['cat_id']));
but my code assumes that the sent array from js is the equivalent of the following :
<form action='edit-article.php' method='post'>
<input type='hidden' name='cat_id' value='1,2'>
</form>
From the code i posted in js it's obvious that there are only 2 integers so i could probably make something like :
$cat_id=$_POST['cat_id'];
$id1=(int)$cat_id[0];
$id2=(int)$cat_id[1];
But how can i correctly parse the array in PHP for any number of elements and make sure i am left with an array of ints ?
LE: The problem i have is understanding how JS sends the data to my php script, in order to correctly extract the data. As i gather, $POST values are always retrieved as strings(is it valid for values sent from JS or just forms and stuff?), but is my cat_id array an array of strings like {'1','2','3'} or is it a string like '1,2,3' ?
Currently you're sending an array, so there's no need to explode:
$cat_id = array_map('intval', $_POST['cat_id']);
Alternatively, you can create the comma separated list on the JavaScript side:
cats = cats.join();
Related
I have two PHP strings that looks like this (obviously shortened for the question):
$year [
[0]=>2003
[1]=>2003
[2]=>2004
[3]=>2004
[4]=>2005
[5]=>2005
]
$cost [
[0]=>200
[1]=>300
[2]=>400
[3]=>500
[4]=>410
[5]=>510
]
I need to turn the PHP arrays above into a JAVASCRIPT array formatted exactly as below:
var newData=[
['2003', 200,300],
['2004', 400,500],
['2005', 410,510]
];
When I type in the JS array implicitly (as above) all works fine (ie the graphics render correctly). However after several hours of trying different approaches, I cannot work out how to easily generate the newData array dynamically (ie from PHP arrays as shown) in exactly the JS Array format shown.
Your quest can be separated in two tasks:
First of all you want to combine both arrays. I guess you want to do this based on the keys they have. There are multiple functions for that in PHP, like array_combine or array_reduce.
Yet for your case the easiest way is a for_each loop, because you have duplicate values in the $year array.
$combined_array = [];
foreach ($year as $id => $year_val) {
if (!array_key_exists($year_val, $combined_array)) {
$combined_array[$year_val] = [(string)$year_val];
}
$combined_array[$year_val][] = $cost[$id];
}
Now you have the years as keys, what you do not want, so you can use array_values to remove the keys again.
$combined_array = array_values($combined_array);
The second task is quite easy: Go to the PHP file, that loads the script you want to provide the array to. Add this before you load the script:
<script>
var myPhpArray = <?php echo json_encode($combined_array) ?>;
</script>
After that the PHP array is accessible from JS in the variable `myPhpArray.
if you respect the structure in the example, the following would do the job:
<?php
$year = [
0 => 2003,
1 => 2003,
...
];
$cost = [
0 => 200,
1 => 300,
...
];
for($i=0;$i<SIZE_OF_ARRAY;$i+=2)
$newData[] = [(string) $year[$i], $cost[$i], $cost[$i+1]];
?>
Now in the javascript portion of the code you just need:
<script>
var newData = <?= json_encode($newData); ?>
</script>
Note that i didnt use the quotes between the php code because i do want the javascript to parse the php output as javascript code and not as a javascript string.
Thanks for all the help. Your answers showed I was going about things the right way (json_encode etc). What has happened though is that the legacy system producing the PHP Arrays was not correcting the values for integers rather than strings. The recipient plug in needed INTs -- see the output array format in the question
So json_encoding the php array worked OK - but it was encoding string rather than INT data values. Fixed that and now it all seems fine.
PS If you look at the orginal question yyou will see the OP array in JS needed two datatypes. And of course it was only getting strings. Lesson there for sure!
Heres the snippet
var a = ['1','2','3'];
var result = a.map(function (x) {
return parseInt(x, 10);
I have a json response from an API and I can't create an array from it with "json_decode" in PHP to iterate through this as an array. I always get "NULL", when I use "var_dump" to print out, what my "json_decode" returns. The response-header of this API response is "application/json", but I am not familiar with this json format.
The json response from the API looks like this:
[1,"Example name","307","7","Test","455",1458572100000]
[1,"Another example name","146","7","Test","455",1458571500000]
[1,"Test","304","7","Test","455",1458572280000]
[1,"Example name 3","163","7","Hello world","455",1458571080000]
This is the result/response of a single API request. Now, for example, I want to get the penultimate number (in this case everytime 455) of every line/object or, for example, the name (second value: "Example name", "Another example name", "Test" and so on). How can I do this with php and this json format? It would be nice, if I can get an array from this to iterate through.
It's a local realtime bus arrival API, but it's similar to/the same as content.tfl.gov.uk/…and I call this API with a simple http/get request using file_get_contents in PHP
"/interfaces/ura/instant_V1?returnList=stopID,stopPointName,LineID,DestinationText,estimatedTime,vehicleID&vehicleID=455")
To clarify, that's not JSON format that you're getting back. But if that's what you're getting then you need a solution :)
I would ignore the first & last character and use str_getcsv() to return the comma separated string as an array:
$input = '[1,"Example name","307","7","Test","455",1458572100000]';
$array = str_getcsv(substr($input, 1, -1));
If you are having multple lines, then you'll want to split them into individual lines before doing the above with:
$lines = explode($input, "]");
$array = array();
foreach($lines AS $line) {
$input = '[1,"Example name","307","7","Test","455",1458572100000]';
$array[] = str_getcsv(substr($input, 1, -1));
}
Updated to show delimeter of ] instead of \n as per comment below.
I have a dynamically created jQuery array that I am trying to post to the same page and turn into a php array. This is an example of what my array looks like:
var final_game = [];
[final_game { final_user_id="1", final_game_id="1", final_game_type="fun", final_price="1", final_score="1.8"},final_game { final_user_id="1", final_game_id="2", final_game_type="fun", final_price="1", final_score="2.8"}]
I am using this code to post it to the same page on click of a button:
$.post("http://www.samepage.com",{final_game: JSON.stringify(final_game)});
I then use this code to print the results to the page:
$data = $_POST['final_game'];
print_r ( $data);
This outputs this string to the page:
[
{\"final_user_id\":\"1\",\"final_game_id\":\"1\",\"final_game_type\":\"fun\",\"final_price\":\"1\",\"final_score\":\"1.8\"},
{\"final_user_id\":\"2\",\"final_game_id\":\"2\",\"final_game_type\":\"fun\",\"final_price\":\"1\",\"final_score\":\"2.8\"}
]
Now I tried to use json_decode, but I wasnt seeing anything displayed to the page. I think it may be because of the mixed content ( string, int, decimal )? How can I transform this string into a usable php array?
I'm writing a simple delete function. This function deletes entries in a list that is being outputted by PHP. This is what happens:
The javascript selects the checked boxes in this list and gets its ID 1,2,3etc.
The created array is converted to JSON using JSON.stringify
PHP gets the POST and decodes it using json_decode() (this fails)
$(document).ready(function(){
$('.action_trash').on('click', function(){
//Select items to trash
var TrashItems = [];
$('input:checked').each(function() {
TrashItems.push($(this).attr("id"));
});
//Convert to JSON
var TrashJSON = JSON.stringify(TrashItems);
alert (TrashJSON);
$.ajax({
type: "POST",
url: "pages/forms_intake/actions/trash/model_trash.php",
data: {TrashItems:TrashItems},
cache: false,
success: function(){
// do stuff to remove trashed elements from list.
}
});
});
});
I'm trying to convert the simple Javascript array to JSON. But I think the JSON is invalid. When I alert the TrashJSON variable, this is the output: ["31","32"]
<?php
session_start();
include "../../../../php/config.php";
$TrashJSON = $_POST['TrashItems'];
var_dump(json_decode($TrashJSON));
//Trash items
//$TrashQuery = mysqli_query ($mysqli, "UPDATE forms_intake SET item_trashed=1 WHERE formid='$TrashInt'");
//Close connection
mysqli_close($mysqli);
?>
When I run this, I'm getting this error:
<br />
<b>Warning</b>: json_decode() expects parameter 1 to be string, array given in <b>/home/nickvmf103/domains/a-training.nl/public_html/sotwebapp/pages/forms_intake/actions/trash/model_trash.php</b> on line <b>7</b><br />
NULL
According to the PHP manual on json_decode, null gets outputted if the JSON is invalid.
So my question is: How to correctly format the JSON in my javascript? So that it can be passed to PHP and converted to a PHP array.
Additional info:
When successfully converted to PHP array, I will use implode to put " OR " between the array values, convert it to a string and use it in my SQL query WHERE statement to trash the items that were checked on my page.
In order for the existing PHP to function how you expect, you need to send TrashJSON instead of TrashItems. TrashItems is the array you've populated, while TrashJson is the JSON encoded version of TrashItems.
Change
data: {TrashItems:TrashItems},
to..
data: {TrashItems:TrashJSON},
jQuery is correctly interpreting TrashItems as an array, and thus sending it as an array of values to the PHP script.
Alternatively, as Barmar has inferred in the comments, you could simply loop over the values array currently posted as TrashItems. You could do this using the following code.
foreach ($_POST['TrashItems'] as $TrashItem) {
echo "$TrashItem\n";
}
This would output each item of the TrashItems array you originally passed in on a separate line, and provide the output of..
31
32
I've never seen this problem before, and I can't find the issue anywhere online. I'm using Angular to post form data to a PHP page. I'm using the file_get_contents() method of retrieving the POST data, which is a simple JSON object.
The problem arises with the data attributes - when I assign php vars to the data, they always have the value "{" or "[" (I echo'd and logged them). Any idea what could be causing this problem?
The relevant form declaration:
<form name="itemForm" ng-if="true" id="newItemForm" class="add-item" ng-submit="addItem(itemForm)">
<input type="text" class="form-control data-entry" ng-model="itemForm.itemType" placeholder="Type" ng-focus="true">
Here's my Angular function:
$scope.addItem = function(itemForm) {
$http.post("../ajax/addItem.php", itemForm).success(function(data) {
//console.data(JSON.stringify(itemForm));
console.log(data);
currItem = itemForm;
itemsArr.push(angular.copy(itemForm));
$scope.itemForm = defaultForm;
getItem();
});
};
partial PHP:
<?php
$params = file_get_contents('php://input');
if($params){
$item = $params["item"];
$type = $item["itemType"];
//get other parameters, insert into MySQL database
echo json_encode(["type = " => $type]);
}
?>
You're using string-based keys for your array. In Javascript terms, that has to be represented as an Object, which uses {} as the delimiters. Proper arrays, which use [], only accept numerical keys.
And note that type = as an array key is somewhat redundant. Why not just type?
The file_get_contents function returns a string, so the $params variable is a string not an array. However, strings in php can be accessed in an array like fashion (except the key must be a number). In your code $item = $params["item"] should will give you a php warning and php will automatically assume an index of 0 since the key you gave was not a number. This is why you were getting { or [ when you echoed the data from php (because valid json is enclosed by {} or []).
To use $params as an array like you are trying to do you first need to do $params = json_decode($params). This will only work assuming you have a valid json string in the file you are reading from.