How I can get values of array result? - javascript

I'm new and I work in php. I have a problem, I have this "array" result from php script (this array was extracted with php of a html page):
Array ( [0] => {"autostart": false,"controls": true,"flashplayer": "/jwplayer7/jwplayer.flash.swf","image": "I NEED THIS", ga: {}, "mute": false, "ph": 1, "preload": "none", "primary": "html", "repeat": false, "skin": { "name": "tube" }, "stagevideo": true, "stretching": "uniform", "visualplaylist": true, "width": "100%", "aspectratio": "16:9", "provider": 'http', "startparam": "start", tracks: [{"file":"I WANT THIS","kind":"thumbnails"}], "sources": [{"file":"I NEED THIS","label":"480p"},{"file":"I NEED THIS","label":"720p"},"I WANT THIS"] ,"logo": {"logoBar": "I NEED THIS", "target": "blank","link": ""},"displaydescription": false,"displaytitle": false , "abouttext": "RapTu Player", "aboutlink": "" } )
I only need the values from image:, sources:[{"file";}} but I can't get the values, nothing, I try with javascript:
var str = '<?php echo $jw; ?>';
var json = JSON.parse(str);
var parse = $.parseJSON(file);
$jw is the variable of the array, and I don't have any result, nothing is printed. Could you help me? (Sorry for my english).
Upgrade: I resolved it using:
object = [<?php echo $jw; ?>]
for(f=0;f<object.length;f++){
}
Thanks everybody!

if you want doing that.
Then use
var json = '<?php echo json_encode($jw); ?>';
and in json variable you have json from array
or if you only sources you can use
var json = '<?php echo json_encode($jw[0]["sources"]); ?>';
but only work with first element in array $jw

In php:- encode string in php properly
$json = json_encode('{"autostart": false,"controls": true,"flashplayer": "/jwplayer7/jwplayer.flash.swf","image": "I NEED THIS", ga: {}, "mute": false, "ph": 1, "preload": "none", "primary": "html", "repeat": false, "skin": { "name": "tube" }, "stagevideo": true, "stretching": "uniform", "visualplaylist": true, "width": "100%", "aspectratio": "16:9", "provider": "http", "startparam": "start", tracks: [{"file":"I WANT THIS","kind":"thumbnails"}], "sources": [{"file":"I NEED THIS","label":"480p"},{"file":"I NEED THIS","label":"720p"},"I WANT THIS"] ,"logo": {"logoBar": "I NEED THIS", "target": "blank","link": ""},"displaydescription": false,"displaytitle": false , "abouttext": "RapTu Player", "aboutlink": ""}');
$array1 = array($json);
Pass $array1 to html in script:-
var str = '<?php echo $jw; ?>'; // echo $array1[0] as $jw
var json = JSON.parse(str);
var parse = $.parseJSON(file);

Related

How do include/call this Javascript file in PHP?

