I'm parsing a webpage with Jsoup which so far is going good, except that when I parse, I get the data that's the 'default text', the text displayed right before a javascript changes the value.
There's
<span id="p1name" class="redtext">Player 1</span>
which I can parse with
Element player1Div = doc.getElementById("p1name");
p1name = player1Div.text();
player1.setText(p1name);
Then there's a script on the website
<script>
$(document).ready(function() {
getData();
});
function getData() {
$.ajax({
type: 'get',
url: '../data.json',
data: '',
dataType: "json",
success: function(data) {
player1name = data['p1name'];
$("#p1name").text(player1name);
</script>
which changes the element's text. So I thought I could just run the java code again and get the new text, but that won't work as I keep getting "Player 1" (whereas I'm sure it should display a different string)
What are my options? How do I solve this?
JSoup can't solve your problem. All Jsoup knows is parse and extract the data.
As the desired text is not part of the html during the parsing it can't be extracted from the Document
All you can do is, issue a new request to ../data.json and fetch the data. Provided, you know that url before fetching the content.
Related
I have one scenario i.e., need to compare the values from Website with Database(MS Sql Table Values)
In my website having one datatable which is dynamic and the values changed based on Username.
I need to check whether the values present in datatable(website) should match with the Database.
Kindly let me know any ideas and code snippet for this.
You can use Javascript/Jquery that when a user change a value in datatable send a Ajax asyncron request to the java server and here check the values.
For example:
$( ".target" ).change(function() {
$.ajax({
type: 'POST',
url: 'myUrl',
data: JSON.stringify(myValues),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
})
});
Possibly I would load the data from MySQL -> Put it in Some POJO that mimics my datatable -> And preValidate the data -> put it in datatable.
Please put out some code which you have tried already.
I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>
Is there a way to send ajax requests in a Java program? I was thinking that there might be a jquery library somewhere, but I don't even know if jquery would be something that I should use. I'm trying to get the data from a certain request from a website as shown in this function:
function searchFraze(fraze, page) {
page = typeof page !== 'undefined' ? page : 1;
$.ajax({
url: 'ajax/tradeCsRight.php',
type: 'POST',
data: "search=1&type=10&fraze="+fraze+"&page="+page,
success: function(data) {
$("#itemlist").html(data);
}
});
}
Basically, I want to POST custom data in the data field above to the website (http://csgolounge.com/). Honestly, I don't even know if I should be doing what I'm doing this way, or if I should use some other method.
Also, in FireBug, I can see the contents of the tradeCsRight.php file as seen here (which is my goal, to see the html content of this): http://i.imgur.com/8ACnGbp.png
If I open the actual file in chrome, however, the page and html is blank (http://i.imgur.com/LHtKyUb.png). Can someone tell me why this is?
I am new to web development. My job is to get data from the server and plot them using amcharts every 1 or 2 seconds.
This is what i have so far:
<form id="getdata" role="form" method="post" action=#routes.DataApplication.get_data()>
<input type="text" name="device" id="device">
<input type="text" name="type" id="type">
<button id = "submit" type="submit">Submit</button>
</form>
Once I enter device and type and click the submit button, it will run the Java method get_data(). The method will search the database and return data that matches the device name, but the thing is it will display is the data in another page, for example www.somepage/getdata. The above html is in www.somepage/data page.
I tried using jquery .post() but the thing is it requires an url, I tried passing /getdata to it but didn't work.
My question is: is there a way to save the data we get from the #routes.DataApplication.get_data() action without reloading the page?
By the way, I am using play framework to develop the webpage.
UPDATE
Ok, making some progresses now, I tried using ajax post, but the data return (in console) is like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
Here I got 11 objects. If i don't use ajax post (using the original post form method), I get 11 data points too.
Here is my code:
<script>
$('#driver').click(function(evt) {
var dataabc = $('form').serialize();
console.log(dataabc);
$('#errors').hide();
$.ajax({
type : 'POST',
data : dataabc,
url : '#routes.DataApplication.get_data()',
success : function(data) {
alert("good");
console.log(data);
},
error : function(result) {
setError('Make call failed');
}
});
return false;
});
</script>
What get_data() does is just take the user input data (which is the form) and get corresponding data from the database and return ok(node);. This node is JsonNode
Any help would be appreciated..
Since you are getting an array of objects back in javascript and it is stored in data. You can loop through it and display the content is some div tag.
Example:
Create an empty div to populate the data after a successful ajax call.
<div id="mytextarea"></div>
Then in your ajax success, instead of printing to console you would loop through the array and append the data to the innerHTML of the div tag like so...
var myTextArea = document.getElementById('mytextarea');
for (var x = 0; x < data.length; x++){
myTextArea.innerHTML = myTextArea.innerHTML + data[x].id + '<br/>';
}
Edit 1: I see you know your object's attributes so I updated the code to append just id to the text area.
It will be very helpful to tell us what exactly the url returns in response. Usually that should be XML or JSON.
You can use FireBug or any other developer tools to catch the response and post it here.
IT doesn't decide what to return - it's YOU!
If you'll return for an instance JSON object in your get_data() action, your AJAX will receive a JSON, check yourself:
public static Result get_data(){
ObjectNode node = Json.newObject();
node.put("hello", "world");
return ok(node);
}
I am using Dojo library. How can I replace all the content of my jsp/html content. I am trying to dynamically reload my page when a data is updated.
Here is my dojo code:
function reloadPage() {
var thisUrl = '/CBS/a/customer/' + customerId + '/profile';
dojo.xhrGet({
url: thisUrl,
load: function (data) {
document.body.innerHTML = data;
},
error: function (data, ioArgs){
document.body.innerHTML = "unknown error";
}
});
}
The server returns a complete html code including the html tags. The data variable holds all the html tags. In my code I did document.body.innerHTML = data;which is wrong because the content of body is replaced by a whole html page. It looks like ajax is working because its updated dynamically but my buttons are not working anymore. Please help.
Why do you use AJAX if you want to update the whole page? Purpose of using of AJAX - update part of content(page), not updating the whole page. If you want to update the whole page, may be it will be more appropriate to use reload?