Change content of text with Ajax in pug - javascript

I have to use Ajax on my website for a school project. I want to change the content of a button, but I first wanted to be able to change some text. I've found some examples on how to change text in a pug-file but they never seem to be working. Does anybody know what I'm doing wrong?
Pug:
extends layout
block content
#reizen.w3-content.w3-container.w3-padding-64
//test ajax
#demo
h2 The XMLHttpRequest Object
button(type='button' onclick='loadDoc()') Change Content
block content
script.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
And I have also a little file, ajax_info.txt, in the root map (the pug file is in the views-map) with only:
Ajax is cool!
The result is always some text: The XMLHttpRequest Object,
and under the text a button with, Change content, but nothing happens when I click on it.

Pug is a completely separate paradigm from Ajax. Ajax is used to make a request from a server without reloading a page, and pug dynamically renders pages when they are requested from the server. A pug application involves building multiple pages, and an Ajax application uses one page.
You can generate the HTML and JavaScript using pug, but that's where the pug ends. It simply can't be used in Ajax calls.
You should look into Ajax libraries like Axios or jQuery and focus your attention there. You can use Express (without pug) to handle your API calls.

Related

How to run PHP code in a JavaScript Function?

I am trying to make a function to open a webpage in the same tab as the one you are coming from, (think clicking on a bookmark in a tab). I have the page I want to go to and I know the PHP code to do what I want,
<?php
header("Location: example.php")
?>
I am wondering if there is a way for me to run PHP code in JavaScript so I can do what I want?
(Before anyone asks why I don't just run the code this way, it's because the situation I am in requires me to run the code through a JavaScript function)
You don't need PHP for page redirection. You can simply do this in pure javascript.
function gotoExample() {
window.location.href = './example.php';
}
Mixing PHP and javascript introduces complication to your code. Avoid that if possible.
There are various ways on how you can run a php script inside a js function. One way is via ajax.
//some js logic here
if (foo) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "http://foo.bar/path/to/a/script.php", true);
xhttp.send();
}
What happens on the above code is that when foo evaluates to true, than a XMLHttpRequest is called and a server side script written in php is executed.
However, in your case, it It is better to just handle a redirect on the client side rather than relying on PHP.
if (foo) {
window.location.href = 'http://foo.bar/path/to/a/script.php';
}
There are various ways on how to issue a redirect via js. The interned is huge. You'll find it with just a couple of searches.

How to reload the CSS or button or part of a page after get request is received?

after get request arrive the values are there and the button disappear
this is the button working on the localhost..
Im trying to add a Facebook share button in a page with dynamic contents like userid, coming from a esp826 server, using java script like innerhtml by ajax call get request once of json when the page body is on-load. When i test in my local host everything is ok since the json file load very fast and before the button loads and so everything works ok. but when i use the esp8266 server the response of the get request come somewhat after the button is loaded and so when it received and the fields get populated with the values the button disappear and remain only a word with a link.
basically the button is working on my localhost... so the innerhtml and everything is ok.. it seems i need to find a way to reload the css or something by the javascript to get the button box alive again.
is there a way to reload the button?
the .json file is just this: getajx.json
{"temp1":"1", "energia":"2", "energiatotal":"3", "tem":"2", "cliente":"22", "usuario":"22"}
you can test on your localhost by placing this getajx.json file having that content in the same directory of the html page is going to work... but i need to know how to make it work if the get request get too long.. please any help???
i tried to add a flag after the response is positive and activate the reloadCss funtion with it but didnt worked
<script>
var temp1, energia, energiatotal, tem, cliente, usuario ;
var ok=0;
function GetAjx() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
ok = 1;
var myObj = JSON.parse(this.responseText);
document.getElementById("temp1").innerHTML = myObj.temp1;
document.getElementById("energiatotal").innerHTML = myObj.energiatotal;
document.getElementById("tem").innerHTML = myObj.tem;
}};
if (ok =1) { function reloadCss(){
var links = document.getElementsByTagName("link");
for (var cl in links){
var link = links[cl];
if (link.rel === "stylesheet")
link.href += "";
}}
};
xmlhttp.open("GET", "getajx.json" , true);
xmlhttp.send();
}
</script>
I found a solution...
apparently i had to change the order of the scripts making the jquery ajax source load first and also tried to put the script from facebook at the bottom of the page...
i took away the reload scripts and other facebook scripts i was testing
and most importantly made the get request false to make it sync instead of async this forces the page to wait for the get request finish..strangely i tried it before and didnt worked this solution perhaps because of the order of the scripts.. can anyone comment on that?
xmlhttp.open("GET", "getajx.json" , false);
was helpful using the f12 on google chrome in specific the performance tab
i decided to not mess up with priority of the scripts even if i tried
any comments i would appreciate
again
thanks for the help

