Properly format JSON array in Javascript - javascript

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

Related

PHP not decoding a JSON object created with Javascript. Error ALWAYS returns 4

I'm trying to create a mapping of key and value pairs in javascript. I create an object and paste it into a hidden textarea, so i can collect it with PHP and decode the object and eventually save it to a database. The data comes in a JSON format, but i'm unable to decode it as a JSON Object in PHP. json_last_error() always returns a 4 and i have no idea why.
Here i fill my onject in Javascript:
finalMapping = databaseMappingList.reduce(function(finalMapping, field, index) {
finalMapping [fileMappingList[index]] = field;
return finalMapping;
}, {})
which works fine. Then i paste it into a txtarea:
$('#txtarea').val(JSON.stringify(finalMapping ));
i get the following output, when i echo $_POST["txtarea"]:
{"a":"a","b":"b","c":"c"}
which i assume is a valid JSON string. hen i use json_decode($_POST["txtarea"]), i get NULL and when i echo json_last_error(), i get 4. hat am i doing wrong?
Try var_dump($_POST['txtarea']); instead of echo for debugging.

Issue with encoded array from php

I'm having an issue returning a value from PHP to Javascript. I have encoded the PHP array like so :
echo json_encode($myArray);
And on the Javascript side i do this within the $.ajax method:
success:function (data) {
alert(data);
}
This works and it alerts the returned array, however when i try to then set my Javascript array to the value of data :
success:function (data) {
myArray = data;
}
This completely breaks my looping operation and so instead of printing out for example:
This is a test
It will print:
t,h,i,s,i,s,a,t,e,s,t
and the length of the array rather than being 4, for 4 words it is 16+ including the square brackets etc. How can i reuse the json encoded array once it has been recieved by javascript and maintain its structure?
Related: Parse JSON in JavaScript?
What you are looking for:
myArray = JSON.parse(data);

php, array of jquery objects into php array, $.post , JSON.stringify

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?

PHP shows "{" or "[" for JSON Object Attributes sent via Angular $http

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.

jQuery/javascript: use PHP return value as javaScript array

is there anyway to import a javaScript array from a PHP return value?
Say that a PHP script, 'makeArray.php', would return '"first","second","third"' (without single quotes). The purpose of the below would thus be to alert 'second'.
$.get(makeArray.php, function(data){
var responseArray = new Array(data);
alert(responseArray[1]);
...
However all I get is 'undefined'. If I was to change the array index to [0], I would get '"first","second","third"'.
Thanks!
You can use JSON.
In PHP
$myarray = array('first','second','third');
return json_encode($myarray);
In JavaScript:
$.get(makeArray.php, function(data){
console.log(data[1]); //=> "second"
}, 'json');
Edit
If you don't have PHP 5.2 then you can try echoing a string and parsing it in JavaScript:
PHP:
echo join('%',$myarray);
JS:
var array = data.split('%');
Because, what you are doing is that you are including all the data recieved form the file (makeArray.php) into the first element of an array. So, obviously it would be in the zero-index of the array.
What you should do in this case is use Array.split() function on the array like - data.split(",") to create an array from the data recieved.

Categories

Resources