JSON stringify and decode JS/PHP - javascript

I have a problem with sending an object in PHP. I stringify the object before sending it to the PHP file.
The PHP file then uses json_decode. But the decode shows a blank variable.
The object which i console.log shows this as its structure:
Its then sent to PHP with this :
console.log(my_Obj);
var as = JSON.stringify(my_Obj);
call_data('add.php?&as='+as, nxtFunc);
Now in the PHP file i have this which handles the situation:
$path = json_decode($_GET['as']);
echo $_GET['as'].'<br/>';
print_r($path);
die;
The result is:
[null,null,{\"8\":[null,null,null,null,null,null,[],[],[],[],[]],\"9\":
[null,null,null,null,null,null,null,null,null,null,[]],\"10\":
[null,null,null,null,null,null,null,null,null,null,[],[]],\"11\":
[null,null,null,null,null,null,null,null,null,null,null,[]]}]
<br/>
My XHR request url in Chrome shows:
add.php?as=[null,null,{%228%22:[null,null,null,null,null,null,[],[],[],[],[]],%229%22:[null,null,null,null,null,null,null,null,null,null,[]],%2210%22:[null,null,null,null,null,null,null,null,null,null,[],[]],%2211%22:[null,null,null,null,null,null,null,null,null,null,null,[]]}]
Notice the print_r shows nothing. Should i not be using stringify ?

Thats because my_Obj is an array and not an object.
Try this:
var as = JSON.stringify({data: my_Obj});
Note:
You will also need to clean up the array before stringifying - i.e. clear out all null/undefined indices. Check this answer: https://stackoverflow.com/a/281335/921204

Related

Communicate php and js

I'm trying to create a js that send data to a php.
My first problem is that I get get back a html code if I insert this to the php.
This is only for understand the idea. So the js should send the "param" to the php and the php should return the result6 variable in this case, but I get a html code...
$('#f_field').change (function()
{
var param = 28;
$.post('check_mutet.php', param, function(result6) {
alert(result6);
});
});
while check_mutet.php contains this
<?php
$result6=666;
echo $result6;
Thank you for your help, as you can see I'm rather noob :)
param is a plain string (it starts out as a number, but will be converted to a string by the time it gets through to HTTP).
This will be available as STDIN in PHP, which you can read as described in answers to this question.
However, you should encode the data into a structured format that is easier to use.
The traditional format for this is application/x-www-form-urlencoded, which is the default format sent by HTML forms.
If you pass an object to jQuery post, it will encode the data in that format for you:
var param = 28;
var data = { example: param };
$.post('check_mutet.php', data, function(result6) {
Then you can read it through the POST superglobal in PHP:
<?php
$result = $_POST['example'];

file_put_content array structure does not work

I'm trying to move an array into a .json file and then simply console.log it. I think its my structure in my array that is messing it up.
$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth], 'RevenueGrowth' =>[$revenuegrowth],);
file_put_contents('Stockdata1.json', json_encode($jsonarray), FILE_APPEND);
This is how it looks like in the .json file.
{"Symbol":["A"],"PERatio":["31.55"],"MarketCap":["19722.500"],"Dividend":["0.87"],"ROE":["14.48"],"DebtToEbitda":["2.04"],"EbitdaGrowth":["5.40"],"RevenueGrowth":["4.20"]}{"Symbol":["AA"],"PERatio":["44.45"],"MarketCap":["6960.660"],"Dividend":["0.00"],"ROE":["2.33"],"DebtToEbitda":["0.95"],"EbitdaGrowth":["0.00"],"RevenueGrowth":["0.00"]}{"Symbol":["AAC"],"PERatio":["0.00"],"MarketCap":["217.730"],"Dividend":["0.00"],"ROE":["-2.76"],"DebtToEbitda":["8.71"],"EbitdaGrowth":["22.30"],"RevenueGrowth":["15.00"]}{"Symbol":["AAP"],"PERatio":["18.68"],"MarketCap":["6888.440"],"Dividend":["0.26"],"ROE":["12.69"],"DebtToEbitda":["1.17"],"EbitdaGrowth":["6.50"],"RevenueGrowth":["13.60"]}
when i then try to console.log in js like this
$.getJSON('Stockdata1.json', function (data) {
console.log(data);
});
nothing comes out... Hope someone can see my mistake..
As soon as you FILE_APPEND the second array, you're invalidating the JSON in the file. The file will contain two JSON objects without a separator (i.e. (abbreviated for clarity) {"Symbol":["A"]}{"Symbol":["B"]}).
Instead, what you need for valid JSON, is to have the file contain a JSON array of all objects: [{"Symbol":["A"]},{"Symbol":["B"]}]. The only way to do that, is to not use file_put_contents() with the FILE_APPEND flag, but to load the file as JSON, add the new object, and write the full JSON back to the file.
My suggestion is to change your code to something along these lines:
$jsonarray = array('Symbol'=>[$symbol],'PERatio'=>[$peratio], 'MarketCap'=>[$marketcap], 'Dividend'=>[$dividend], 'ROE'=>[$roe], 'DebtToEbitda'=>[$debttoebitda], 'EbitdaGrowth' =>[$ebitdagrowth], 'RevenueGrowth' =>[$revenuegrowth],);
$data = json_decode(file_get_contents('Stockdata1.json'));
if (!$data) {
// file is empty or does not contain valid JSON
$data = [];
} elseif (is_object($data)) {
// file only contains a JSON object, not a JSON array
$data = [ $data ];
}
$data[] = $jsonarray;
file_put_contents('Stockdata1.json', json_encode($data));

