Cannot access Object key "#attributes" for itunes RSS feed - javascript

I'm trying to parse an itunes RSS feed by converting it to JSON via php and then inserting it with jQuery .ajax.
First is the php
<?php
$url = "http://schoolceoshow.libsyn.com/rss";
$fileContents = file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents);
$json = json_encode($simpleXml);
echo $json;
?>
Now the javascript
var root = location.origin + "/";
$.ajax({
url:root + "php/podcast.php",
type:"GET",
data:"json",
success:function(data){
var dataObject = $.parseJSON(data);
console.log(dataObject.channel.item[0].enclosure);
},
error:function(){
console.log("failed");
}
});
What that logs out is
Object {#attributes: Object}
#attributes: Object
length: "25583209"
type: "audio/mpeg"
url: "http://traffic.libsyn.com/schoolceoshow/SchoolCEOShow-007.mp3"
My only issue here is accessing the #attributes key. How do I access a key with an # symbol? Thanks!

The solution is to access the object with bracket notation. What I've added to my code is
var enclosure = dataObject.channel.item[0].enclosure;
console.log(enclosure["#attributes"]);
Answer was found at : Parsing JSON w/ # at sign symbol in it (arobase)

Related

How to make php array to be a javascript array? [duplicate]

This question already has answers here:
Convert php array to Javascript
(21 answers)
Closed 4 years ago.
I have file php that send value in array by query to ajax.
$sql = "SELECT * FROM populasi INNER JOIN waktu ON populasi.idWaktu = waktu.id WHERE waktu.jam = $jam";
$result = $con->query($sql);
$points=array();
foreach ($result as $m) {
$points[] = 'new google.maps.LatLng('.$m[x].', '.$m[y].')';
}
print_r($points);
this ajax will receive a value from php file and I want the value to be a javascript array like "var points". Can you help me how to do it ? Thanks
$.ajax({
type: "POST",
url: "proses.php",
data: {
jam: slider.value,
},
success: function(response){
//example array points
var points = [
new google.maps.LatLng(-7.320339, 112.768071),
new google.maps.LatLng(-7.320233, 112.768446),
];
}
});
can you please try below code
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable.get response and used to your javascript code
<?php $json_points = json_encode($points); ?>
A good solution for this is to convert data to JSON format in php and pass it to your js code
in your php:
$sql = "SELECT * FROM populasi INNER JOIN waktu ON populasi.idWaktu = waktu.id WHERE waktu.jam = $jam";
$result = $con->query($sql);
$result = json_encode($result);
echo($result);
in js:
$.ajax({
type: "POST",
url: "proses.php",
data: {jam:slider.value,
},
success: function(response){
response=JSON.parse(response);
var points=[];
for(var i=0; i<response.length; i++){
var responsePoint=response[i];
points.push(new google.maps.LatLng(responsePoint.x, responsePoint.y));
}
}
});

convert js array to php array and check its content

I want to sent a JS array to remote php server and convert it to a php array.
To check if php array is equal to js array I'm trying to get its members inside result div, but without success.
var rlist = ["title1", "title2", "title3"];
var b = JSON.stringify(rlist);
$.ajax({
url: 'reorder.php',
type: 'post',
data: {'b': b},
success: function(data) {
$("#result").html(data);
}
});
reorder.php
$rlist = json_decode( $_POST['b'], true );
echo $rlist;
try to put this code in the reorder.php
$rlist = json_decode( $_POST['b'], true );
foreach ($rlist as $value) {
echo "<div>" . $value . "</div>";
}
You can use json_decode as jQuery ajax submits it's arrays as json.
// Use as object
$json = json_decode($_POST['postdata']);
// Use as
echo $json->seomthign
$json = $_POST['postdata'];
// Output array
echo "<pre>";
var_dump(json_decode($json));
echo "</pre>";

Ajax read PHP generated json

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...
This is my ajax:
function find(){
var type = $('#object_type').val();
$.ajax({
type : 'POST',
url : 'get_user.php',
data : {
'type' : type
},
dataType : 'json',
error : function(response){
alert('SOMETHING WENT WRONG');
},
success : function(response){
This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
}
});
}
This is my PHP function:
$type = $_POST['type'];
$user_array;
$user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();
while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {
$row_array['name'] = $row['name'];
$row_array['link'] = $row['link'];
array_push($user_array, $row_array);
}
mysqli_close($conn);
$result = json_encode($user_array, 128);
echo json_encode($result);
First change that you should make :
You don't need to encode two times
$result = json_encode($user_array, 128);
echo json_encode($result);
should be
$result = json_encode($user_array, 128);
echo $result;
Now the response should look like
[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]
which is a valid Javascript Array and can be accessed using following code :
var len = response.length;
for(i=0;i<len;i++){
console.log(response[i].name);
console.log(response[i].link);
}
As provided in techierishi's answer. Do not encode your response twice. Just do
echo $result;
The JSON should be valid and parsed, why?
json_encode is used on a valid PHP array returned from a MySQLi query.
dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.
The JSON that is returned has the following structure
ROOT
ARRAY
ARRAY OBJECT
OBJECT PROPERTY
To address something like that:
root[array index].property
Will give you the array's value, which is an object. That object has multiple properties.
[] means array
{} means object
So [{name:"value 1"},{name:"value 2"}] is actually
ARRAY
[0].name = value 1
[1].name = value 2
So retrieving information like name from your JSON will be:
response[0].name; // = test

php decode json array

I have a php page that receives a json object from javascript page, but i was not able to decode the json in php. How to decode the json and store in php such that $arr[0]=[1,2,34,5,2]; $arr[1]=[2,1,34,5,2]; $arr[2]=[8,1,34,5,2]; in php ?
after removing "myString = JSON.stringify(myObject);"
echo $value; outputs "Array"
echo $value[0]; outputs nothing
echo $value->{"key"}; outputs nothing either
how can i actually get the array contents?
javascript:
var mon=[1,2,34,5,2];
var tue=[2,1,34,5,2];
var wed=[8,1,34,5,2];
var myObject = {'key' :'value','key2':'value','key3':'value'};
myObject.key = mon;
myObject.key2 = tue;
myObject.key3 = wed;
myString = JSON.stringify(myObject); //this line removed
var jsonString = JSON.stringify(myObject);
$.ajax({
type: "POST",
url: "n3.php",
data: {data : jsonString},
cache: false,
success: function(aaa){
alert("OK");
$("#pageContent").html(aaa);
}
});
php:
<?php
$value = json_decode($_POST['data']);
echo $value; //this echos the whole json object
echo $value->{"key"}; //this outputs nothing
?>
You are JSON encoding your data twice on the Javascript side. When you call json_encode in PHP once, you get a JSON encoded object back. That's why echo $value outputs the whole string. If it was a PHP array at this point it would output "Array" or an error in case it was an object, it would not output the whole content.
Either json_decode it again, or don't double encode it in Javascript.

json_encode with multidimensional array returning string "array" instead of data

I am passing a multidimensional array back to a .php file using json, jquery, and ajax. My goal is essentially to fill a drop down box (id=project) with multiple entries. Here's some code snippets:
$("#turninId").change(function() {
var user_id = $("#turninId").val();
$.ajax ( {
url:"send_input.php",
type: "POST",
dataType: "json",
data:{id_selection: user_id},
success:function(response) {
for (var i=0; i<response.proj.length; i++) {
$("#exp").html(response.proj[i]);
$("#project").html(response.proj[i]); } });
});
In send_input.php (backend), I query a db, and send the information to an array. Then I use json_encode.
$query="SELECT project FROM main";
$results = $db->query($query);
while ($row_id = $results->fetchArray()) {
$proj_option[] = "<option value=\"".$row_id['project']."\">".$row_id['project']."</option>\n";
$pselected=$row_id['project'];
}
$output = array( "proj" => "$proj_option");
echo json_encode($output);
My problem is that this is RETURNING THE STRING "Array".
For example, if I do: response.proj[0], I get "A" returned.
What gives? I've seen a few people with questions about this error, but no definite solution. Any help?
This is because you are casting $proj_option to a string by enclosing it in quotes. Just remove the quotes and you will get the array.

Categories

Resources