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
Related
I get stuck with my code. If you know about it, please respond to this question, cause I very need your help.
I have 2 tables (proposal and surveyor).
Proposal field :
proposal_id, proposal_name, surveyor_proposal
Example row : ('1', 'this is proposal name', '3,18,22')
As you can see, this is have 3 surveyor id separated by comma)
Surveyor field :
surveyor_id, surveyor_name
Example row :
('3', 'Randy')
('18', 'Bella')
('22', 'Zidan')
! here it is, I want to print out Randi, Bella, and Zidan in the view table
Model.php :
function get_all_datatables($x) {
$this->datatables->select('proposal_name, surveyor_name');
$this->datatables->from('proposal');
$this->datatables->join('surveyor','surveyor_id = surveyor_proposal','left');
return $this->datatables->generate();
}
Controller.php :
function get_data_json($x) { //get product data and encode to be JSON object
header('Content-Type: application/json');
echo $this->m_bl->get_all_datatables($x);
}
View.php :
$("#table").dataTable({
initComplete: function() {
var api = this.api();
$('#table_filter input')
.off('.DT')
.on('input.DT', function() {
api.search(this.value).draw();
});
},
oLanguage: {
sProcessing: "loading..."
},
processing: true,
serverSide: true,
ajax: {"url": "<?= base_url('dashboard/bl/get_data_json/'.$uri); ?>", "type": "POST"},
{"data": "proposal_name"},
{"data": "surveyor_name"},
rowCallback: function(row, data, iDisplayIndex) {
var info = this.fnPagingInfo();
var page = info.iPage;
var length = info.iLength;
$('td:eq(0)', row).html();
}
});
Update!
I've been add 1 table junction, the fields is :
proposal_id_junction, surveyor_id_junction
Example Value :
('1','3') --> as Randy
('1','18') --> as Bella
('1','22') --> as Zidan
And i update my table join :
$this->datatables->join('junction','proposal_id_junction = proposal_id','left');
$this->datatables->join('surveyor','surveyor_id = surveyor_id_junction','left');
But, thats showing same proposal and different surveyor name, like this :
'this is proposal name','Randy'
'this is proposal name','Bella'
'this is proposal name','Zidan'
I want to thats view like this :
'this is proposal name','Randy, Bella, Zidan'
Please help.
I want to return for each vehicule of the API the brand name and the model name
i'm actualy using this loop:
$vehiculecount=count($data);
for($x = 0; $x < $vehiculecount; $x++) {
echo $data[$x];
echo $data[brand][name];
echo "<br>";
}
That actualy return me only :
Array
Array
Array
Array
Array
Array
...
This is what i'm getting in PHP with curl to an API :
{
totalResult: "150",
nbPageList: 2,
createdAt: "2018-05-28T09:23:05+0200",
updatedAt: "2018-05-28T10:55:14+0200",
reference: "5nqts",
reportNumber: 5,
country: "FR",
state: "vehicle.state.parc",
brand: {
reference: "56f50a85cb0f8",
name: "CITROEN"
},
model: {
reference: "57f4d339e38e3",
name: "C3 AIRDREAM BUSINESS"
},
I want to get only 'brand''name' for each vehicle for exemple.
Thx a lot for your help !
First, you should dump, as debugging purpose, the $data object in your loop.
Then, you should see that inside your loop, to acces to an element by its number, you have to use the indexed access like this :
echo $data[$x][brand][name];
Also, to access the brand and name index, you have to use string-key index like this : $data[$x]['brand']['name']
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.
I've stored a bunch of data in my database to draw a binary tree in a html canvas
Idx / Name
1 Apple
2 Bee
3 Cafe
4 Diamond
8 East
9 Game
16 Hobby
Here, idx represents the location of items in a binary tree. So the data above looks something like this in a tree
1.Apple
/ \
2.Bee 3.Cafe
/
4.Diamond
/ \
8.East 9.Game
/
16.Hobby
Now, I need to encode that database rows into a json format:
{
id: "1",
name: "Apple",
data: {},
children: [{
id: "2",
name: "Bee",
data: {},
children: [{
id: "4",
name: "Diamond",
data: {},
children: [{
// East/Game/Hobby comes here in the same manner...
}]
}]
},
{
id: "3",
name: "Cafe",
data: {},
children: [] // has no children
}]
}
What I've tried was creating an array of arrays and going through all the values descending order by grab a vale and put it into its parent array and remove it from the array. So, my pseudo code was something like this...
nodeArray = [1,2,3,4,8,9,16]; <-each node is an object with needed data contained.
treeArray = [........] <- arrays with key=>each index / value=>empty
while(nodeArray size is larger than 1) // 1 = the top most value
{
grab the last node from nodeArray
parent_idx = (int)(last one id / 2)
push the last node into the treeArray[parent_idx]
pop the used index
}
Then, I will have treeArray something like this
treeArray = [
1:[2,3]
2:[4]
4:[8,9]
8:[16]
]
...this is not the array-converted binary tree I was looking for.
So, I need to go through treeArray in desc order and relocate them... Yup. I know I'm getting messed up here :( It's getting more complicated and harder to understand.
Would be there more elegant and simpler way to do it? :(
I ended up using javascript and loop through each node and calling the following function
var objlist = {};
function buildTree(id, parent_id, data)
{
if(id in objlist) alert("It already exists!");
objlist[id] = { id: id, data: data, children: [] };
if (parent_id in objlist)
{
objlist[parent_id].children.push(objlist[id]);
}
}
where parent_id is id/2.
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 :-)