I search for some code, even I found it, but I dunno how to add a new line of the javascript he creates.
The original link is this, I have some problem in code bellow. Because I have change the code "price": "120.00", to "price": "\\using php to call some data",.
This is original code:
{
"product_id": "1",
"store_id": "1",
"price": "120.00",
"sequence": "0",
"id": "1",
"parent_id": "0",
"name": "Store 1",
"email": "store1#store1.com"
}
This is what I wrote:
$result1=mysqli_query($conn, "select * from product");
while ($row1=mysqli_fetch_assoc($result1))
{
$pno1 = $row1["no"];
$sql1 = "SELECT * FROM xx where WHERE product_id = '$pno1') ";
$query1 = mysqli_query($conn , $sql1);
$rowcont1 = mysqli_num_rows($query1);
?>
{
"name": "<?php echo $row1["PACKAGE_NAME"]; ?>",
"id": "<?php echo $row1["PACKAGE_NAME"]; ?>",
"cat": "UNIFI",
<?php
if ($rowcont1 == 0)
{
?>
"vas": "<?php echo "No default vas"; ?>"
<?php
}
else
{
?>
"vas": "<?php
while($rowvas1=mysqli_fetch_assoc($query1))
{
echo "$rowvas1[PACKAGE_NAME]\\n\\n"; //This is the line I want to chage (\\n no function for me)
}
?>"
<?php
}
?>
},
<?php
I have found many question same with me, but even I have tried all of the solutions, my code still didn't work
Try the following instead:
echo "$rowvas1[PACKAGE_NAME]<br>";
Instead of \n just add html line-break <br>.
Edit: If you are using the JS provided in the jsfiddle, be sure to change the following line:
$('#price-store').text(pricestore[$('option:selected', this).index()].price);
to(.text( to .html():
$('#price-store').html(pricestore[$('option:selected', this).index()].price);
Related
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>";
?>
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);
I can't find an API for Vine to get the page content's title, description and image. The JSON is in the body of the page itself in a script tag: . How do I get the content (the JSON) of this script tag using PHP so it can be parsed?
Vine page:
https://vine.co/v/igO3EbIXDlI
From page source
<script type="application/ld+json">
{
"#context": "http://schema.org",
"#type": "SocialMediaPosting",
"url": "https://vine.co/v/igO3EbIXDlI",
"datePublished": "2016-03-01T00:58:35",
"author": {
"#type": "Person",
"name": "MotorAddicts\u2122",
"image": "https://v.cdn.vine.co/r/avatars/39FEFED72B1242718633613316096_pic-r-1439261422661708f3e9755.jpg.jpg?versionId=LPjQUQ4KmTIPLu3iDbXw4FipgjEpC6fw",
"url": "https://vine.co/u/989736283540746240"
},
"articleBody": "Mmm... Black black blaaaaack!! \ud83d\ude0d ( Drift \u53d1 )",
"image": "https://v.cdn.vine.co/r/videos/98C3799A811316254965085667328_SW_WEBM_14567938452154dc600dbde.webm.jpg?versionId=wPuaQvDxnpwF7KjSGao21hoddooc3eCl",
"interactionCount": [{
"#type": "UserInteraction",
"userInteractionType": "http://schema.org/UserLikes",
"value": "1382"
}, {
"#type": "UserInteraction",
"userInteractionType": "http://schema.org/UserShares",
"value": "368"
}, {
"#type": "UserInteraction",
"userInteractionType": "http://schema.org/UserComments",
"value": "41"
}, {
"#type": "UserInteraction",
"userInteractionType": "http://schema.org/UserViews",
"value": "80575"
}],
"sharedContent": {
"#type": "VideoObject",
"name" : "Mmm... Black black blaaaaack!! \ud83d\ude0d ( Drift \u53d1 )",
"description" : "",
"thumbnailUrl" : "https://v.cdn.vine.co/r/videos/98C3799A811316254965085667328_SW_WEBM_14567938452154dc600dbde.webm.jpg?versionId=wPuaQvDxnpwF7KjSGao21hoddooc3eCl",
"uploadDate" : "2016-03-01T00:58:35",
"contentUrl" : "https://v.cdn.vine.co/r/videos_h264high/98C3799A811316254965085667328_SW_WEBM_14567938452154dc600dbde.mp4?versionId=w7ugLPYtj5LWeVUsXaH1bt2VuK8QE0qv",
"embedUrl" : "https://vine.co/v/igO3EbIXDlI/embed/simple",
"interactionCount" : "82366"
}
}
</script>
What to do after this?
$html = 'https://vine.co/v/igO3EbIXDlI';
$dom = new DOMDocument;
$dom->loadHTML($html);
When I go to that page, I don't see the script tag you are referencing. So I found a page that has one, and this is how I would do it:
<?php
$html = file_get_contents('https://tv-sewingcenter.com');
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTML($html);
$jsons = array();
$scripts = $dom->getElementsByTagName('script');
if( ! empty( $scripts ) )
{
foreach( $scripts as $script )
{
if( $script->hasAttribute('type') && $script->getAttribute('type') == 'application/ld+json' )
{
$jsons[] = json_decode($script->nodeValue, true);
}
}
if( ! empty( $jsons ) )
{
foreach( $jsons as $json )
{
echo '<pre>';
print_r( $json );
echo '</pre>';
}
}
}
I want to ask how to the repeat a region in javascript?
The data are dynamic and I want to find all items through php do...while loop:
<script type="text/javascript">
window.onload = function () {
<?php do{ ?>
var chart<?php echo $row_RecAllAnswers['q_id']; ?> = new CanvasJS.Chart("<?php echo $row_RecAllAnswers['q_id']; ?>", {
theme: "theme2",//theme1
title:{
text: "No. " + "<?php echo $row_RecAllAnswers['q_id']; ?>"
},
animationEnabled: true, // change to true
data: [
{
// Change type to "bar", "splineArea", "area", "spline", "pie",etc.
type: "column",
dataPoints: [
{ label: "A" , y: <?php echo $row_RecAllAnswers['A']; ?> },
{ label: "B", y: <?php echo $row_RecAllAnswers['B']; ?> },
{ label: "C", y: <?php echo $row_RecAllAnswers['C']; ?> },
{ label: "D", y: <?php echo $row_RecAllAnswers['D']; ?> }
]
}
]
});
chart<?php echo $row_RecAllAnswers['q_id']; ?>.render();
chart<?php echo $row_RecAllAnswers['q_id']; ?> = {};
window.alert(<?php echo $row_RecAllAnswers['q_id']; ?>);
<?php } while ($row_RecAllAnswers = mysql_fetch_assoc($RecAllAnswers)); ?>
}
</script>
Use json_encode to convert your mysql query result to JSON.
Write the JSON to your HTML.
In Javascript use a foreach on the JSON array to iterate.
json encode that php array into a javascript variable and then loop through that variable. In twig I do it like this:
var objectName = {{ phpVariable|json_encode|raw }};
so I think this should work find in PHP (did not test it):
var objectName = <?php echo json_encode($phpVariable); ?>;
Then the javascript variable 'objectName' will contain your data and now you can use regular javascript to loop through the data. You can also use underscore as it is easier.
_.each(objectName, function(item, key){
//do stuff here
});
So I am trying to use this plugin: http://w3widgets.com/responsive-calendar/
And the way the calendar is initialized and have events added is like so:
<script>
<?php $today = date('Y-m'); ?>
$( document ).ready( function() {
$(".responsive-calendar").responsiveCalendar({
time: '<?php echo $today; ?>',
events: {
"2014-04-30": {"number": 1, "badgeClass": "badge-warning", "url": "http://w3widgets.com/responsive-calendar"},
"2013-04-26": {"number": 1, "badgeClass": "badge-warning", "url": "http://w3widgets.com"},
"2013-05-03": {"number": 1, "badgeClass": "badge-error"},
"2013-06-12": {}}
});
});
</script>
I want to generate the events with a foreach because the events are all stored in a database. I tried to do the following:
events: {
<?php foreach($events as $event): ?>
"<?php echo $event->date; ?>"...
But I get an error that says the ) in the ($events as $event) is unexpected.
How can I do this, I must be able to or the calendar has to disappear. Plain and simple.
UPDATE
If I var_dump() the $events I get the following string (shortened to the first event!)
array(3) { [0]=> object(stdClass)#21 (5) { ["id"]=> string(1) "1" ["name"]=> string(17) "State Large Group" ["school"]=> string(9) "NHS Bands" ["date"]=> string(9) "4-16-2014" ["showHome"]=> string(1) "1" }...
And If I events: <?php echo json_encode($events); ?> it doesn't encode in the correct order. It does:
events: [{"id":"1","name":"State Large Group","school":"NHS Bands","date":"4-16-2014","showHome":"1"},{"id":"2","name":"State Solo\/Ensemble","school":"NHS Bands","date":"4-26-2014","showHome":"1"},{"id":"3","name":"League Music Festival","school":"RVMS Bands","date":"4-29-2014","showHome":"1"}] });
When it needs to be something like:
"2013-06-12": {}
events: <?php echo json_encode($events) ?>
You can convert your database result to json and pass it to events.
JSON encode MySQL results