Hello I've this array in Symfony on my controller:
$array = [
"label" => [
"january",
"february"
],
"data" => [
0,
1
]
];
I wish I could convert it for use in Javascript.
The goal is that I can get in JS:
["january", "february"]
and
[0,1]
to use them as array variables
I tried json_encode($array), it works but I can't access to my array using {{array["label"}} in Twig in the Javascript block
Can someone help me please ?
EDIT : Okay guys, it works now, I did this :
Controller :
return $this->render('products/index.html.twig', [
"report" => json_encode($report),
]);
index.html.twig (javascript bloc)
const data = {{report | raw}};
Thanks all !
You do not have to call JSON.parse since the output of json_decode is a javascript literal. Just assign it to a variable.
var yourArray = <?php echo json_encode($array); ?>;
You can access property like this
alert(yourArray[0].Key);
You can try use:
PHP:
$array = [
"label" => [
"january",
"february"
],
"data" => [
0,
1
]
];
$response = new Response(json_encode($array));
$response->headers->set('Content-Type', 'application/json');
return $response;
JavaScript:
var data = JSON.parse(response);
console.log(data.label)
Hope help you.
What you get is a Json string, not an object, you first have to parse it in Javascript.
const data=JSON.parse(array);
Related
Hello I am working on the data structure. I have following problems:
when I dump ($ data), I have all the info.
I am looking for how has integrated a php variable in json.
here is my piece of code. I have serious problem with concatenation. thank you in advance
<script type="application/ld+json">
{
"name":"<?php ($data[restaurant_name]);?>"
"author": {
"#type": "<?php.....?>",
"name": "<?php.....?>"
},
"datePublished": "<?php ($data[date]);?>",
"description": "<?php ($data[description]);?>",
}
</script>
Do not construct JSON objects like this, it's error-prone!
just using PHP construct an associative array, then use json_encode() function to create valid JSON object and pass whole to JS.
// variables
$name = 'Foo';
$type = 'bar';
$authorName = 'John';
// array
$data = [
'name' => $name,
'author' => [
'#type' => $type,
'name' => $authorName
]
];
// encode to JSON and display
echo json_encode($data);
Edit 2 : even better, multiple values works
Actually, one simply has to give a "value" field that fills the box. No need for the "id/label" field, but value field is required. This is working :
foreach ($queries as $query)
{
$results[] = [
'zip' => $query->zip,
'value' => $query->commune,
'libelle' => $query->libelle,
'lieudit' => $query->lieudit
];
}
return Response::json($results);
Edit : here is the solution, thanks to Adyson's answer
The script should be json formatted and returning
An array of objects with label and value properties:
[ { label: "Choice1", value: "value1" }, ... ]
(jQuery API documentation)
So, modifying the PHP script like this will work :
foreach ($queries as $query)
{
$results[] = [
'id' => $query->zip,
'value' => $query->commune,
];
}
return Response::json($results);
Original question
Using Jquery Autocomplete, querying a script.
The list shows as many rows as there are results (when I set my script to return X results, there are X rows as well in the list) :
But it doesn't fill the rows with the data. What could have gone wrong there ?
The data returned is some json :
Request URL:http://localhost:8000/search/autocomplete?term=750
Request Method:GET
Status Code:200 OK
Remote Address:127.0.0.1:8000
Response Headers
view source
Cache-Control:no-cache
Connection:close
Content-Type:application/json
Date:Tue, 15 Nov 2016 14:53:07 GMT
Host:localhost:8000
And here is the data :
[{"zip":"75004","commune":"PARIS 04","libelle":"PARIS","lieudit":""},
{"zip":"75005","commune":"PARIS 05","libelle":"PARIS","lieudit":""},
{"zip":"75003","commune":"PARIS 03","libelle":"PARIS","lieudit":""},
{"zip":"75006","commune":"PARIS 06","libelle":"PARIS","lieudit":""},
{"zip":"75008","commune":"PARIS 08","libelle":"PARIS","lieudit":""},
{"zip":"75012","commune":"PARIS 12","libelle":"PARIS","lieudit":""},
{"zip":"75015","commune":"PARIS 15","libelle":"PARIS","lieudit":""},
{"zip":"75016","commune":"PARIS 16","libelle":"PARIS","lieudit":""},
{"zip":"75017","commune":"PARIS 17","libelle":"PARIS","lieudit":""},
{"zip":"75010","commune":"PARIS 10","libelle":"PARIS","lieudit":""},
{"zip":"75018","commune":"PARIS 18","libelle":"PARIS","lieudit":""},
{"zip":"75001","commune":"PARIS 01","libelle":"PARIS","lieudit":""},
{"zip":"75009","commune":"PARIS 09","libelle":"PARIS","lieudit":""},
{"zip":"75014","commune":"PARIS 14","libelle":"PARIS","lieudit":""},
{"zip":"75002","commune":"PARIS 02","libelle":"PARIS","lieudit":""},
{"zip":"75007","commune":"PARIS 07","libelle":"PARIS","lieudit":""},
{"zip":"75011","commune":"PARIS 11","libelle":"PARIS","lieudit":""},
{"zip":"75013","commune":"PARIS 13","libelle":"PARIS","lieudit":""},
{"zip":"75019","commune":"PARIS 19","libelle":"PARIS","lieudit":""},
{"zip":"75020","commune":"PARIS 20","libelle":"PARIS","lieudit":""}]
Here is my JS :
$(function(){
$( "#fromzip" ).autocomplete({
source: "/search/autocomplete",
dataType: 'json',
minLength: 3,
});
});
The HTML :
<input
id="fromzip"
name="fromzip"
type="text"
class="form-control"
placeholder="69003"
pattern=".{5}"
title="5 numbers zip"
maxlength="5"
required >
And the PHP (Laravel Input, DB and Response facades) :
public function autocomplete(){
$term = Input::get('term');
$results = array();
$queries = DB::table('zips')
->where('zip', 'LIKE', $term.'%')
->orWhere('libelle', 'LIKE', $term.'%')
->take(30)->get();
foreach ($queries as $query)
{
$results[] = [ 'zip' => $query->zip,
'commune' => $query->commune,
'libelle' => $query->libelle,
'lieudit' => $query->lieudit];
}
return Response::json($results);
}
Have a look at http://api.jqueryui.com/autocomplete/#option-source. It states that the data must be in the format
[ { label: "Choice1", value: "value1" }, ... ]
Your sample data items don't have either of those properties (label or value).
You can modify your server-side script to output the right format, or if you can't/won't do that, you could use the source-as-a-function option in the plugin to write a function that transforms the data.
I make this function in php, but i want to make now in Jquery, is the same process to build a this json format in jquery?
I need the same format like this PHP, but now in jquery
$json_full = array();
$json= (object) array (
"salutation"=>'test' ,
"title"=>'test' ,
"first_name"=>'test' ,
"last_name"=>'test' ,
"street"=>'test' ,
"street_number"=>'test' ,
"address_supplement"=>'test' ,
"zipcode"=>'test' ,
"city"=>'test' ,
"country"=>'test' ,
"terms_accepted"=>true,
"receiving_mails_accepted"=>'test' ,
"email"=>'test' ,
"lottery_accepted"=> false,
"lottery_solution"=> "LOTTERY",
"original_created_at"=>'test' ,
);
$json->items = (object )array (
'campaign_number' =>'test' ,
'item_number' =>'test' ,
);
array_push($json_full, $json);
print_r(json_encode($json_full));
In javascript you can do this:
var json = { // Create object
"salutation" : "test",
"title" : "test",
"lottery_accepted" : true, // Boolean
"items" : [{ // Array of objects
"campaign_number" : "test",
"item_number" : "test"
}],
...
};
var jsonfull = []; // Push to jsonfull.
jsonfull.push(json);
Convert to string:
JSON.stringify(json);
I'm having trouble with JSON. I made this in PHP and I'm sending it to my JavaScript, but I can't get the values.
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
},
}
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
},
}
]
I'm trying to access it with
var obj = JSON.parse(result);
alert(obj.book[0].dir[1]);
Anyone have any ideas?
First you need to validate your json, i have validate your json it gives error.
In your json dIr is id.
You have defined 3 dir id for same object this may be error.
EDIT: I missed it but first comment explains your missing your closing square brackets for the book arrays. Add that in and your good to go. Validate the JSON first.
You don't need to do JSON.parse you can simply do
var data = <?php echo "Your generated JSON code"; ?>;
Worth a note you can create your data structure in PHP and then simply use json_encode, then you can be sure it will be valid JSON
var data = <?php echo json_encode($yourData); ?>;
You have output an array so to get the first object you will do something like
var firstObj = data[0];
To get the first dir of the first book
var firstDir = data[0]["book"][0]["dir"];
[
{
"book": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
},
{
"book2": [
{
"dir": "extract/pg6130-images.epub"
},
{
"dir": "extract/pg6130-images.epub/6130/0.css"
}
]
}
]
Your JSON was not valid i used: http://jsonlint.com/ to sort it!
Now you should be able to acess the data fine.
The code shown in the question is not a valid JSON. There are missing closing square brackets for each of the book arrays and (thanks to #punund) a missing comma between array members. The correct JSON would be this:
[
{
"book":[
{
"dir":"extract\/pg1065.epub"
},
{
"dir":"extract\/pg1065.epub\/1065\/0.css"
},
{
"dir":"extract\/pg1065.epub\/1065\/1.css"
}
]
},
{
"book":[
{
"dir":"extract\/pg6130-images.epub"
},
{
"dir":"extract\/pg6130-images.epub\/6130\/0.css"
}
]
}
]
You should not normally be printing JSON directly, but instead creating a JSON object in PHP and then using json_encode function. The following PHP will produce valid JSON for your scenario:
<?php
$result = array(
(object)array("book" => array((object)array("dir" => "extract/pg1065.epub"),
(object)array("dir" => "extract/pg1065.epub/1065/0.css"),
(object)array("dir" => "extract/pg1065.epub/1065/1.css"))),
(object)array("book" => array((object)array("dir" => "extract/pg6130-images.epub"),
(object)array("dir" => "extract/pg6130-images.epub/6130/0.css")))
);
echo json_encode($result);
?>
I tried posting a previous question, but i believe it was convoluted.
Basically, i was told "can you make the data come thru like this?" - keep in mind that this data is not derived from a form, but but by data that is driven via a search on the client side.
This is what is suppose to be sent to the server. So if you dumped the error_log, it would look this. This is all dynamic, so the object below will be that format BUT the data will change.
{
"matchedItems" :
[
{ "itemID1" :
{ "Cost" : "12",
"Size" : "small",
"Colors" : [ "blue", "red" ]
}
},
{ "itemdID2" :
{ "Cost" : "33",
"Size" : "large",
"Colors" : [ "yellow" ]
}
}
]
}
so, I run thru the some things on the page and bundle up the data and return data sets, thus the hashes within the array.
BUT for the life of me, I can't get anything to look good in the actual .ajax post. When I console.log the data out, it looks good. Its an array of hashes. etc... looks fine. BUT the following is what is actually sent when I look at the params of the request. So below is what I am actually sending. It did some weird merging and such, it looks like.
{
'matchedItems[0][itemid1][Color]' => 'Blue',
'matchedItems[0][itemid1][Size]' => 'small',
'matchedItems[0][itemid1][Cost]' => '33.90',
'matchedItems[1][itemid2][Color][]' => ['Silver'],
'matchedItems[1][itemid2][Size]' => 'small',
'matchedItems[1][itemid2][Cost]' => '44',
'matchedItems[2][itemid3][Color][]' => ['blue','Red'],
'matchedItems[2][itemid3][Size]' => 'large',
'matchedItems[2][itemid3][Cost]' => '23'
};
I tried to $.params the data, no luck. I tried various data settings in dataType, no luck. I am at a loss on how to format the data I send that mimics what I posted first.
Any ideas?
You should json_encode() your output from PHP
Example:
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Output:
{"a":1,"b":2,"c":3,"d":4,"e":5}
You can use jQuery to decode the json you got back from the ajax reply:
var json_reply = jQuery.parseJSON('{"a":1,"b":2,"c":3,"d":4,"e":5}');
alert( json_reply.a ); // alerts "1"