I am using jqplot and have constructed an array with the following PHP code
if($fiveRes){
$lastNum = mysql_num_rows($fiveRes);
$testarray = array();
while($row = mysql_fetch_array($fiveRes, MYSQL_ASSOC)) {
$testarray[] = array($row['GameDate'], floatval($row['WKP']));
}
echo json_encode($testarray);
}
This code outputs the correct code that I need to insert into the jqplot function. Here is the array generated by the code above:
[["2011-12-24",0],["2011-12-19",14],["2011-12-08",22],["2011-12-04",14],["2011-11-27",12]]
So currently i'm printing this array to the screen, and then using jQuery .text() to capture the string and place it inside a variable. I can echo out the var that I assigned the array string to and it works correctly, however when I pass it into the jqplot function it does nothing.
var p1array = $('.col.first .parray').text();
alert(p1array); //Alerts the correct array formatted like above.
var plot1 = $.jqplot('jqplot0', [p1array], {
title:'Last 5 Fantasy Points',
axes:{
xaxis:{
renderer:$.jqplot.DateAxisRenderer,
tickOptions:{
formatString:'%b %#d'
}
},
yaxis:{
tickOptions:{
formatString:''
}
}
},
highlighter: {
show: true,
sizeAdjust: 7.5
},
cursor: {
show: false
}
});
To make it even more complicated, if I copy the string that the PHP generates and I hardcode it into a variable in JS it works. Any ideas why the jqplot plugin won't evaluate the string I get from using $(this).text();.
Here is the jQplot example i'm modeling after: http://www.jqplot.com/tests/cursor-highlighter.php
Using this method helped me solve this problem. Instead of using jQuery to access the printed variable I inserted a little bit of javascript at the bottom of my PHP page to capture the local variable in PHP and then used that to pass into the jQplot function.
Pass a PHP string to a JavaScript variable (and escape newlines)
Use [p1array] directly with out braces and try... it should work just like p1array
Related
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);
I'm making a jQuery .post() with the following arrays:
'cleanedLinkStructureArray[]': cleanedLinkStructureArray,
'cleanedPermaLinkArray[]': cleanedPermaLinkArray
The data inside these arrays:
cleanedPermaLinkArray looks like this: ["2012","10","30","hello-world"]
and cleanedLinkStructureArray like this: ["year","monthnum","day","postname"]
Javascript code:
var ajaxPost = $.post(
enableAJAX.ajaxurl,
{ action: 'ajaxRequest',
'ajaxRequestNonce' : enableAJAX.ajaxRequestNonce,
'cleanedLinkStructureArray[]': cleanedLinkStructureArray,
'cleanedPermaLinkArray[]': cleanedPermaLinkArray },
'json'
);
ajaxPost.done(function(responseText) {
alert(responseText);
console.log(responseText);
});
ajaxPost.fail(function() {
alert("Oops, I'm afraid we've broken something");
});
I don't understand how I catch the two arrays in PHP? and use the data from the arrays inside PHP? Preferably I would create new PHP array with them, where the values inside cleanedLinkStructureArray become the keys for the array and the values inside cleanedPermaLinkArray the values for that new array.
I guess it must be something with this, but I need someone more experienced to tell me what I need to do here.
$_POST['cleanedPermaLinkArray[]']
$_POST['cleanedLinkStructureArray[]'];
Any help would be appreciated.
Kind regards,
Marnix
Your arrays will be in
$_POST['cleanedPermaLinkArray']
$_POST['cleanedLinkStructureArray'];
you can do a simple var_dump($_POST) to see how the data is formed
First, in $.post, you do not need the square brackets, so this is one of your params:
'cleanedLinkStructureArray': cleanedLinkStructureArray,
Then in PHP, you have to first catch it like such:
$cleanedLinkStructureArray = $_POST["cleanedLinkStructureArray"];
Now, you can use the following:
foreach ($cleanedLinkStructureArray as $item) {
// Do something with $item
}
Another way is to pass all your params from $.post to php is setting them as json object.
This is all coming down from the server as JSON, right? Just use json_decode on the values and the'll be converted to arrays, natively inside of php.
$cleanedPermaLinkArray = json_decode($_POST['cleanedPermaLinkArray[]']);
echo cleanedPermaLinkArray[0]; // some value..
I cannot convert JS object to exact string, my code:
jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
jsonObjStr = JSON.stringify(jsonObj);
alert(jsonObjStr);
$.post("test", jsonObjStr.toString(), function(output){
alert(output);
});
first alert displays:
{"payment_date":"2012-06-15","payment_value":100.1}
and in function test (i'm using codeigniter framework) it should print "payment_date" and "payment_value", code like this:
echo $this->input->post("payment_value");
echo $this->input->post("payment_date");
which is equvalent in "clear" php to:
echo $_POST["payment_value"];
echo $_POST["payment_date"];
but second alert displays clear string.
If I put
{"payment_date":"2012-06-15","payment_value":100.1}
instead of jsonObjStr.toString() it works fine
Does anyone knows how to fix it WITHOUT using json_decode? I need to have posted values in this format, not in other array
So i need to convert jsonObjStr exact to string (something inversely to function eval())
Thank in advice
According to $.post docs, second argument should be map or query string:
map example:
{
"payment_date":"2012-06-15",
"payment_value":100.1
}
query string example:
'payment_date=2012-06-15&payment_value=100.1'
When you use JSON.stringify, then you get:
'{"payment_date":"2012-06-15","payment_value":100.1}'
which is invalid query string. So the solution is: do not stringify anything, pass the object itself as 2nd argument:
jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
$.post("test", jsonObj, function(output){
alert(output);
});
I have an array($my_array) that looks something like:
array(2) {
[25]=>int(10)
[30]=>int(8)
}
I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?
Edit: At first, I thought I could just assign it like a string, but that isn't working:
var photo_limit = $my_array;
I tried also doing a var_dump into my js value.
I'm currently trying to use something like:
for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}
Thanks.
The best way is to use json_encode. See json_encode reference
Used like this:
<script>
var array = <?php echo json_encode($array)?>;
</script>
Note, hovewer, that you'll receive Javascript object, instead of array. At a glance the only difference is if you have string keys in your array, you'll be able to access them in JS like array.*string key*, i.e. using dot notation.
1: json_encode your PHP array.
2: Decode the JSON string in JavaScript using eval(alternative: jQuery.parseJSON)
<script>
var arr = eval('(<?php echo json_encode($thePhpArray); ?>)');
</script>
Here is my PHP code, it's getting a listing of collections from mongodb
$list = $db->dbname->listCollections();
$result = array();
$i=0;
foreach ($list as $thiscollection) {
$result[$i++] = $thiscollection->getName();
}
echo json_encode( $result );
I do console.log in the callback and this is what I see.
["fruits", "dogs", "cars", "countries"]
The problem is that this is a string, not an array. I need to iterate through these values. How an I make this into a real object or get php to give me json rather than php array so I can use parseJSON on it.
Thanks.
js:
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
});
I see you are using jquery, if you want data to come back to you as a json object you need to do 1 of 2 things.
add header("Content-Type: application/json") to your php file, this will tell jquery to convert it to a json object instead of as text
Add a forth parameter to your $.post,
$.post('/ajax-database.php', function (data) {
console.log($.parseJSON(data));
$.each(data, function (key, value) {
console.log(value);
});
}, "json");
that will tell jquery to call your error handler if its NOT json, like if your php code fails and outputs html instead. You really should use $.ajax, i have no idea why anyone uses $.post, you can't do ANY meaningful error handling.
JSON is strings. If you want to be able to iterate over it then you need to decode it.