I am writing a PHP script that uses Twitters API's to get a response of tweets in JSON. I am then using the id's in this JSON as parameters in Twitter's widgets.createTweet() function.
The official twitter documentation for this can be found here.
I believe the problem is at the point where I am trying to icnlude the Twitter widgets.js file within my PHP script.
Here is my entire PHP script with my keys and tokens redacted:
<?php
echo "<h2>Simple Twitter API Test</h2>";
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => ""
'oauth_access_token_secret' => ""
'consumer_key' => ""
'consumer_secret' => ""
)
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user'])) {$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);} else {$user = "iagdotme";}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";exit();}
$number_tweets = count($string['statuses']);
// THIS IS THE PROBLEM AREA ///////////
echo "<script sync src='https://platform.twitter.com/widgets.js'></script>"
echo "<div class='cols'>";
foreach ($tweet_array['statuses'] as $tweet ) {
$id = $tweet["id"];
echo "<div class='grid-item'><div id='container-$id'></div></div>";
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
echo '<script>';
$t = 1;
foreach ($js_array as $js) {
echo $js;
$t++;
}
echo '</script>';
?>
I believe the problem is where I am trying to include the js file from https://platform.twitter.com/widgets.js
It seems to me like everything else here should work. This php file doesn't give me any errors when I try to open it in a browser. I am stuck.
What I'm tyring to do with this code:
make an API call to Twitter and retrieve a set of tweets
use the id's in those tweets to pass
How am I trying to do it:
Using php I have made a successful API call to Twitter with the assistance of an open sourced php library/api wrapper.
store the JSON response in an array, loop through that array getting the tweet id's (attributes for each tweet within the json)
use those id's as parameters for twitter's createTweet function
What my problem is:
I think the problem is, is that my code doesn't know what I mean when I use the twttr.widgets.createTweet() js function because htts://platform.twitter.com/widgets.js is not included properly.
To reiterate, this is where I am trying to include that file:
echo "<script sync src='https://platform.twitter.com/widgets.js'></script>"
Is that piece included properly? If so, are there other things that pop out as erroneous?
Here is a sample of the JSON response from the twitter API call.
{
"statuses": [
{
"created_at": "Wed May 15 15:13:53 +0000 2019",
"id": 1128679903329542144,
"id_str": "1128679903329542144",
"text": "Araw-gabi nasa isip ka, napapanagip ka kahit sa'n magpunta",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"metadata": {
"iso_language_code": "tl",
"result_type": "recent"
},
"source": "Twitter for Android",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 1016132854999183360,
"id_str": "1016132854999183360",
"name": "L Y S A💛",
"screen_name": "ilysachn",
"location": "Home📍",
"description": "",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 97,
"friends_count": 73,
"listed_count": 0,
"created_at": "Mon Jul 09 01:32:06 +0000 2018",
"favourites_count": 624,
"utc_offset": null,
"time_zone": null,
"geo_enabled": true,
"verified": false,
"statuses_count": 188,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "F5F8FA",
"profile_background_image_url": null,
"profile_background_image_url_https": null,
"profile_background_tile": false,
"profile_image_url": "http://pbs.twimg.com/profile_images/1125769288797675520/3Ez4FP9n_normal.jpg",
"profile_image_url_https": "https://pbs.twimg.com/profile_images/1125769288797675520/3Ez4FP9n_normal.jpg",
"profile_banner_url": "https://pbs.twimg.com/profile_banners/1016132854999183360/1553425392",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "tl"
},
If you want to know what syntax errors you have in runtime use phpstorm.
I fix errors and now code looks like this
and your script will connect in php file.
<?php
echo "<h2>Simple Twitter API Test</h2>";
require_once('TwitterAPIExchange.php');
$settings = [
'oauth_access_token' => "",
'oauth_access_token_secret' => "",
'consumer_key' => "",
'consumer_secret' => ""
];
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user'])) {
$user = preg_replace("/[^A-Za-z0-9_]/", '', $_GET['user']);
} else {
$user = "iagdotme";
}
$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest(),$assoc = TRUE);
if(array_key_exists("errors", $string)) {
echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string["errors"][0]["message"]."</em></p>";exit();
}
$number_tweets = count($string['statuses']);
?>
<script sync src='https://platform.twitter.com/widgets.js'></script>
<?php
echo "<div class='cols'>";
foreach ($tweet_array['statuses'] as $tweet ) {
$id = $tweet["id"];
echo "<div class='grid-item'><div id='container-$id'></div></div>";
$js_array[] = "twttr.widgets.createTweet('$id', document.getElementById('container-$id'));";
}
echo "</div>";
?>

how to assign php variable value to a javascript variable [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 4 years ago.
I am trying to pass a value from a php variable to a javascript variable. So instead of defining manually each time {"data": "Country"},{"data": "Customer Name"}... as you see below
<script type="text/javascript">
$(document).ready(function () {
$('#users').DataTable({
"columns": [
{"data": "Country"},
{"data": "Customer Name"},
{"data": "Order Number"},
{"data": "Address"}
],
"processing": true,
"serverSide": true,
"ajax": {
url: 'demo2.php',
type: 'POST'
}
});
});
</script>
Let's say I have a php variabe defined on the top of my html as below
<?php
$jsColumns = '{"data": "Country"},{"data": "Customer Name"},{"data": "Order Number"},{"data": "Address"}';
?>
I want to insert this php variable inside my script
$('#users').DataTable({
"columns": [
<?php echo $jsColumns;?>
],
"processing": true,
"serverSide": true,
"ajax": {
url: 'demo2.php',
type: 'POST'
}
});
It's not working inside the script but when i use echo $jsColumns; on the top in the php part i can see that the variable contains value.
Any idea please what i am missing in my code ? Thank you very much.
What you are doing looks right, but special characters in your actual data may be causing problems, and will be insecure. You could make an array of data, and then use json_encode to escape it - e.g.
<?php
$jsColumns = array(
array('data'=>'Country'),
array('data'=>'Customer Name'),
array('data'=>'Order Number'),
array('data'=>'Address')
);
?>
then
$('#users').DataTable({
"columns": <?php echo json_encode($jsColumns); ?>,
"processing": true,
"serverSide": true,
"ajax": {
url: 'demo2.php',
type: 'POST'
}
});

Send Data from Cassandra to DataTables (NoSQL)

Hey Guys I have a problem. I`m new to Cassandra and DataTables and my task is to send data from our 'Cassandra-Server' to the Table plug-in 'DataTables'.
I was looking for some examples or tutorials but I never found one for Cassandra-NoSQL.
I tried the following and this Error is always occurring:
PHP:
//setting header to json
header('Content-Type: application/json');
include 'connect.php';
$statement = new Cassandra\SimpleStatement("SELECT * FROM table1");
$result = $session->execute($statement);
//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
//now print the data
print json_encode($data);
JS:
$(document).ready(function () {
'use strict';
var table = $('#main').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "php/server-side.php",
"type": "GET"
},
"columns": [
{ "data": "name" },
{ "data": "type1" },
{ "data": "type2" },
{ "data": "type3" },
{ "data": "land" },
{
"data": "id",
"orderable": false
}
],
"order": [[0, 'asc']]
});
});
Error:
*Uncaught TypeError: Cannot read property 'length' of undefined
jquery.dataTables.min.js: 39*
I think DataTables don't know what to do with the information (json/$data).
In this example https://datatables.net/examples/data_sources/server_side.html
sspclass.php is used but it is written in SQL so no use for me =(
Can somebody help me with this specific problem?

How can i put json result into an input value using jQuery?

I am trying to put json result into a input the value.
I have this code:
$.ajax({
type:"POST",
url: '{% url "url_searchTour"%}',
data: data1,
success: function(jsonAjaxResult){
console.log(JSON.stringify(jsonAjaxResult));
$('#txt_nombre').val(jsonAjaxResult);
},
error: function(data){
alert("Got an error, Pleas conctact the Administrator");
}
});
The view returns single json object.
View:
dataSer1 = serializers.serialize("json",dataT1)
dataSer2 = serializers.serialize("json",dataT2)
data0 = json.dumps({'dataEsp':dataSer1,'dataEng':dataSer2})
return HttpResponse(data0, content_type='application/json')
How can I put the information returned into a inputy value. For example like this:
$('#txt_nombre').val(jsonAjaxResult['dataEsp.name']); //from obj1
$('#txt2_nombre').val(jsonAjaxResult['dataEng.name']); //from obj2
What i have so far is this:
console.log(jsonAjaxResult['dataEsp']);
It retuns the next code:
[{
"fields":
{
"Monday": true,
"restrictions": "No kids",
"name": "Yate Mar",
},
"model": "appMain.touresp",
"pk": 1
}]
JSON.stringify() it's the way to do it, check how it's working with your data.
var jsonData = [{
"fields":
{
"Monday": true,
"restrictions": "No kids",
"name": "Yate Mar",
},
"model": "appMain.touresp",
"pk": 1
}]
console.log(jsonData)
var txt = document.getElementById("myTxt");
txt.innerHTML = JSON.stringify(jsonData)
<textarea id="myTxt"></textarea>

Can't use JSON string from PHP in casperjs

I cant set json in args to use it in casperjs script.
Im launching first casperjs script, it return object in php file and then i need to use it in another one.
im trying to make it like this:
$command = "$casperjs $script $arg0";
$result = shell_exec($command);
$json_data = json_decode($result, true);
//here im getting some data from json but dont change it
$arg1 = json_encode($json_data); // i ried take $result but have the same result
$command = "$casperjs $script2 $arg1";
$json_data = shell_exec($command);
And here i have error:
SyntaxError: Unable to parse JSON string
$result
{ "url": "bilko.com", "webPages": [ { "url": "bilko.com", "links": [ "/site-map", "/en/", "/biography", "/gallery", "/services", "/contacts", "/gallery/corporative", "/gallery/wedding", "/gallery/birthday", "/gallery/teambuilding" ], "content": "\n\t\n\t\t\n\t\n\t \n \n \n \n \n \n" } ], "menus": { "identifier": ".menu", "items": [ [ { "text": "Биография", "url": "/biography" }, { "text": "Галерея", "url": "/gallery" }, { "text": "Услуги", "url": "/services" }, { "text": "Контакты", "url": "/contacts" } ] ] }, "top": { "content": "/images/topLogo.png", "identifier": "header" }, "footer": { "content": "Профессиональный ведущий\nНиколай Билько\n+7 925 025 33 27\n", "identifier": "footer" }, "socBtns": [ [ "https://vk.com/id23333446", "/images/socBtns/vk.png" ] ], "sitemap": [ "/biography", "/contacts", "/en/", "/gallery", "/gallery/birthday", "/gallery/corporative", "/gallery/teambuilding", "/gallery/wedding", "/services", "/site-map", null ] }
in script2 im trying to make
site = JSON.parse(system.args[4]);
If you want to pass data to casperjs then write it to a file and pass the path to the casperjs script. You can then read the contents of the file:
var fs = require("fs");
var site = JSON.parse(fs.read(system.args[4]));
You can write the JSON string to a temporary file in the php script:
$tmp = tempnam(dirname(__FILE__), "tmp");
file_put_contents($tmp, json_encode($json_data));
$json_data = shell_exec("$casperjs $script2 $tmp");
unlink($tmp);
Possible failures might be:
limit of argument length (something like 120 characters)
you can't have spaces in $arg1
your shell might try to interpret "" inside of the JSON string, so enclose the whole string in '': "$casperjs $script2 '$arg1'"
you also have non-ansi characters there that might break the call depending on the shell

Categories