Can't use JSON string from PHP in casperjs - javascript

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

Related

How to retrieve data from json file

I am having trouble with accessing my json file from my javascript file. I would like to change the object to a different text in my json file once a submit button is clicked on the webpage. I am aware that I would use ajax to achieve this goal, but I do not know how to access the json file.
This is the db.json file
{
{
"assets": [
{
"id": "0946",
"manufacturer": "SONY",
},
{
"id": "0949",
"manufacturer": "AUDIOTECNIA"
}
],
"transfers": [
{
"id": 1,
"status": "in-progress"
}
]
}
This is my Javascript file
$('form').on('submit', function(e){
e.preventDefault();
parsedData = JSON.parse(db.json);
console.log(parsedData[0].id)
//Changing Status
$.ajax({
type: "PATCH",
url: `http://localhost:3000/transfers/`
});
I've tried using parseData because I read that is how to retrieve the object, from the json file, but I do not believe I am writing it correctly. What documentation or steps would one recommend for solving this issue?
You have an extra comma after "in-progress",
const parsedData = JSON.parse(`{
"transfers": [ {
"id": 1,
"status": "in-progress"
}]
}`)
Then, to access id in parsedData:
console.log(parsedData.transfers[0].id)
You did not initialize the variable parsedData.
var parsedData = JSON.parse(db.json);

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>";
?>

generate javascript code with php

I would like to dynamically generate the columns definition on a Datatable. The columns definitions are:
"columns": [
{ "data": "id", "orderable": false },
{ "data": "code" },
{ "data": "name" },
{ "data": "created", "render":
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
},
{ "data": "modified", "render":
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
}]
I tried generating the javascript code using an array of php objects and then json_encode it, like the following:
$formatted_cols = [];
foreach ($cols as $idx => $col){
$temp = [];
$temp['data'] = $col;
if(in_array($col, array('id', 'actions'))){
$temp['orderable'] = 'false';
}
if(in_array($col, array('created', 'modified'))){
$temp['render'] = "
function (data) {
var date = new Date(data);
return date.toLocaleString();
}
";
}
$formatted_cols[] = $temp;
}
And then I do the following in the place where the code would normally appear:
echo json_encode($formatted_cols);
But the code came out like this:
[
{
"data": "id",
"orderable": "false"
},
{
"data": "code"
},
{
"data": "name"
},
{
"data": "created",
"render": "\r\n function (data) {\r\n var date
= new Date(data);\r\n \r\n return
date.toLocaleString();\r\n }\r\n "
},
{
"data": "modified",
"render": "\r\n function (data) {\r\n var date
= new Date(data);\r\n \r\n return date.toLocaleString();\r\n }\r\n "
}
]
As you can see, with a bunch of \r\n and stuff. Anybody can help me get the desired output please?
Thanks in advance for any help
UPDATE
I removed the line breaks but still the functions are inside double quotes
{
"data": "modified",
"render": "function (data) {var date = new Date(data);return
date.toLocaleString();}"
}
How do I remove those quotes?
Try using nl2br(). It'll take away all those \r and \n
http://php.net/manual/es/function.nl2br.php
The \r\n "stuff" represents a carriage-return + linefeed combination, in other words a line break.
You're going to get these in the JSON data if you're trying to encode multi-line strings. JSON itself does not support multi-line strings without them like PHP does.
Remove your newlines, like this:
{ "data": "created", "render": "function (data) { var date = new Date(data); return date.toLocaleString(); }" },
But you'll still be left with a string, which isn't the sort of thing you should work with, even though you can convert it to a function in JS. It's pretty ugly. Even if it worked, it's not great to generate JS in PHP - try to find another method if you can. Let PHP serve only the data, and have JS integrate functionality into it, if possible.

The json file displays the wrong format

I'm using ajax to write json files. But the file display format is not correct.
AJAX:
$.ajax
({
type: "GET",
dataType : 'json',
contentType: "application/json",
async: false,
url: 'save_json.php',
data: {
data: JSON.stringify(data)
},
success: function () {alert("Thanks!"); },
failure: function() {alert("Error!");}
});
SAVE_JSON.PHP:
<?php
$myFile = "profile.json";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $_GET["data"];
fwrite($fh, $stringData);
fclose($fh)
?>
It shows the following:
{"profile":[{"no":1,"firstName":"C","lastName":"D","age":25,"sex":"M","country":"US","phoneNumber":"019878736729","email":"johnsmith#example.com"},{"no":2,"firstName":"A","lastName":"B","age":28,"sex":"M","country":"VN","phoneNumber":"84928374839","email":"nguyentam#example.com"}]}
But i want to display with correct format as follows:
{
"profile": [
{
"no": 1,
"firstName": "C",
"lastName": "D",
"age": 25,
"sex": "M",
"country": "US",
"phoneNumber": "019878736729",
"email": "johnsmith#example.com"
},
{
"no": 2,
"firstName": "A",
"lastName": "B",
"age": 28,
"sex": "M",
"country": "VN",
"phoneNumber": "84928374839",
"email": "nguyentam#example.com"
}
]
}
Can somebody help me?
Let's be clear about the two parts in this and what each part is doing.
Your JavaScript file is taking an object ("data") and turning it into a JSON string with the call to JSON.stringify(). It is then sending it to your PHP server.
Your PHP server is saving a string to the file. It isn't handling this string as a JSON string at all - it doesn't care.
You have a bunch of approaches how you can handle this. You can, for example, turn the string back into an object on the PHP side and dump out the formatted version:
$obj = json_decode($string_data,true);
$formatted_json = json_encode($obj, JSON_PRETTY_PRINT);
fwrite($fh, $formatted_json);
You could also do this formatting on the JavaScript side, replacing your call to JSON.stringify() with one with additional parameters:
JSON.stringify(data,null,4)
The null indicates that you're not going to use a replacer function, while the 4 is how many spaces to indent the pretty printing.
Which method you use is up to you and how much bandwidth you want to use (sending the formatted version takes up more space).
Keep in mind, however, that JSON parsers don't use this extra space - it is all formatting to help you (or some other human) read it.
(And #Quentin raises an excellent point in the comments to your question - using "GET" is a bad idea in this case for a lot of reasons. Switch to "PUT" or, at worst, "POST".)

display json data using xhrget (DOJO)

I am unable to figure out what is the problem with displaying json data..below is the code
var xhrGet1 = dojo.xhrGet({
url: "Page/",
handleAs: "json",
handle: function(response)
{
dojo.byId('json-data').innerHTML = response.questions[0];
}
});
Html
<div id='json-data'></div>
And my json file looks like this
{
"Info": {
"PURPOSE": ".... ",
},
"questions": [
{
"ID": 1,
"Question": "User ID",
"Information": "",
}, {
"ID": 2,
"Question": "Name",
"Information": "",
}
],
so on...any ideas??
The property handleAs : "json" in your xhr call makes the incoming json automatically eval'ed to javascript objects. So, you have to convert your javascript object back to string using JSON.stringify.
e.g. :
dojo.byId('json-data').innerHTML = JSON.stringify(response.questions[0]);
You can also use dojo.toJson for the same purpose. It uses json.stringify but has the benefit of having a second argument ("prettyprint"), allowing you to pretty-print out of the box, like this :
dojo.byId('json-data').innerHTML = dojo.toJson(response.questions[0], true);
wrap your JSON with PRE and CODE tags.
So:
dojo.byId('json-data').innerHTML = "<pre>code>" + response.questions[0] + "</code></pre>";
Also see: Display JSON as HTML for some libraries that can help you pretty-format your JSON when rendering in the browser

Categories