How to change URL without load in JavaScript - javascript

I have a question How to change URL without load. I am working on a PHP, JavaScript project.
I am try to make without load Home page. in home Header section content some buttons like :-
Header
on click button than load data using XMLHttpRequest() and i want to change Url like:-
https://example.com/home to https://example.com/search
Code
var xmld = new XMLHttpRequest();
xmld.open("GET", "/Api/SearchPage", true);
xmld.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmld.onreadystatechange = function() {
if (xmld.readyState == 4 && xmld.status == 200) {
var json = JSON.parse(xmld.responseText);
if (json.Status == "Ok") {
doument.querySelector("#content").innerHTML = json.HTMLData;
window.location.href = "https://exmaple.com/Search"; // without load
}
}
}
xmld.send();
in example, when you click item than url change without load
I am not use any js and php framework
Example
https://dribbble.com/
https://in.pinterest.com/
it's possible??

if you don't use a framework window.history.pushState() will do the thing you want.
See this link: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

Use a state manager like Redux with a modern Javascript framework like ReactJs.

Related

Handling multiple call to a script

I'm working in an embed script while loads HTML form with JS validation while loaded in web pages. For now only one script loads on a page. If we add more embed script on a single page, the last added or loaded one will work & its related form & validation will execute. What I'm trying is to run multiple embed scripts in a single page.
Here is the current embed script pattern which is placed in HTML page:
<script src="http://link-to-my-embed-code-executer/embed_form.js"></script>
<div id="12345wertyui67890" class="form_wrap"><!-- HTML form with validation loads here --></div>
<script>
window.onload = function() {
EmbedManager.embed({
key:"12345wertyui67890",
is_embed_form:"1",
external_style:"1"
})
}
</script>
Here is the current script in embed_form.js
var EmbedManager = {
key: '',
is_embed_form: !0,
external_style: 0,
resizeCallback: function() {},
init: function(embedParams) {
EmbedManager.key = embedParams.key;
EmbedManager.is_embed_form = embedParams.is_embed_form;
EmbedManager.external_style = embedParams.external_style;
EmbedManager.serverUrl = ''; // Here is the URL which provide HTML Form as response
},
embed: function(embedParams) {
var xhr = new XMLHttpRequest();
xhr.open('POST', EmbedManager.serverUrl);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.onload = function() {
if (xhr.status !== 200) {
document.getElementById(EmbedManager.key).innerHTML = "Unable to load form"
}
var response = JSON.parse(xhr.responseText);
// Attempt to get the element using document.getElementById
var elementDOC = document.getElementById(EmbedManager.key);
// If it isn't "undefined" and it isn't "null", then it exists.
if ((typeof(elementDOC) != 'undefined') && (elementDOC != null) && (EmbedManager.is_embed_form)) {
// Only for Form, not used in LP
document.getElementById(EmbedManager.key).innerHTML = response.form_html;
}
}
// More code here to load Form in place of embed script & do validations
}
}
I'm trying to manage the updates in JS file because embed scripts are already provided to clients & I'm not interested in making bigger updates in those embed scripts. If it could be handled inside the JS file, it will be better.
What I'm trying to do is add a new function remapEmbed which will be a copy of codes in current embed function & also after that will replace codes in embed function to such a manner to collect multiple requests from embed scripts & make an array, later I will call remapEmbed function to do the rest. I know little changes will be needed there also, I will look into it later.
Here is the expected script in embed_form.js
var EmbedManager = {
key: '',
is_embed_form: !0,
external_style: 0,
resizeCallback: function() {},
init: function(embedParams) {
EmbedManager.key = embedParams.key;
EmbedManager.is_embed_form = embedParams.is_embed_form;
EmbedManager.external_style = embedParams.external_style;
},
remapEmbed: function(embedParams) {
// Code which was in `embed` function
// More code here to load Form in place of embed script & do validations
},
embed: function(embedParams) {
// Code to collect request & make a array
// Expecting to add codes here
// Later will call `remapEmbed` function & do rest.
EmbedManager.remapEmbed(embedParamsOne);
}
}
But the issue is that I'm getting only the call from the last embed script which is added on the page. It might be because of the last call overwriting the previous ones. How can I handle multiple requests?
Here I'm adding the Codepen, so you can check the code.
Unfortunately, you cannot place multiple onload events on a single
page. You can nest multiple functions within the one onload call. Ref
It working fine with Your script. Because you are calling embed scripts in Onload. Make sure all scripts inside last window.onload function.
Change html to
<!-- The embed code that will not replace with the response -->
<div id="12345AAA67890" class="form_wrap">HTML form with validation loads here: First Embed Code</div>
<!-- This embed code will be replaced with HTML content -->
<div id="12345BBB67890" class="form_wrap">HTML form with validation loads here: Second Embed Code</div>
<script>
window.onload = function() {
EmbedManager.embed({
key:"12345BBB67890",
is_embed_form:"1",
external_style:"1"
})
EmbedManager.embed({
key:"12345AAA67890",
is_embed_form:"1",
external_style:"1"
})
}
</script>
Hope this is the solution you are looking.

How to extract Article URLs from a external website and store them in a list / array?