$.post Jquery send array

I have problem with send array in $.post to php.
var_dump result is "NULL"
JSON.stringify doesn't work..
JQUERY
var photobox = [];
photobox.push(e.target.result);
$.post("../modules/upload.php",{"images[]" : photobox, count : sum},
function(data)
{
$('.list').prepend(data);
}).done(function() {
$('#files').prop('disabled', false);
$('.file-search').html("Szukaj...");
$(".img-thumbnail").removeClass("first");
$(".img-thumbnail").first().addClass("first");
e.target.result is base64 code
PHP
$images = $_POST['images'];
var_dump($images);
You can send arrays like this:
$.post('/thepage.php', {'NameOfKey': variableName});
The above code will allow VariableName to be an Array.
You would need to encode to JSON on your client, but when on your server (PHP) convert it back to an array by using json_decode:
http://php.net/manual/en/function.json-decode.php

post request in javascript with multilevel object

I am going CRAZY posting a json request to a php webservice file when the object I am trying to send is multi-level. ie:
postdata = {
name:"francesco"
, age:58
, address : {
street:"my Street"
, number: 42
, city:"London"
}
}
I have tried every example on the web, but, when I read the $_POST data on the php webservice two things happen:
if I use JSON.stringify I dont get anything on $_POST or $_GET depending what method I use, and I have to read the file_get_contents('php://input') and then json_decode it (whereas calling the webservce from php I get the info tidily in my $_GET or $_POST globals),
If I use other methods I have found, I get the name and age fine, but the address comes through as "[object object]" .
My question is, is it possible, WITHOUT USING jquery, to :
- create an object in javascript (multilevel or however the right term)
- use the "XMLHttpRequest()" object to post it to the php ws?
- read it from php using the $_GET or $_POST globals (depending on method used)?
I have been going crazy for over 96 hours now!!!
Thanks!
Francesco
So many incorrect answers here.
To POST a nested object to your PHP script you can use plain js:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://yourwebsite.com/yourscript.php");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send({"data":postData});
To read the info server-side
$postData = $_POST['data'];
When I looked to see what PHP had actually given me with error_log(print_r($_POST['test'], true)) I got
Array
(
[name] => francesco
[age] => 58
[address] => Array
(
[street] => my Street
[number] => 42
[city] => London
)
)
It's all there.
Question #1
is it possible to create an object in javascript (multilevel or however the right term)
This is how you create an object in javascript:
var o = {
foo: "bar"
};
Question #2
is it possible to use the "XMLHttpRequest()" object to post it to the php ws?
It's not hard to find it on the web: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The code would be something like:
var oReq = new XMLHttpRequest();
oReq.open("POST", "http://www.example.org/target");
oReq.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
oReq.send(JSON.stringify(postdata));
Question #3
is it possible to read it from php using the $_GET or $_POST globals (depending on method used)?
No, you can't. As the docs say, $_POST is:
An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.
So the $_POST is usable only if you're passing form encoded data. Since you're passing a JSON, you're supposed to parse the request body by yourself.
From what I understand, it is not possible to post data to php from jscipt unless it's a form. but I can do this:
if ($_POST != null)
$req = $_POST;
else {
$json = file_get_contents('php://input');
$req = json_decode($json, true);
}
.. and then just read the $req ..
Is this VERY dirty or commonplace??

"invalid label" Firebug error with jQuery getJSON

I'm making a jQuery $.getJSON request to another domain, so am making sure that my GET URI ends with "callback=?" (i.e. using JSONP).
The NET panel of Firebug shows that I am receiving the data as expected, but for some reason the Console panel logs the following error: "invalid label".
The JSON validates with JSONLint, so I doubt that there is anything truly wrong with the structure of the data.
Any ideas why I might be receiving this error?
This is an old post, but I'm posting a response anyway:
Let's assume you want to get the jSON code generated by the following file, "get_json_code.php":
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
Like you mentioned, $.getJSON() uses JSONP when you add a "jsoncallback=?" parameter to the required URL's string. For example:
$.getJSON("http://mysite.com/get_json_code.php?jsoncallback=?", function(data){
alert(data);
});
However, in this case, you will get an "invalid label" message in Firebug because the "get_json_code.php" file doesn't provide a valid reference variable to hold the returned jSON string. To solve this, you need add the following code to the "get_json_code.php" file:
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo $_GET['jsoncallback'].'('.json_encode($arr).')'; //assign resulting code to $_GET['jsoncallback].
?>
This way, the resulting JSON code will be added to the 'jsoncallback' GET variable.
In conclusion, the "jsoncallback=?" parameter in the $.getJSON() URL does two things: 1) it sets the function to use JSONP instead of JSON and 2) specifies the variable that will hold the JSON code retrieved from the "get_json_code.php" file. You only need to make sure they have the SAME NAME.
Hope that helps,
Vq.
It looks like you're misusing JSONP in your server script.
When you receive a request with a callback parameter, you should render the following:
callbackName({ "myName": "myValue"});
Where callbackName is the value of the callback parameter.

Categories