How to access an html content json object via URL [closed] - html

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
So for example, if my URL is www.someurlsomewhere.com/GetItemById?Id=5 and my response is an array of json objects.
Success: true
Html: "<html><body>test</body></html>"
FileName: "test.html"
How do I say www.someurlsomewhere.com/GetItemById?Id=5?data=Html to make it act like a link to the Html part of my json object within response.

You are talking about Query Parameters or URL Parameters. The correct format for adding multiple parameters is separating them with &. Your URL would look similar to: www.someurlsomewhere.com/GetItemByID?Id=5&src=html.
To extract that information, you would need to parse the URL parameters and then serve up the information that you want based on the data. This can be done server side or client side. Look up URL Parameter Parsing to get ideas on how to do it in the language of your choice. One of the examples that comes up in JavaScript is How can I get query string values in JavaScript?.
After you've parsed the URL parameter out that you want, now you need to render it to the page. Look up Parsing HTML. I'm going to assume you're doing it in javascript, just to give you an example of parsing:
var data = {
success: true,
html: "<html><body>test</body></html>",
filename: "test.html"
}
var el = document.createElement('html'); //creates a temporary dummy element to append to the page... although if you already have something on the page, you may use that container
el.innerHTML = data.html; //here you're selecting the element and adding a string of HTML to it
There are a lot of unknowns about what you're asking. But here is a potential client side solution that retrieves the URL parameter then passes it as HTML to the DOM.
<script>
//Assuming your URL looks like this:
// www.someurlsomewhere.com/GetItemByID?Id=5&src=html
function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var src = getParameterByName('src'); //Use your parameter function to retrieve the src parameter from the URL. Currently src = 'html'
//This is a representation of your JSON payload that you're receiving from somewhere
var data = {
success: true,
html: "<html><body>test</body></html>",
filename: "test.html"
}
var el = document.createElement('html'); //creates a temporary dummy element to append to the page... although if you already have something on the page, you may use that container
el.innerHTML = data[src]; //here you're selecting the element and adding a string of HTML to it. This would translate to data.html
</script>

Related

How to get clean json from wikipedia API

