unable to unpack php array with $.post() - php

I have an array stored in php: $cv1 = array('a','b');
As you can see in the code below, I am trying to get the respective data from the array then delegate it to two separate functions.
But the data returned from the php callback function is: 'Array' instead of 'a','b';
and result[0] gets 'A' result[1] gets 'r' etc.
Thanks for help!
js:
$('a').on('click',function(){
var cv = $(this).data('cv');
var url= '_php/myphp.php';
$.post(url,{contentVar:cv},function(data) {
result=data;
return result;
}).done(function() {
alert(result[0]);
$('#myDiv').html(result[1]);
});
});
php:
$cv1 = array("a","b");
$contentVar = $_POST['contentVar'];
if($contentVar == "cv1")
{
echo json_encode($cv1);
}

It's common in PHP for you to get "Array" instead of an actual array when it accidentally gets cast to a string. That's not what you're doing here though; we can test:
> $cv1 = array("a","b");
array(2) {
[0] =>
string(1) "a"
[1] =>
string(1) "b"
}
> json_encode($cv1);
string(9) "["a","b"]"
$cv1 gets encoded correctly.
You must be treating it like a string somewhere else:
> (string)array("a","b")
! Array to string conversion
string(5) "Array"
Also, why do you have two success callbacks in $.post? The 3rd argument is a success callback, which works the same as .done. Use one or the other (I recommend done) but not both.
You may also consider passing json as the last argument (dataType) so that jQuery knows what to expect and will properly decode the result.

Try to do something like this:
$.post(url,{contentVar:cv}
function(response)
{
alert(response[0]);
},'json'
);

You need to convert the json string format to a javascript object/array.
var result = $.parseJSON(data);
see this question jQuery ajax request with json response, how to? for more detail.
But there is something strange that, if is returning 'Array', the php is not converting the array to json, what happens if the ($contentVar == "cv1") return false? If you will return an array to javascript you need to convert to a string (and the json format is perfect for this).

Related

Pass JavaScript Array to PhpPresentation

I am trying to use PhpPresentation to dinamically generate PowerPoint presentations with charts in PHP, using Google Analytics as data source.
I can make both processes independently (1. generating the pptx using a manually defined array of data and 2. generate an array in JavaScript with data from Google Analytics Core Reporting API). However, I am not able to combine both processes sucessfully (pass JavaScript's array and use it in PHP instead of my manually defined array).
1. generating the pptx using a manually defined array in php
If I use the following array as data source (as defined in PhpPresentation documentation), the PowerPoint is generated without problem:
$series2Data = array('20151201' => 266.1, '20151202' => 198.5, '20151203' => 271.8);
2. generate an array with data from Google Analytics Core Reporting API
The stringified array generated with JavaScript is:
[{"date":"20151201","avgSessionDuration":266.1},{"date":"20151202","avgSessionDuration":198.5},{"date":"20151203","avgSessionDuration":271.8}]
I am passing this array to the php that generates my PowerPoint:
<form method="post" id="theform" action="Sample_05_Chart.php">
<input type="hidden" id="markers" name="markers">
<button>Submit</button>
</form>
<script>
window.onload = function() {
var form = document.getElementById('theform');
form.addEventListener('submit', function(){
var markersField = document.getElementById('markers');
var markers = data2;
markersField.value = JSON.stringify(markers);
});
}
</script>
And in the PHP file I have added:
$markers = json_decode($_POST['markers']);
$series2Data = $markers;
However, the generated PowerPoint is corrupted, as I believe the array structure isn't what PhpPresentation expects.
My array's knowledge, however, is not so good in PHP as it is in JavaScript.
How could I transform an array, whose var_dump looks like
array(3) { [0]=> object(stdClass)#4 (2) { ["date"]=> string(8) "20151201" ["avgSessionDuration"]=> float(266.1) } [1]=> object(stdClass)#9 (2) { ["date"]=> string(8) "20151202" ["avgSessionDuration"]=> float(198.5) } [2]=> object(stdClass)#10 (2) { ["date"]=> string(8) "20151203" ["avgSessionDuration"]=> float(271.8) } }
into an array as described in point 1?
First of all, json_decode takes an optional second argument. First, the json string you wish to decode and second a boolean value which tells it whether or not to decode as an array of objects (stdClass) or as an associative array.
If you want the an associative array of the data posted, just use json_decode($markers, true).
However, the format you are asking for will not be given by this. So you need to massage the data some either in javascript or php.
Here's the php code to transform it:
$series2Data = [];
$markers = json_decode($_POST['markers'], true);
foreach ($markers as $marker) {
$series2Data[$marker['date']] = $marker['avgSessionDuration'];
}
Javascript:
function formatMarkersToData(markers) {
var series2Data = {};
for (var i = 0; i < markers.length; i++) {
var marker = markers[i];
series2Data[marker.date] = marker.avgSessionDuration;
}
return series2Data;
}
markersField.value = JSON.stringify(
formatMarkersToData(markers)
);
What both of these blocks of code do is loop over your data and set the index and value according to the required format of date => avgSessionDuration in the series2data variable. The javascript uses an object to allow for manually setting the key.
The above javascript code would then allow you to just use json_decode($_POST['markers'], true); to get the proper associative array for your $series2Data. Otherwise, you'll need the PHP code to do the massaging before passing it off to PhpPresentation.
It just depends on at what point you want the data transformed - on the server, or on the client. If this is at all confusing, please let me know.

Echo/return an array in php

Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);

javascript objects to json string to php array -> POST

Hey guys i really need help with this. i pass this json object to php..
var x = {};
x.xt = {};
x.xt.id = id;
x.xt.to = foo;
somearray.push(x);
convert object to json:
$.toJSON(x);
json string:
[{"x":{"xt":"9","to":"2"}}]
them i post this:
$.post(
"temp/sop.php",
{ xa: somearray},
function(data){
console.log("response - "+ data);
});
server side:
$xtj = $_POST["xa"];
$encodedArray = array_map(utf8_encode, $xtj);
$asnk = json_decode($encodedArray);
This returns:
string(4) "null"
and this:
$asnk = json_encode($xtj);
returns:
null
the data base it is set to:
UTF8
also when i test if it is an array, comes back true..
any idea how to solve this? thanks
also server side:
$xtj = $_POST["xa"];
$asnk = json_decode($xtj);
this returns:
NULL
$.toJSON(x) does not do the conversion in-place; it returns the JSON, and you're just discarding it. You need this instead:
$.post(
"temp/sop.php",
{ xa: $.toJSON(somearray) },
// ...
});
Then, on the PHP side, you won't want array_map as it's not going to be an array until you decode the JSON:
$xtj = $_POST["xa"];
$encodedArray = utf8_encode($xtj); // I'm not sure you need this, by the way.
$asnk = json_decode($encodedArray);
try using
if(get_magic_quotes_gpc()) $xtj = stripslashes($xtj);
to lose the excessive escaping before trying to decode.
What you are doing is you are converting to json string in JS ($.toJSON()).
And then in PHP you are again trying to convert to json string (json_encode()).
And you are using array_map() on something that is not an array but a string. (Try echo $_POST["xa"]; to see the contents of it.)