JavaScript / Python interaction in Linux without a REST framework?

I'm working on some changes to a page that needs to retrieve information from some files under /proc so the page can display version information to the user. Currently, the page is generated entirely by the Python script, which allows me to just read the file and put everything in the page at creation time.
However, this led to the issue that the version numbers wouldn't update when a new version of the software was uploaded. I don't want to regenerate the page every time a new package is installed, so I made the main page static and want to instead just query the information from a Python script and return it to the page to populate the page when loaded.
The Python scripts are set up as CGI and have sudo access, so there's no issue with them retrieving those files. However, if I wanted to use something like AJAX to call the Python script, is there any way I could return the data without using a REST framework such as Flask or Django? The application needs to be lightweight and preferably not rely on a new framework.
Is there a way I can do this with vanilla JavaScript and Python?
Ok, so the solution was fairly simple, I just made a few syntactical errors that led to it not working the first few times I tried it.
So the request looked like this:
window.onload = function() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if((this.readyState == 4) && (this.status == 200)) {
var response = JSON.parse(this.responseText);
// Do stuff with the JSON here...
}
};
xhr.open("GET", scriptURL, true);
xhr.send();
}
From there, the Python script simply needed to do something like this to return JSON data containing my version numbers:
import sys, cgi, json
result = {}
result['success'] = True
result['message'] = "The command completed successfully"
d = {}
... write version information to the 'd' map ...
result['data'] = d
sys.stdout.write("Content-Type: text/plain\n\n")
sys.stdout.write(json.dumps(result))
sys.stdout.write("\n")
sys.stdout.close()
The most persistent problem that took me forever to find was I forgot a closing quotation in my script tag, which caused the whole page to not load.

Get text from a link in javascript

I am trying to get text from a service on the same server as my webserver. The link is something like this:
http://<OwnIPadres>:8080/calc/something?var=that
This is my code:
function httpGet(theUrl)
{
alert(theUrl);
var doc = new XMLHttpRequest();
doc.onreadystatechange = function() {
if (doc.readyState == XMLHttpRequest.DONE) {
alert("text: " + doc.responseText );
document.getElementById('ctm').text = doc.responseText;
}
}
doc.open("get", theUrl);
doc.setRequestHeader("Content-Encoding", "UTF-8");
doc.send();
}
The url that i print in my first alert is the good one if i test in my browser, it is an html page with a table in it. But the alert of my text is empty? Is it a problem that the text is html?
Actually, its quite ok that your 'text' is 'html'. The problem is that using a different port counts as cross-site scripting. Therefore, your XMLHttpRequest is being stopped by the browser before it actually reaches your page across port 8080.
I'm not sure what else you're doing before and around this code snippet, but you could try an iframe call to your url to get your data, or you could add an
Access-Control-Allow-Origin: http://:8080/
in your header (however that will only get you the most modern browsers).
Finally, you could pull in a JS framework like JQuery which could help you with pulling in this service data.

Ajax call from Bookmarklet

I am trying to create a bookmarklet that, upon clicking, would request some information from the user (a url and a couple other fields in this case) and then send that data to a php page on my server and then display the result.
I would like to do an Ajax call for this so that I don't actually redirect to the new page, just get the data but I assume I would run into the "Same Origin Policy" limitation of Ajax.... is there any known way of basically doing the same thing?
Also, what would be the best way to pass the parameters? I already have a mechanism in place to recieve the parameters as a post message from a form...is there any way I could just reuse this?
You can set a bookmarklet by create a bookmark and add that piece of code below in location, but, according to same origin policy limitation, that will only work when the current tab is on the same location, here www.google.com.
If I've understand well your needs, that should be ok for your problem.
var request = new XMLHttpRequest();
request.open("GET", "http://www.google.com", true);
request.onreadystatechange = function() {
var done = 4, ok = 200;
if (request.readyState == done && request.status == ok) {
if (request.responseText) {
alert(request.responseText);
}
}
};
request.send(null);
I don't know if POST would work.
You won't be able to do a post, but a GET will work fine. If you're using something like jQuery, it will simply create a script tag with a src URL which would send the data you are looking to submit.
You will have to return JSON style data.
See: http://docs.jquery.com/Ajax/jQuery.getJSON
Alternatively, your bookmarklet could create an iframe on the page, and that could do you work of submitting the data (you could use post then) if you weren't looking to communicate between the iframe and the page itself, but instead just use user input to submit.

Categories