Pass existing php array to jquery - php

I have a PHP array I want to pass to my jquery (replace the test array with my php array).
Array
(
[12] => Some Text
[6] => Another text
[11] => one more text
)
Jquery:
$('#SearchUser').typeahead({
source: [
{ ID: 1, Name: 'Toronto' },
{ ID: 2, Name: 'Montreal' },
{ ID: 3, Name: 'New York' },
{ ID: 4, Name: 'Buffalo' },
{ ID: 5, Name: 'Boston' },
{ ID: 6, Name: 'Columbus' },
{ ID: 7, Name: 'Dallas' },
{ ID: 8, Name: 'Vancouver' },
{ ID: 9, Name: 'Seattle' },
{ ID: 10, Name: 'Los Angeles' }
],
display: 'Name',
val: 'ID',
itemSelected: updateID
});
So how can I set the var for "source" to my php array?
Suggestions?
As always,, you are awesome!
-Tom

How I'd done it in one of my projects was,
$.get("<?= $baseUrl ?>search/data", function (data) {
var dataObject = JSON.parse(data);
$('#q').typeahead({
'source': dataObject,
// 'items': 5
});
});
and my search controller's data method is:
echo (json_encode($arr)); // $arr is ["a","b","c"] etc. but you can have an associated array too.
Basically, the point of showing my code is to say use json

You can use json_encode function of php to conver a php array to json. Then you can use the json as javascript array.
http://www.php.net/manual/en/function.json-encode.php
I don't know how you get data from php code to javascript code, but if you print data as json, you can take it via an ajax call.

Use PHP's json_encode() function to create a string that is a valid JSON, and then read that with jQuery's $.getJSON().
Something like this:
get_array.php
$someArray = /* whatever */;
echo json_encode($someArray);
read_array.js
$.getJSON('get_array.php', function(data) {
// data now contains your array
});
Alternatively, you could do something like this:
<script type="text/javascript">
var someArray = <?php echo json_encode($someArray); ?>
</script>
If you don't want the separate files and don't mind using a global variable for it.

You can do the following:
<script type="text/javascript">
var jsArray = <?php echo json_encode($phpArray); ?>
</script>
but it is a bad practice to mix language X with language Y.
Well, take a look at my answer to this post in which you can do the following in a better way:
Is echoing Javascript code condtionally based on server-side logic considered harmful?
Hope this helps :-)

Related

Handling PHP response with Axios/React Native

