posting through json and jquery - javascript

I'm totally new to JSON format so this is probably a very generic question and I'm not even sure this is the right way to go.
What I would like to do is write a JSON file with some text in it, something like a list of conversations.
var conversations = [
one [{
"you":"Hello",
"him":"Hey there"
}],
two [{
"you":"Hello on this second one",
"him":"Hey there how are you"
}]
];
then, on pageload, load a random conversation on my php index (I can use jquery). What's important for me is sending the you/me content to some specific divs.
the use case would be: Page loads, picks randomly conversation one and renders this on my page
<div class="you">Hello</div>
<div class="him">Hey there</div>
Am I in any way in the good direction? any suggestions or resources I can study to have something like this working? Any hint or code is greatly appreciated :) thanks

Is that what you're looking for?
<div id="you"></div>
<div id="him"></div>
<script>
var conversations = [
{
you:"Hello",
him:"Hey there"
},
{
you:"Hello on this second one",
him:"Hey there how are you"
}
];
// random number from 0 to 1
var random = Math.floor((Math.random() * 2) );
var you = document.getElementById('you');
var him = document.getElementById('him');
you.innerHTML = conversations[random]['you'];
him.innerHTML = conversations[random]['him'];
</script>
https://jsfiddle.net/vjdkLcvq/