I am learning Web Development and I have a little side project which I want to build.
It's a very simple website that should list all of the articles of a particular category on my blog, for example, https://www.ceos3c.com/category/hacking/
So I would like to extract all links to actual blog posts from a category and store them in an array or something for further processing / displaying them on the links list.
I already searched a bit but most solutions were directed towards the same website. So using var links = document.getElementsByTagName("a"); for example. I found this code that kind of does what I want, but I somehow need to access the external URL of my blog instead of the DOM.
var links = document.getElementsByTagName("a");
var thisHref = window.location.href;
for(var i=0; i<links.length; i++) {
templink = links[i].href;
if (templink != thisHref){// if the link is not same with current page URL
alert(links[i].href);
}
}
From a Javascript console, you'll only be able to scrape information from the current page.
You could execute an XMLHttpRequest and try to parse the result but it would be a pain in the arse ( cross site scripting, mixed active content error, Content Security Policy from your browser ...)
Below is a simple example (will only work if you are on the same website: eg https://developer.mozilla.org/fr):
var xhr = new XMLHttpRequest();
var url = "https://developer.mozilla.org/fr/docs/S%C3%A9curit%C3%A9/MixedContent"
xhr.open('GET', url, true);
xhr.send();
xhr.addEventListener("readystatechange", parseResponse, false);
function parseResponse(event) {
if(this.readyState === XMLHttpRequest.DONE)
{
if(this.status === 200)
{
console.log(this.responseText);
} else {
console.warn(this.statusText);
}
}
}
If you really want to scrape data from other website/pages, a better option is to develop/use a webcrawler.
A basic webcrawler will:
Index the content of a page
Extract raw information
Export the data into a structured format
You should have a look on Github
https://github.com/search?q=crawler

How to receive data from html form POST at other html page?

I have a html page called index.html. Inside it I use js to send JSON to other page (loja.html) and right after that I load this page. I would like to read the contents of JSON on loja.html and use it to populate some html tags. Here's my code:
piece of index.html's
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
alert(ajax.status);
}
}
ajax.open("GET", "http://localhost:8080/DBRest/loja.html",true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(dataToJSON(nome,idade));
console.log(dataToJSON(nome,idade));
window.location = 'http://localhost:8080/DBRest/loja.html';
piece of loja.html's js:
window.onload = function() {
alert('alert');
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
alert(ajax.status);
alert(JSON.parse(ajax.responseText));
}
}
}
When I load loja.html from index.html none of alerts are displayed. when typed on browser, only first alert is displayed. How can I correctly send data to loja.html from index.html and after it immediately load loja.html?
Javascript lives/executes within the current browser window/location; if loja.html isn't currently loaded, it won't do anything as the javascript on that page hasn't been run. You'll need a server-side component to accept the GET (not POST) request that you're making and store the data. loja.html can then load that via Javascript.
You have a few options to move data between pages:
Store Data in Local Storage
Store Data in a cookie
Add data to the URL via query parameters
Query the database on the new page to retrieve the data.
Without using a SPA, there isn't a direct way to move data from one html page to another html page.

Request plain text file in javascript from URL?

I started a blog recently and coded it by hand. It is a static, CSS/HTML5 website. Upon sharing it with friends, I realized that when I would update it via FTP, it would be cached already by their browsers. I decided that I would keep all of my blog posts on new pages and then create a landing page that would somehow determine the newest post and forward users there after they clicked an enter button or something like that.
I was able to create a button that could forward them to a specific link, but I want to create a script that will always forward them to the newest page. So I created a file called 'getLatest.json' and uploaded it to an 'api' subfolder of my site. I then tried to use an XMLHttpRequest to load it:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
window.location = "http://latestBlogPost.com" +
xhttp.responseText.today;
//Today is a parent in the object returned.
}
};
xhttp.open("POST", "http://myWebsite.com/api/getLatest.json", true);
xhttp.send();
}
But that didn't work. The response was a null string. I tried using jquery to no avail.
I tried uploading a file called getLatest.html which contained the url in plaintext. That didn't work either.
tl;dr: Is there some way that I can get plaintext from a URL's html content?
edit: getLatest.json and getLatest.html contain a link to the newest blog post.
There are couple of ways to do this.
First your code is not working because you are using a "POST" it should be "GET", if you do that it will work.
Second easiest way is to create a java script file with variable declared and reference that file to your website
<script type="text/javascript" src="http://your javascript file"> </script>
This file contains your variable like this
var latestBlog = "http://....";
in your code use this variable. No more code required. but as i mentioned earlier if you change your HTTP Verb to get your code will work

How can I set the http RequestHeader for a file load in the $script.js library?

The $script.js library I am using
https://github.com/ded/script.js/
has the following Javascript. What I need to do is set the request header in this code block but I am not sure how to do this:
var el = doc.createElement("script"),
loaded = false;
el.onload = el.onreadystatechange = function () {
if ((el.readyState && el.readyState !== "complete" && el.readyState !== "loaded") || loaded) {
return false;
}
el.onload = el.onreadystatechange = null;
loaded = true;
// done!
};
el.async = true;
el.src = path;
document.getElementsByTagName('head')[0].insertBefore(el, head.firstChild);
Here's an example of something similar (not part of $script.js) that does set the request header:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
The first code block (the one I need to use but can modify slightly) is not very clear to me. Does anyone know how I can change this first code blocks (used in $script.js) to set the request header?
If I'm interpreting the library correctly, XMLHttpRequest isn't used directly by $script.js. It appears to be creating <script></script> tags dynamically and letting the browser handle downloading the script files. Using this library, it does not appear you can specify custom headers.
Altering the request headers the browser sends via Javascript is not possible according to some of the articles I've read including the answer to this question on SO: Is it possible to alter http request's header using javascript?
If you want to set custom headers, you'll need to use a dynamic loading library which uses XHR to load the scripts. Here is another article I've found with patterns for this type of functionality: On-Demand Javascript.

Categories

Resources