Used explode to convert php string to array, need help manipulating this in javascript

I am sending an array in php (converted from a string using explode), to a seperate javascript page. I was wondering how do I get into the javascript array and actually retrieve data values.
array in javascript (from php file)-
array(2) {
[0]=>
string(2) "30"
[1]=>
string(0) ""
}
array(2) {
[0]=>
string(2) "30"
[1]=>
string(0) ""
}
Here is the ajax call on the javascript page -
$.ajax({
url: "GetTest.php",
type: "POST",
success: function(data){
alert("success");
console.log(data);
},
error: function(data){
alert('failure');
}
});
on the php page -
var_dump((explode(',', $something));
How do I get in here and pull out the "30" value. I am using an ajax call to get this data, and then putting placing this array in a variable called "data", but if I do something like data[0], I get the letter "a" as a response.
Any help towards this will be greatly appreciated.
Thanks,
If you are returning the array itself, it will not be converted to a JavaScript object. I believe you will just get the string "Array". What you need to do is call json_encode($your_array) to convert the array to a JavaScript object. Then, PHP will return a JavaScript object that looks like this:
{
"0": "30",
"1": ""
}
You can then call JSON.parse on the response and access the data in that object as you would any other JavaScript object.
Note: If you are using PHP < 5.2 and do not have the JSON PECL extension installed, the json_encode() function will not be available, and you will need to either write a function to convert an array to JSON or find one that someone else has written.
A JavaScript array should look like this...
var myArray = ["30", "0"];
You probably have a string instead of an array if you get an 'a' at index 0.
"array"[0] === "a"
So you need to fix your client side array first.
In pure javascript:
xhr.onreadystatechange = function()//where xhr is your request object
{
if (this.readyState === 4 && this.status === 200)
{
var yourArray = JSON.parse(this.responseText);
console.log(yourArray);//logs the array above, normally
}
};
Be aware that IE, prior to 9 at least, does not come with JSON support as standard, in which case, just google JSON.js and include it in the header. Also make sure that the array you send is json_encode'ed before you echo it.
Looking at the code you added, I'd say: replace the var_dump by echo json_encode(explode(',',$someString)); and you're all set

What is the best way to send PHP array via jquery?

can anybody help to explain or give reference on how to send array of multiple array (or just array ) in jquery. and what the best way to do when something is failed or successfull. what i mean is how the php code send back the success or failed message
See this article for an example. Basically, you have to use PHP's json_encode() to convert a PHP array to JSON code. In the linked example, the jquery-json plugin is used to convert JSON back to a Javascript array.
Alternatively, you can use jQuery's built-in capabilities for retrieving a PHP response as a Javascript array/object.
Use JSON ENCODE
Something like this:
index.php
<script type="text/javascript" src="jsfile.js"></script>
<a href='numbers.php' class='ajax'>Click</a>
numbers.php
<?php
$arr = array ( "one" => "1", "two" => "2", "three" => "3" ); // your array
echo json_encode( $arr ); // encode it to json
?>
jsfile.js
jQuery(document).ready(function(){
jQuery('.ajax').live('click', function(event) {
event.preventDefault();
jQuery.getJSON(this.href, function(snippets) {
alert(snippets); // your array in jquery
});
});
});
If it is a simple error message and always the same one, you can simply return that string e.g. "error" and test for that value in JavaScript. But I would recommend to send the complec data in XML or even better in JSON (because it is smaller and can be used without poarsing it in JavaScript). Just do this in your PHP:
if($error){
echo "error";
} else {
json_encode($complex_data);
}
If you want to put some information into your error, which I highly recommend, just return an error array encoded with JSON. So replace the echo "error" with this:
echo json_encode(array("error" => "your error message", "status" => "an optional error status you can compare in JavaScript"))
Than you just have to check if the "error" is found in the JSON returned from PHP.

Categories