I am agree with you. I always prefer JSON instead of Database. Specially for a conversation project like yours. More readable, easy to edit etc.
here is the json file where I save text conversations.
messages.json
{
"1442831655": {
"writtenFrom": "tom",
"line1": "tom writing to jim."
}
action.php
$fileName = "./data/messages.json";
$str_data = file_get_contents($fileName);
$data = json_decode($str_data,true);
echo json_encode( $data );
index.php
...<script src="../public/js/jquery-2.0.3.min.js"></script>
<script src="ad.js"></script>...
ads.js
$(document).ready(function(){
showInbox(authUser);
});
Just sending you some ideas. The whole script is much more complex. (PHP, AJAX, JSON)

Related

Retrieved all information inside tags : DOMNODE

I have a script in which I have no control over the HTML and can only modify the basic CSS. I just wanted to know if it is possible to cut all the information from < script> until its closing </ script> without distinguishing between the elements inside?
First of all I use wp_remote_get (yes it is wordpress) :
$response = wp_remote_get("http:localhost/wp/?p={id}");
This is what response looks like:
array(6) { ["headers"]=> object(Requests_Utility_CaseInsensitiveDictionary)#6325 (1) { ["data":protected]=> array(6) { ["date"]=> string(29) "Fri, 04 Feb 2022 08:27:59 GMT" ["server"]=> string(141) "Apache/2.4.48 (Unix) OpenSSL/1.0.2u PHP/8.0.8 mod_wsgi/3.5 Python/2.7.13 mod_fastcgi/mod_fastcgi-SNAP-0910052141 mod_perl/2.0.11 Perl/v5.30.1" ["x-powered-by"]=> string(9) "PHP/8.0.8" ["x-pingback"]=> string(48) "http://localhost:8888/Sadem/wordpress/xmlrpc.php" ["link"]=> array(3) { [0]=> string(74) "; rel="https://api.w.org/"" [1]=> string(104) "; rel="alternate"; type="application/json"" [2]=> string(60) "; rel=shortlink" } ["content-type"]=> string(24) "text/html; charset=UTF-8" } } ["body"]=> string(49331) "
And the body ($response["body"]) contains a very simple html page:
Links with stylesheets
Tags html
Links with scripts
And the script :
$content = response['body'];
$document = new DOMDocument();
$document->loadHTML($content);
// An empty array to store all the 'scripts'
$scripts_array = [];
// Store every script's line inside the array
foreach ($document->getElementsByTagName('script') as $script)
{
if ($script->hasAttribute('src')) {
$scripts_array[] = $script->getAttribute('src');
}
}
Then for you to understand I return the array of all my scripts that I transmit.
I get the array via an api.
Today with my script above I get this:
"more_info":{
"http://localhost/wp/wp-content/plugins/elementor/assets/lib/font-awesome/js/v4-shims.min.js",
"http://localhost/wp/wp-includes/js/comment-reply.min.js',
[...]
}
But I would like to be able to get this:
"more_info":{
"<script src='http://localhost/wp/wp-content/plugins/elementor/assets/lib/font-awesome/js/v4-shims.min.js'id='font-awesome-4-shim-js'></script>",
"<script src='http://localhost/wp/wordpress/wp-includes/js/comment-reply.min.js'id='comment-reply-js'></script>",
[...]
}
If you haven't understood yet, I'm browsing a page and I want to get all the lines and I want to put them in an array.
I hope it's clearer for you,
Thank you for your answers ! :)
You are getting only the src attribute value, because that's all you are asking for in $script->getAttribute('src'). Replace your foreach with:
$xpath = new DomXPath($document);
$attribs = $xpath ->query("//script/#*");
foreach ($attribs as $attrib) {
$scripts_array[] = $attrib->nodeValue ;
}
and see if it works.
first of all thank you for your answer! I tried, and I don't get what I want. When I do a query I get this:
"more_info": [
"http://localhost:8888/Sadem/wordpress/wp-content/plugins/elementor/assets/lib/font-awesome/js/v4-shims.min.js?ver=3.5.5",
"font-awesome-4-shim-js",
...and more
]
What I was looking for was having the complete line like this:
"more_info": [
"http://localhost/.../assets/lib/font-awesome/js/v4-shims.min.js",
"font-awesome-4-shim-js",
...and more
]
What I was looking for was having the complete line like this:
"more_info": [
"<script src='http://localhost/.../assets/lib/font-
awesome/js/v4-shims.min.js' id='font-awesome-4-shim-js'></script>",
...and more
]
But I thank you again for your help, so few people want to help me....

"Manipulate" html files (server-side) and insert their content in main html page (*without* PHP)

Context : I'm working on a site that runs on my university's server (IIS, not Apache), no way to use PHP.
I want the site to be so simple that people with very little HTML/CSS/js knowledge can put new content when I'll be done with it. I'm a grad student in health sciences and I've learned HTML, CSS, etc. by myself since a few years (so I'm definitely not a pro), so pardon me if my question is a little naive.
I'd really need some script/tool that would allow me to :
Get content from an external file (blog post) on the server (let's say a list of ".html" files located in a folder on the server, let's say the folder "/blog-posts/", containing a bunch of files named "jan-15.html", "feb-15.html", etc.)
Pick the last 4 files (4 most recent)
Insert this content at a precise point in a html file
(Optional, but it would really be nice) Pull the date the file was last edited, put it in a string and insert said string before the blog post, in the home page
So :
Do anyone know if anything like this already exists ?
If not, do you guys think it's possible with some js/jQuery to "manipulate" external files like that ?
If it's possible, any hints how :) ?
Thanks a million times, I know I'm asking a lot, but I've been searching for a viable solution for this for the last few months... It's my first time writing here but I've been an avid reader since a very long time.
Have a great day !
You can store a simple blog configuration as a JSON object and update it as you add new posts. Let's say you have the files jan.html and feb.html in your blog-posts folder.
Now in the main folder, create a file content.json as follows this:
{
"posts": [
{ "uri": "feb.html", "date": "2/12/15" },
{ "uri": "jan.html", "date": "1/3/15" }
]
}
Now you can get the blog content with AJAX requests from JavaScript. Example:
<script>
function Init(posts)
{
var e = document.getElementById('content');
var s = '';
posts.forEach(function(post)
{
console.log(post.content);
s += '<div><h2>Date: ' + post.date + '</h2><p>' + post.content + '</p></div>';
});
e.innerHTML = s;
}
function LoadContent(config)
{
var remain = config.posts.length;
var posts = [];
config.posts.forEach(function(post)
{
var req = new XMLHttpRequest();
req.open('GET', 'blog-posts/' + post.uri, true);
req.onload = function()
{
remain--;
posts.push({ content: req.responseText, date: post.date });
if(remain === 0)
{
Init(posts);
}
};
req.send(null);
});
}
function LoadConfig()
{
var req = new XMLHttpRequest();
req.open('GET', 'content.json', true);
req.onload = function()
{
LoadContent(JSON.parse(req.responseText));
};
req.send(null);
}
window.addEventListener('load', LoadConfig);
</script>
<div id="content"></div>

How to use explode function to delimit and display different values