I'm a React Native beginner, please excuse basic questions. I'm having trouble handling json returned from PHP in react native using axios get.
My php returns (have tried both with and without headers part, and also tried with/without json_encode):
<?php
$json ="[{
id: 1,
title: 'List Item One',
description: 'test1'
},
{
id: 2,
title: 'List Item Two',
description: 'test2'
}]";
header('Content-Type: application/json; charset=utf-8');
echo json_encode($json);
My react native function is below (with the part I'm trying to get to work commented out)
const [messages, setMessages] = useState([]);
useEffect(() => {
loadMessages();
}, []);
const loadMessages = async () => {
let res = await axios.get('https://example.com/test_messages.php');
//setMessages(res.data);
console.log(res.data);
}
return (
<Screen style={styles.screen}>
<FlatList
data={messages}
keyExtractor={message => message.id.toString()}
renderItem={({item}) => (
The console.log seems to work and returns:
[{
id: 1,
title: 'List Item One',
description: 'test1'
},
{
id: 2,
title: 'List Item Two',
description: 'test2'
}]
but when I try to use the commented part instead, I get this error:
"undefined is not an object ('evaluating message.id.toString')"
It seems to just be formatting the output because the console.log seems fine. Further, when I hard code the array into a variable and use it in the useState function, it works fine also.
The format of this json maybe incorrect, you can check it at https://jsonlint.com/. The correct format should be like the output of JSON.stringify below

Sending object via $.post

I have an object saved in the variable called items.
0: Object
name: "Jim"
age: "42"
1: Object
name: "Bill"
age: "50"
When trying to post
$.post("mypage.php", items, function(data)
I get an empty post variable in the php page, but this returns post variables
$.post("mypage.php", "name=jim", function(data)
What am I doing wrong?
Edit it is an array of objects so if I pass
$.post( "mypage", items[0], function( data) {
I get a results but
$.post( "mypage", items, function( data) {
print_r is empty
It looks like the object you're posting may be an array with this format:
items = [
{
name: "Jim",
age: "42"
},
{
name: "Bill",
age: "50"
}
]
The docs seem to indicate that you must pass a plain object. You probably want to post something with the format:
items = {
people: [
{
name: "Jim",
age: "42"
},
{
name: "Bill",
age: "50"
}
]
};
Then you should be able to access the data via $_POST['people'].
UPDATE
To be accurate, you can post your array just fine, it will generate this post Jim=&Bill=
Almost surely not what you want. However if you follow the syntax specified by jQuery.param, your array will be treated correctly. Should be and array of objects with name and value:
items = [
{
name: "Jim",
value: "42"
},
{
name: "Bill",
value: "50"
}
]
You are using a curious behaviour of jQuery. It's found in the $.param function, which is used behind the scenes to prepare an AJAX query from your data.
If you send an array, jQuery expects it to be an array of objects, each of which has two keys, name and value. You are obviously not providing data in that structure. Your script actually sends data that looks like this:
Jim=undefined&Bill=undefined
If you do print_r($_POST['Jim']); in PHP, you will get the string undefined.
You obviously don't want this. You need to send the array within an object.
{
people: [
{
name: 'Jim',
age: 42
},
{
name: 'Bill',
age: '50'
}
]
}
This way your data will be serialised as this:
people[0][name]=Jim&people[0][value]=42&people[1][name]=Bill&people[1][age]=50
If you do print_r($_POST['people']);, you will get a meaningful result.

PHP loop through jquery loop

I have this simple jQuery function:
$(document).ready(function () {
var books = {};
books.id = '1';
books.author = 'Bob';
$.post('/index.php',
{
books: books
},
function(data, textStatus)
{
alert(data);
});
});
And this index PHP script:
<?php
foreach($_POST['books'] AS $key) {
echo ''.$key['id'].' is written by '.$key['author'].'';
}
?>
I want to loop through the jQuery array and display the id and author of each key in the array. I don't know the correct way to access the values in the array. It seems I'm doing it wrong.
You have misunderstood the difference between {} and [] in JavaScript:
{} is an object
[] is an array
In your case you should pass an array of book objects for this to work in your php script.
Example:
var books = [
{
id: 1,
name: "The Da Vinci Code",
author: "Dan Brown"
},
{
id: 1,
name: "Gray Mountain: A Novel",
author: "John Grisham"
}
]
To add more elements to the array after it has been initialized, you can simply use push:
books.push({id: 3, name: "Avatar", author: "Lisa Fitzpatrick"});
Will output:
1 is written by Dan Brown
2 is written by John Grisham
3 is written by Lisa Fitzpatrick

Javascript, using Highcharts to display a chart of rankings with JSON Data

I am trying to use javascript Highcharts to display a chart of rankings from JSON data. I can't seem to get the chart to display.
This is the javascript code:
$(document).ready(function() {
var options = {
chart: {
renderTo: 'drawing',
zoomType: 'x',
width: 900,
height: 222
},
exporting: {
enabled:true
},
title: {
text: url+' - '+keyword
},
credits: {
text: '****',
href: 'http://***/'
},
xAxis: {
type: 'datetime',
dateTimeLabelFormats: {
day: '%b %e '
}
},
yAxis: [{
//min: 1,
allowDecimals: false,
reversed: true,
///: .2,
//maxPadding: .2,
title: {
text: 'Rankings'
}
},],
tooltip: {
crosshairs: true,
shared: true
},
series: [{}]
};
var url = "http://*******/chart.php";
$.getJSON(url, function(data) {
$.each(data, function(arrayID,group) {
$.each(group.data, function(id,val) {
arg = val[0].replace(/Date.UTC\((.*?)\)/, '$1').split(',');
var timestamp = Date.UTC.apply( null , arg );
date=new Date(timestamp);
data[arrayID].data[id][0] = timestamp;
});
});
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
});
Our PHP Script gives us this JSON:
[{"name":"Google Rank","data":[["Date.UTC(2013,04,05)","23"],["Date.UTC(2013,04,04)","23"],["Date.UTC(2013,04,03)","22"],["Date.UTC(2013,04,02)","24"],["Date.UTC(2013,04,01)","26"],["Date.UTC(2013,03,31)","24"],["Date.UTC(2013,03,30)","24"],["Date.UTC(2013,03,29)","25"],["Date.UTC(2013,03,28)","25"],["Date.UTC(2013,03,27)","25"],["Date.UTC(2013,03,26)","26"],["Date.UTC(2013,03,25)","25"],["Date.UTC(2013,03,24)","24"],["Date.UTC(2013,03,23)","-"],["Date.UTC(2013,03,22)","10"],["Date.UTC(2013,03,21)","10"],["Date.UTC(2013,03,20)","10"],["Date.UTC(2013,03,19)","10"],["Date.UTC(2013,03,18)","10"],["Date.UTC(2013,03,17)","10"],["Date.UTC(2013,03,16)","9"],["Date.UTC(2013,03,15)","9"],["Date.UTC(2013,03,14)","9"],["Date.UTC(2013,03,13)","9"],["Date.UTC(2013,03,12)","9"]],"visible":"true","pointInterval":"86400000","showInLegend":"false"},{"name":"Bing Rank","data":["Date.UTC(2013,2,9)",9],"visible":"true","pointInterval":"86400000","showInLegend":"false"}]
Note the JSON data represents numbers as strings which could be a problem.
PHP Code which generates the JSON data:
$googledata = array();
while($gkdata = mysql_fetch_assoc($keywordquery)){
$explodedate = explode("-", $gkdata['date']);
$year = $explodedate[0];
$month = $explodedate[1];
$day = $explodedate[2];
$googledata[] = array(
"".$year.",".$month.",".$day."",
$gkdata['grank'] //$gkdata['grank'] should be a number, but is sometimes a dash so it's cast to an accommodating datatype: string.
);
}
$chartdata = array(
array(
"name" => 'Google Rank',
"data" => $googledata,
"visible" => 'true',
"pointInterval" => '86400000',
"showInLegend" => 'false',
),
array(
"name" => 'Bing Rank',
"data" => array(
'Date.UTC(2013,2,9)',
9
),
"visible" => 'true',
"pointInterval" => '86400000',
"showInLegend" => 'false',
)
);
The Highcharts won't display anything other than the chart itself with no data. The Date.UTC(2013,03,12) is supposed to go on the X-Axis & the number next to it is supposed to be the rank number. Can anyone see what is wrong?
The chart takes data as [x,y]. You just need to reverse the order of your data to ['value',datestamp'] if you want the date to be on the y axis.
Edit:
I am not sure from the text what the problem you are having is, but one problem that will arise from your code is that your number data values are being returned as strings, in quotes.
You will need to cast them as integers in your php before json encoding in order for them to come through unquoted, as integers.
You should be seeing an error from this: http://www.highcharts.com/errors/14
You are expecting $gkdata['grank'] to always return a number, it sometimes returns a dash -. The Array Object is using the datatype which best represents the data, and it chooses string. If you want to force it as int, you'll have to use a data structure that only allows integers to be put in it. Then it will puke when you try to put in a dash, which it should be doing, because how do you plot a DASH on a chart?
Had you taken off your blindfold, and looked at the error HighCharts returned to you, you would see this:
Highcharts Error #14 String value sent to series.data, expected Number
This happens if you pass in a string as a data point, for example in a setup like this:
series: [{
data: ["3", "5", "1", "6"]
}]
Highcharts expects the data values to be numbers. The most common reason for this is that data is parsed from CSV or from a XML source, and the implementer forgot to run parseFloat on the parsed value.
For performance reasons internal type casting is not performed, and only the first value is checked (since 2.3).
So fix your code to make grank always a number. HighCharts won't plot strings for performance reasons.

Javascript Pie Chart php to javascript object array

I am using the code at http://jsfiddle.net/MX7JC/9/ to build a pie chart.
But I want the data to come from php variables. How do I change :
var agg = { label: 'Aggressive', pct: [60, 10, 6, 30, 14, 10] },
as seen in the code on the link, so that pct consists of an array of php variables rather than fixed numbers. Such as :
var agg = { label: 'Aggressive', pct: [$r1, $r2, $r3, $r4, $r5, $r6]},
How do I alter the code to allows this? I tried json encode and I am having problems.
You can generate the Javascript when it's defined using PHP:
<script type="text/javascript">
var agg = { label: 'Aggressive', pct: [
<?php echo $r1.", ".$r2.", ".$r3.", ".$r4.", ".$r5.", ".$r6; ?>
]},
</script>

Categories