I'm using XMLHttpRequest to pull down the HTML from a specified URL, then stored it in fshtml. I then used:
function showInWindow(fshtml) {
var newWindow = window.open();
newWindow.document.write(fshtml);
}
To display all the HTML in a new window. But the HTML does not contain any of the code from the AJAX table in the middle of the page, which is what I want to access. Is there a way to use XMLHttpRequest to include the static version of the AJAX table HTML in xhr.responseText?
EDIT: This code pulls down html from the website:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.flashscore.com/basketball/", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
return showInWindow(xhr.responseText);
}
}
xhr.send();
The new window had HTML for all the headers and tabs and such, but there didn't appear to be any table data. Hope this helps.
Related
Goal: load more rows from the database to a view using an ajax request when a user clicks the "load more" button. I would like the data to load without a page reload.
Problem: The data being loaded via ajax keeps repeating the same rows on every request and doesn't paginate as per standard request.
Detail: I have a view that loads 4 rows from the database which I paginate using Laravel's built-in pagination. I've added an event listener on a "load more" button which successfully sends the request to the controller, which in turn successfully returns data. The controller returns a partial view of the data I want to display. However this data doesn't seem to increment properly and keeps repeating the records shown on each request. I am not sure what I am missing here, if the problem is in the controller or in the JS?
I am not very experienced with Laravel, PHP and JS since coming from more of a web designer and UI design background and would love to really understand what I am doing wrong here.
PLEASE NO JQUERY EXAMPLES.
Partial view:
#foreach ($products as $product)
<div style="background-color:pink; width: 200px;">
<p>{{ $product->title }}</p>
<img src="/images/product/{{ $product->img }}" alt="{{ $product->title }}" style="width: 50px;">
</div>
#endforeach
Javascript:
(I am updating the button href attribute so the request URL reflects the correct query)
const container = document.querySelector('#sandbox-container');
let button = document.getElementById('load-stuff');
let url = button.getAttribute('href'); // http://127.0.0.1:8000/sandbox?page=2
let pageNum = button.getAttribute('href').substr(35,1);
button.addEventListener('click', (event) => {
event.preventDefault();
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
// if page loads successfully, replace the number at the end of the url with the incremented page number
pageNum++;
newUrl = url.replace(/page=([^d]*)/, `page=${pageNum}`);
button.setAttribute('href', newUrl);
xhr.onload = function() {
if (xhr.status === 200) {
container.insertAdjacentHTML('beforeend', xhr.responseText);
}
else {
console.log(`Request failed, this is the response: ${xhr.responseText}`);
}
};
xhr.send();
})
Controller:
public function sandbox(Request $request)
{
$products = Product::orderBy('title', 'asc')->paginate(4);
if($request->expectsJson()){
return view('sandbox-more', compact('products'));
} else {
return view('sandbox', compact('products'));
}
}
Consider this snippet for your javascript
const container = document.querySelector('#sandbox-container');
let button = document.getElementById('load-stuff');
button.addEventListener('click', (event) => {
event.preventDefault();
const xhr = new XMLHttpRequest();
let url = button.getAttribute('href');
let pageNum = button.getAttribute('data-page-number') || 0;
xhr.open('GET', url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
// if page loads successfully, replace the number at the end of the url with the incremented page number
pageNum++;
newUrl = url + '?page=' + pageNum;
xhr.onload = function() {
if (xhr.status === 200) {
container.insertAdjacentHTML('beforeend', xhr.responseText);
button.setAttribute('data-page-number', pageNum);
}
else {
console.log(`Request failed, this is the response: ${xhr.responseText}`);
}
};
xhr.send();
})
What I've done here is to have the page number saved to a dedicated custom attribute "data-page-number". Doing "button.getAttribute('href').substr(35,1)" is inefficient. And then check the page number and increment it on the button's click event. Also, only update the "data-page-number" attribute when the request has been successful. I hope this helps
You should regenerate the pagination every time you make a request to get the correct data. Here is a very good example on doing it via jQuery. Should just adjust it to your needs since you are using pure Javascript.
I'm recently working on a website project. Therefor I have a website.php with all html code, a function.php and saveArray.js . In website.php I'm printing a html table with a button at the bottom. Through the button click I'm getting to the saveArray.js, where I save all the table data in an array.
With this code
var arrString = JSON.stringify(tableData);
var request = new XMLHttpRequest();
request.open('post', 'function.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-
urlencoded');
request.send('daten=' + arrString);
I post the JS array to function.php. In function.php I do something with the array and in an if statement I want to show a modal.
The modal itself works, but I want to show it on website.php page. Which doesn't happends, because I'm currently on function.php .
How can I solve this ?
EDIT: In my array is an ID and I want to check if this ID is already in my database or not. Depending on this result I want to show the modal and upload the data if necessary. All the checking is happening in function.php
I suppose you want to inject the string returned (the modal PHP code) by your function in function.php in your current page ('website.php').
To do this, you'll have to inject the response given by the XMLHttpRequest when the request is finished.
Let's suppose we want to add all the contents within
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
See, You are not handling the response of the request.So handle the response.and restuern the status of the request from function.php and if data is saved the open the model. You need not go to the function.php page. See the code
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is response of the request //now check it
//Suppose you returned " data saved" as response from function.php
if(this.responseText='data saved'){
//Open model here
}
}
};
xhttp.open("POST", "function.php", true);
xhttp.send();
I am loading my table on document.ready() from a json file as follows
document load....
$(document).ready(function () {
getSummaryData(function (data1) {
var dataarray=new Array();
dataarray.push(data1);
$('#summaryTable').DataTable({
data: dataarray,
"columns": [
---
---
and retrieving the data from a file as follows
function getSummaryData(cb_func1) {
$.ajax({
url: "data/summary.json",
success: cb_func1
});
console.log(cb_func1)
}
This was essentially loading dummy data so i could I could figure out how to load the table correctly etc. This works fine.
It does following
1. page loads
2. reads data from file
3. populates table
In reality, the data will not be loaded from file but will be returned from xhr response but I am unable to figure out
how to wire it all together. The use case is
POST a file via XMLHttpRequest
Get response
populate table (same data format as file)
I will post the file as follows...
<script>
var form = document.getElementById('form');
var fileSelect = document.getElementById('select');
var uploadButton = document.getElementById('upload');
---
form.onsubmit = function(event) {
event.preventDefault();
---
---
var xhr = new XMLHttpRequest();
// Open the connection.
xhr.open('POST', 'localhost/uploader', true);
// handler on response
xhr.onload = function () {
if (xhr.status === 200) {
console.log("resp: "+xhr);
console.log("resptxt: "+xhr.responseText);
//somehow load table with xhr.responseText
} else {
alert('ooops');
}
};
// Send the Data.
xhr.send(formData);
So ideally I need one empty row in the table or similar until someone uploads a file and then the table gets populated with the response.
Any help much appreciated.
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "youruploadserver.com/whatever", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
console.log(this.responseText);
dostuff = this.responseText;
};//end onreadystate
xhr1.send();
It looks mostly correct, You want the this.readyState == 4 in there. what is your question, how to populate a table from the response?
That also depends on how you are going to send the data and how the server is going to parse the data, looks like you want to use a json format which is smart. JSON.stringify(formdata) before you send it and then make sure your server parses it as a json object Using body-parser depending on what server you are using. and then you JSON.stringify() the object to send it back.
The javascript code will be launched from www.example.com through the url bar in google chrome so i cannot make use of jquery. My goal is to pass the full html source code of www.example.com/page.html to a variable in javascript when i launch the code in www.example.com. Is this possible? If so how? I know to get the current page source it's just document.documentElement.outerHTML but i'm not sure how i'd do this. I think it's possible by using responseText somewhere in the following code:
http.send(params);
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://www.example.com/page.html",true);
xmlhttp.send();
data = ""
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
data = xhr.responseText
}
}
xhr.send();
function process(){
url = "http://www.example.com/page.html"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4){
alert(xhr.responseText)
}
}
xhr.send();
}
this is how i run script from the address bar.. I do it all the time..
i create a bookmark like this
javascript:script=document.createElement('script');script.src='http://10.0.0.11/clear.js';document.getElementsByTagName('head')[0].appendChild(script); void(sss=1);
then i host the js file on my computer.. i use analogx simpleserver... then you can use a full page for your script
This happens in all tested browsers (Chrome, Firefox, Opera ...)
Some HTML entities are are swallowed and not displayed when retrieved from ajax. The same HTML entity is displayed when it is hardcoded in the HTML source file.
Here is the actual output: (the entity is not display nether in the web page nor in the console)
Here is the expected output:
Here is the javascript that retrieves the entity:
<html><head><script type="text/javascript"> function injectEntity(){ var xhr = new XMLHttpRequest(); xhr.open("POST", "entity.php", true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ var doc = xhr.responseXML; console.log(xhr.responseText); var div = document.getElementById("container"); div.appendChild(doc.getElementById("the-entity")); } } xhr.send(null); }</script></head><body> inject the following entity: <div id="container"> </div></body></html>
And here is the php file that is used to retrieve the entity:
<?phpheader('Content-type: application/xml; charset=UTF-8');$xml = new DOMDocument('1.0', 'utf-8');$tag = $xml->createElement('b','');$tag->setAttribute("id","the-entity");$xml->appendChild($tag);echo $xml->saveXML();?>
You want ’, not (which is an unprintable control character)