I’m making a random sentence generator for my English class. I’m close but because of my limited php and javascript knowledge I need to ask for help. I’m not bad at reading the code, I just get stuck writing it.
I want to use explode to break up a string of comma seperated values. The string is a mix of English and Spanish, on the .txt file they would seperated like:
The book, El libro
The man, El hombre
The woman, La mujer
etc.
I would like to break these two values into an array and display them in separate places on my web page.
I`m going to use a random text generator script that I found, it’s working great with no problems. I just need to modify it using explode to read, separate the values into an array, and be able to display the separate values of the array.
<?php
/* File, where the random text/quotes are stored one per line */
$settings['text_from_file'] = 'quotes.txt';
/*
How to display the text?
0 = raw mode: print the text as it is, when using RanTex as an include
1 = Javascript mode: when using Javascript to display the quote
*/
$settings['display_type'] = 1;
/* Allow on-the-fly settings override? 0 = NO, 1 = YES */
$settings['allow_otf'] = 1;
// Override type?
if ($settings['allow_otf'] && isset($_GET['type']))
{
$type = intval($_GET['type']);
}
else
{
$type = $settings['display_type'];
}
// Get a list of all text options
if ($settings['text_from_file'])
{
$settings['quotes'] = file($settings['text_from_file']);
}
// If we have any text choose a random one, otherwise show 'No text to choose from'
if (count($settings['quotes']))
{
$txt = $settings['quotes'][array_rand($settings['quotes'])];
}
else
{
$txt = 'No text to choose from';
}
// Output the image according to the selected type
if ($type)
{
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
// Set the correct MIME type
header("Content-type: text/javascript");
// Print the Javascript code
echo 'document.write(\''.addslashes($txt).'\')';
}
else
{
echo $txt;
}
?>
The script that displays the result:
<script type="text/javascript" src="rantex.php?type=1"></script>
Can someone please help me modify the rantex.php file so that I can use explode to separate the different comma separated values, and use a different script to call them in different places on my web page?
Thank you, and please excuse my noobness.
The following seems unnecessary, since file() will have already removed new line characters:
// New lines will break Javascript, remove any and replace them with <br />
$txt = nl2br(trim($txt));
$txt = str_replace(array("\n","\r"),'',$txt);
To break your line, you may instead use:
list($english, $spanish) = explode(', ', trim($txt));
It seems you are trying to use PHP to serve a static page with some random sentences, right? So why not use PHP to serve valid JSON, and handle to display logic on the client?
Heres a quick implementation.
// Get the data from the text file
$source = file_get_contents('./quotes.txt', true);
// Build an array (break on every line break)
$sentences = explode("\n", $source);
// Filter out empty values (if there is any)
$filtered = array_filter($sentences, function($item) {
return $item !== "";
});
// Build a hashmap of the array
$pairs = array_map(function($item) {
return ['sentence' => $item];
}, $filtered);
// Encode the hashmap to JSON, and return this to the client.
$json = json_encode($pairs);
Now you can let the client handle the rest, with some basic JavaScript.
// Return a random sentence from your list.
var random = sentences[Math.floor(Math.random() * sentences.length)];
// Finally display it
random.sentence
[edit]
You can get the JSON data to client in many ways, but if you don't want to use something like Ajax, you could simply just dump the contents on your webpage, then use JavaScript to update the random sentence, from the global window object.
// Inside your php page
<p>English: <span id="english"></span></p>
<p>Spanish: <span id="spanish"></span></p>
<script>
var sentences = <?= json_encode($pairs); ?>;
var random = sentences[Math.floor(Math.random() * sentences.length)];
var elspa = document.getElementById('spanish');
var eleng = document.getElementById('english');
elspa.innerText = random.sentence.split(',')[1];
eleng.innerText = random.sentence.split(',')[0];
</script>
Ok, so I have this figured out, I take 0 credit because I paid someone to do it. Special thanks to #stormpat for sending me in the right direction, if not for him I wouldn't have looked at this from a JSON point of view.
The .PHP file is like so:
<?php
$f_contents = file('quotes.txt');
$line = trim($f_contents[rand(0, count($f_contents) - 1)]);
$data = explode(',', $line);
$data['eng'] = $data[0];
$data['esp'] = $data[1];
echo json_encode($data);
?>
On the .HTML page in the header:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
(function ($) {
$(function()
{
function load_random_data() {
$.get('random_line.php', function(data) {
var data = $.parseJSON(data);
$('#random_english').text(data.eng);
$('#random_spanish').text(data.esp);
});
}
load_random_data();
$('#get_random').click(function(e){
e.preventDefault();
load_random_data();
});
});
})(jQuery);
</script>
This splits the different variables into classes, so to call them into my html page I call them by their class, for instance I wanted to drop the variable into a table cell so I gave the individual td cell a class:
<td id="random_spanish"></td>
<td id="random_english"></td>
Plus as a bonus the coder threw in a nifty button to refresh the json classes:
<input type="button" value="Get random" id="get_random" />
So now I don`t have to have my students refresh the whole web page, they can just hit the button and refresh the random variables.
Thanks again everyone!