I want to get the result from a wikipedia page https://en.wikipedia.org/wiki/February_2 as JSON.
I tried using their API: https://en.wikipedia.org/w/api.php?action=parse&page=February_19&prop=text&formatversion=2&format=json
Though it is giving it as Json format. The content is HTML. I want only the content.
I need a way to get clean result.
If you want plain text without markup, you have first to parse the JSON object and then extract the text from the HTML code:
function htmlToText(html) {
let tempDiv = document.createElement("div");
tempDiv.innerHTML = html;
return tempDiv.textContent || tempDiv.innerText || "";
}
const url = 'https://en.wikipedia.org/w/api.php?action=parse&page=February_19&prop=text&format=json&formatversion=2&origin=*';
$.getJSON(url, function(data) {
const html = data['parse']['text'];
const plainText = htmlToText(html);
const array = [...plainText.matchAll(/^\d{4} *–.*/gm)].map(x=>x[0]);
console.log(array);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Update: I edited the code above according to the comment below. Now the function extracts all the list items putting them into an array.
I guess by clean you mean the source wikitext. In that case you can use the revisions module:
https://en.wikipedia.org/w/api.php?action=query&titles=February_2&prop=revisions&rvprop=content&formatversion=2&format=json
See API:Get the contents of a page and API:Revisions for more info.

Can I get HTML id from HTML code written in JSON String in IBM WATSON [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have written HTML code inside a JSON object as a string, is there a way in which i can access the HTML id from there.
{
"text":"<ol><li id='it_1'>Item1</li><li id='it_2'>Item2</li><li id='it_3'>Item3</li></ol>"
}
I want that whenever user is clicking any link in the inner list, i should get the id of it. In this scenario i have defined this case in IBM Watson, now my motive is whenever user is clicking any of the links i need to trigger another case. But for that i need to check which one did he choose.
You can use DOMParser(), querySelectorAll() and map() like the following way:
var json = {
"text":"<ol><li id='it_1'>Item1</li><li id='it_2'>Item2</li><li id='it_3'>Item3</li></ol>"
}
var doc = new DOMParser().parseFromString(json.text, "text/html");
var ids = [...doc.querySelectorAll('li')].map(el => el.id);
console.log(ids);
You first need to add that list elements into the DOM
Then you need to attach click event listeners to each of the <li> elements
Using that listener you can access the id and other attributes of that element
var obj = {
"text": "<ol><li id='it_1'>Item1</li><li id='it_2'>Item2</li><li id='it_3'>Item3</li></ol>"
};
document.getElementById('container').innerHTML = obj.text;
var liElems = document.querySelectorAll('ol li');
for(var i=0; i<liElems.length; i++){
liElems[i].addEventListener('click', function(e){
console.log(e.target.id);
});
}
<div id="container"></div>

How does text url parameter work? [duplicate]

This question already has answers here:
Backbone router with multiple parameters
(2 answers)
Closed 6 years ago.
PLEASE INVEST SOME TIME READING THE QUESTION COMPLETELY BEFORE MARKING OR ANSWERING
I want to display text from data in url and access it using the same. Eg.
http://stackoverflow.com/questions/24888693/how-does-out-parameter-work
Notice how this page is accessed using the param how-does-out-parameter-work
Currently i am using requireJs with backboneJs in my web app. So, in my router i am routing like
siteTitle = 'Boiler Plate';
define([
'jquery',
'underscore',
'backbone',
'handlebars',
'jcookie',
'views/home',
'views/404'
], function ($, _, Backbone, Handlebars, jcookie, HomePage, FoFPage) {
var AppRouter = Backbone.Router.extend({
routes: {
':*':'home',
'home' : 'home',
'home/:a' : 'home',
'*whatever' : '404'
},
home: function (a) {
document.title = siteTitle + ' - Home';
homePage = new HomePage({route: a});
homePage.render();
},
404: function(){
document.title = siteTitle + ' - 404';
fofPage = new FoFPage;
fofPage.render();
}
});
var initialize = function () {
var app_router = new AppRouter;
Backbone.history.start();
};
return {
initialize: initialize,
AppRouter: AppRouter
}
});
Notice that i am getting the passed parameter a and them loading the page accordingly. Currently i am setting that parameter a as a number that is my post ID and using it accordingly. Bu if i want to pass a portion of my post's heading and access it how can i do that?
I can think of one way is selecting substring from mysql data base and based on url input but it wont help as if the parameter is how-does-out-parameter-work i can never parse it as How does 'out' (parameter) work? which is actual text in database. What am i missing?
UPDATE
the ignoring the post param is only applicable in stackvoerflow not on this site
https://www.theguardian.com/us-news/2016/nov/10/hate-crime-spike-us-donald-trump-president is using something else. What am i missing?
If you're attempting to follow the same process as Stackoverflow, they appear to use an Id for each question. I can only speculate what the title parameter is used for.
http://stackoverflow.com/questions/24888693/how-does-out-parameter-work
Equates to the following:
{domain}/{questions}/{questionId}/{title-string}
You can see that the title-string is an option parameter as the following will still route you to the correct question
http://stackoverflow.com/questions/24888693
The additional parameter is likely to stop duplicate Ids causing an issue in the database if the question Id counter has to be reset.
Maybe you can clarify why you need to search for a hypenated string in the databse?

JSON results into a variable and store in hidden input field

I wrote code below that is working perfectly for displaying the results of my sales tax calculation into a span tag. But, I am not understanding how to change the "total" value into a variable that I can work with.
<script type="text/javascript">
function doStateTax(){
var grandtotalX = $('#GRANDtotalprice').val();
var statetaxX = $('#ddl').val();
$.post('statetax.php',
{statetaxX:statetaxX, grandtotalX:grandtotalX},
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
// ...
});
return false;
};
</script>
Currently, $('.total-placeholder').html(data.total); is successfully placing the total number into here:
<span class="total-placeholder"></span>
but how would I make the (data.total) part become a variable? With help figuring this out, I can pass that variable into a hidden input field as a "value" and successfully give a proper total to Authorize.net
I tried this and id didn't work (see the testtotal part to see what I'm trying to accomplish)..
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
$testtotal = (data.total);
// ...
If you are using a hidden field inside a form, you could do:
//inside $.post -> success handler.
$('.total-placeholder').html(data.total);
$('input[name=yourHiddenFieldName]', yourForm).val(data.total);
This will now be submitted along with the usual submit. Or if you want to access the data elsewhere:
var dataValue = $('input[name=yourHiddenFieldName]', yourForm).val();
The "data" object you are calling can be used anywhere within the scope after you have a success call. Like this:
$.post('statetax.php',
{statetaxX:statetaxX, grandtotalX:grandtotalX},
function(data) {
data = $.parseJSON(data);
var total = data.total;
var tax = data.total * 0.19;
});
return false;
};
Whenever you get an object back always try to see with an alert() or console.log() what it is.
alert(data); // This would return <object> or <undefined> or <a_value> etc.
After that try to delve deeper (when not "undefined").
alert(data.total); // <a_value>?
If you want 'testotal' to be recognized outside the function scope, you need to define it outside the function, and then you can use it somewhere else:
var $testtotal;
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
$testtotal = (data.total);
EDIT:
The comments are becoming too long so i'll try and explain here:
variables defined in javascript cannot be accessed by PHP and vice versa, the only way PHP would know about your javascript variable is if you pass it that variable in an HTTP request (regular or ajax).
So if you want to pass the $testtotal variable to php you need to make an ajax request(or plain old HTTP request) and send the variable to the php script and then use $_GET/$_POST to retrieve it.
Hope that answers your question, if not then please edit your question so it'll be clearer.

jQuery - Parse Json then Display Data

I'm having a problem parsing valid Json from a Twitter List then displaying the list on the page.
Here is my code;
var url = "http://api.twitter.com/1/aplusk/lists/5676047/statuses.json&callback=?";
$.getJSON(url, function(data) {
var results = '';
$(data.results).each(function() {
results += "<p class='tweet_result' id='tweet" + this.id_str + "'><a href='http://twitter.com/" + this.user.screen_name + "' title='' class='tweet_user'></p>";
});
$(results).prependTo("#twitter_results");
});
If you put the url in to www.jslint.com you can view the structure of the json
I'm new to json so I could be doing something stupid here.
Thanks in advance for your help and advice.
The URL has to be:
http://api.twitter.com/1/aplusk/lists/5676047/statuses.json?callback=?
(Note the question mark instead of the ampersand)
Also see the returned object, it does'nt have a member "results", it's a native javascript-array.
You'll have to iterate over data itself:
$(data).each(function(i,item)
where you can access the properties inside via
item.someProperty