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

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?

Related

I'm passing a JSON in form data from javascript. And accessing that JSON in php. It replaces "" to &quot

Im sending a array after converting it into JSON using
var json_arr = JSON.stringify(info);
and JSON is,
{"1":"111112221111","2":"1111122211","3":"11111222"}
I'm sending this JSON as value of a text box (In form field using post method).
And I'm printing it in a php file as
$this->log->write($data['infoArray']);
It prints as
{"1":"111112221111","2":"1111122211","3":"11111222"}
I tried
json_decode($data['infoArray'],true);
but it prints nothing (blank)
so when I'm trying to iterate through it as,
foreach ( $data['infoArray'] as $key => $value) {
$this->log->write("key :".$key);
$this->log->write("value :".$value);
}
it throws warning
PHP Warning: Invalid argument supplied for foreach()
So my questions are,
why "" are getting replaced by &quot.
how can I iterate through JSON so I can access key and value in it.
I don't know what does your log() method exactly do so I can't really tell you why.
Use html_entity_decode() before json_decode()-ing the value of $data['infoArray']
Try this:
$decoded = json_decode( html_entity_decode( $data['infoArray'] ) );
foreach ( $decoded as $key => $value) {
$this->log->write("key :".$key);
$this->log->write("value :".$value);
}
1.why "" are getting replaced by &quot.
Actually it's " and it's html format for displaying quotation mark. I think JSON wants to keep quots from being mixed with other key values in you JSON array so it replaced them by "
2.how can I iterate through JSON so I can access key and value in it.
Try json_decode()
So for the warning try to decode html special charaters first, then use JSON decode then use it in foreach:
$json_decoded = htmlspecialchars_decode(json_decode($data['infoArray']))
foreach ( $json_decoded as $key => $value) { ...
infoArray is a json string not an php array (you will have to use json_decode php function first to convert the posted json string to php array).
The " is added by the log function (i guess it is printed in some html), so double quotes are escaped by default (by the function) to "
Since JSON is posted as value of textbox the escaping is probably done there and the " are replaced there before postinbg to php. Use html_entity_decode before using json_decode. Although passing json data as part of textfields seems awkward in the first place

Properly format JSON array in 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

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.

Javascript array to php with post

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

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