How can I create a custom function in PHP for HTML tags?

Last time I asked for help in PHP and I got great response. Thanks to all of you for that. Now I am learning and creating website using MVC PHP. I want to ask you that can I create a custom function to use html tags? I am trying to remember that where I saw an example of it. Actually I've seen it before in and open source project.
It was like something this:
htmltag(script(src=address, type=javascript))
Its output was in html like:
<script src="address" type="javascript"></script>
So can I create something like this? I am trying to do this way:
public function script($var1, $var2){
$var1 = array(
'type'=>'',
'charset' => '',
'src' => ''
);
$var2 = false;
print("<script $var1>$var2</script>");
}
So can anyone guide me with this? Do I need to create class first? I will be waiting for your reply friends.
Javascript works with DOM, see the reference
function htmltag(name,atts) {
var tag = document.createElement(name);
for(var i in atts) tag.setAttribute(i, atts[i]);
return tag;
}
var img = htmltag("img", {
src: "https://kevcom.com/images/linux/linux.logo.2gp.jpg",
alt: "linux logo"
});
document.body.appendChild(img);
Note that img here is object (XML Node), not just plain text, so you can attach events on it etc. If you want to extract just the plain html code from it, use img.outerHTML. Test it on the fiddle.
Note: print is the equivalent of Ctrl+P in the browser :-) it is not the print equivalent in PHP.
In PHP you can use DOM::createElement and other methods from DOM which are quite similar to those from javascript. Personaly I prefer something more simple:
function tag($name,$atts="",$content="") {
$str_atts = "";
if(is_array($atts)) {
foreach($atts as $key=>$val) if(!($val===null || $val===false)) $str_atts.= " $key=\"$val\"";
} else $str_atts = " ".preg_replace("/=(?!\")(\S+)/m","=\"\\1\"",$atts);
if($name=="img" && !strpos($str_atts,"alt=")) $str_atts.= " alt=\"\"";
if(in_array($name,array("input","img","col","br","hr","meta"))) $name.= "/";
if(substr($name,-1)=="/") { $name = substr($name,0,-1); return "<{$name}{$str_atts}/>"; }
else return "<{$name}{$str_atts}>$content</$name>";
}
Examples
echo tag("p","class=foo id=bar1","hello");
echo tag("p",'class="foo" id="bar2"',"hey");
echo tag("p",array("class"=>"foo","id"=>"bar3"),"heya");
echo tag("img","src=https://kevcom.com/images/linux/linux.logo.2gp.jpg");

jQuery $.post() using output data as selector

I am trying to build a quiz environment. The user selects an answer and then clicks submit. Upon submit, the following jquery is called:
$(document).ready(function() {
$('.btn-large').click(function() {
$.post("correct_quiz.php",
{
choices : $('input[name=choice][type=radio]:checked').serialize()
},
function(data) {
var temp = '#correct' + data;
var temp2 = '#correct3';
$(temp).show(); // Make the wrong/right icons visible
});
});
});
This jquery makes a green or red icon appear, based on whether the answer was correct or not. The correct_quiz.php script contains:
<?php
$root = "/users/stadius/maapc/public_html/";
include($root . "connect_to_database.php");
$choices = $_POST['choices']; // This will for example output "choice=3"
echo substr($choices,7,7); // This will then output "3"
?>
I ran into a problem, when I try the above jquery code with variable temp2 the script works like I want. But when I try it with variable temp it doesn't. When I debug, I see that they contain exactly the same string though: both are '#correct3' (when I choose the 3rd answer).
So why is this not working when I use variable temp, and is working when using temp2?
I think your problem is in this line:
echo substr($choices,7,7);
Try to use:
$list = explode('=', $choices);
echo $list[1];
instead of substr

Categories