My HTML file looks like this:
Sum: <div id="sum">?</div>
And the corresponding JavaScript like this:
function refresh(){
//Wait for request from Amazon Gateway API, then replace 'sum' with result of
Python function
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "https://8qp45dk604.execute-api.us-east- 1.amazonaws.com/beta", true);
xhttp.send();
xhttp.addEventListener("readystatechange", processRequest, false);
function processRequest(e){
if(xhttp.readyState == 4 && xhttp.status == 200){
var response = JSON.parse(xhttp.responseText);
var a = response.a;
var b = response.b;
document.getElementById("sum").innerHTML =
resultOfPythonFunction('sum.py', 'sum', a, b);
}
}
setTimeout(refresh, 3000);
}
What should I replace the line resultOfPythonFunction('sum.py', 'sum', a, b); with in order to modify the div with the result of a Python sum function?
The browser can't execute python code. To do what you're asking, you would have to set up a python back end that you could send HTTP POST requests to that would perform sum on your request body, and then send back the result. Some common tools for this are django, flask, and pyramid.
You could then grab this result and set it to the div in the way you did before.
Related
I'm trying to call a Restful service on my localhost. I am doing it this way because It's an asynchronous call. The appropriate Url plus the Uri-template to call my service is this:
"http://localhost:65016/Service1.svc/SN?lower=200&upper=300"
on the line where I try to open ( xhttp.open ), my client page only receives the proper data whenever I literally insert the url like this:
xhttp.open("GET", "http://localhost:65016/Service1.svc/SN?lower=200&upper=300" , true);
but I need the 200 and 300 numbers to be user input so I tried these two things:
I first tried grabbing the user input and simply concatenating it to the base URL in between the URi template like this:
<script>
function ServiceCall()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
var ans = document.getElementById("secretNum");
ans.innerHTML = xhttp.responseText;
}
}
var base_uri = "http://localhost:65016/Service1.svc/";
// grab the lower number
var ln = document.getElementById("LN").firstChild;
var LN = ln.nodeValue;
// grab upper number
var un = document.getElementById("UN").firstChild;
var UN = un.nodeValue;
//complete
var URL = base_uri + "SN?lower=" + LN + "&upper=" + UN;
xhttp.open("GET", URL, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
}
</script>
Doesn't work. So i tried looking at the documentation for the xmlHttpRequest.open, and I saw that the parameter had to be a URL. so I tried using the URL(string) function and using the output as a parameter and that didn't work either.
Any help please?
Thank you. I it helped to look at the network request. I was simply using the wrong syntax to obtain the value inside of the html input tag.
var ln = document.getElementById("LN").value;
returns the real value inside of html input tag given by the user input.
I'm answering my own question because this is a homework assignment.
(Not that I was cheating. Answering this is far from solving the homework)
I am currently attempting to move a variable from JS to PHP.
They are being used for Stripe.
I understand I may have to use AJAX?
function _goAheadWithCustomerId(c) {
console.log('Customer Id is :', c);
customerId = c; }
I want to move customerId to a PHP file.
How might I do that?
Well the easiest way i can think of without using AJAX is just send a get request to a php page using
window.location.href
Code for JS
function _goAheadWithCustomerId(c) {
console.log('Customer Id is :', c);
customerId = c;
window.location.href = "index.php?customerid=" + c;
}
And later using php check if(isset($_GET["customerid"] to check if the value has been received or not.
Php Code
if(isset($_GET["customerid"]))
{
$c = $_GET["customerid"];
// use it the way you want.
}
You can try following code in AJAX.
function sendCustId(c) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("custDiv").innerHTML = "Customer ID successfully sent to server.";
}
};
xhttp.open("GET", "myPhpScript.php?custId="+c, true);
xhttp.send();
}
At server side you need to access variable as
$customerId = $_REQUEST['custId'];
I have a js function GetTableData() that gets an array like this. [rowindex,[value1,value2,value3...]]. I want to send over these array using Ajax POST to a php script or url. This time, its not variables that are being sent over but its a function GetTableData() that holds the array of values. How do I go about this as no data is being sent.
<script language="JavaScript" type="text/javascript">
function ajax_post() {
var hr = new XMLHttpRequest();
vars = function GetTableData;// This is my problem
hr.open("POST", "destination.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.table_attendance == 200) {
}
}
hr.send(vars); // Actually execute the request
document.getElementById("resultsdiv").innerHTML = "processing...";
}
</script>
HTML code here
<input type="button" value="Post using Ajax" onClick="javascript:ajax_post() );" />
As Marc B also points out:
var vars = GetTableData();
This will only work if GetTableData is defined in a higher scope than the current function and is accessible to that function.
Also make sure GetTableData "returns" the data; so your function:
function GetTableData()
{
return [rowindex,[value1,value2,value3..]];
}
Besides you have to call your GetTableData as vars = GetTableData();, you have to encode your request data:
hr.send("tableData=" + encodeURIComponent(JSON.stringify(vars)));
We do 2 encodings
encodeURIComponent Mandatory, required to be sent by POST with application/x-www-form-urlencoded
JSON.stringify Optional (can be another encoding method). Has to be an encoding method that your backend cand decode. JSON is a great one and almost a standard
Then, parse it (decode) in the backend. For example in PHP
$tableData = json_decode($_POST['tableData'])
Hope this helps. Cheers
Here is my javascript function that reads from the file every second and outputs it:
var timer;
var url = "http://.../testdata.txt";
function ajaxcall() {
var lines;
var alltext;
request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if (request.readyState === 4) { // document is ready to parse.
if (request.status === 200) { // file is found
allText = request.responseText;
lines = request.responseText.split("\n");
document.getElementById("test").innerHTML = "";
for (i in lines) {
document.getElementById("test").innerHTML += lines[i] + "<br>";
}
}
}
}
request.send();
}
timer = setInterval(ajaxcall, 1000);
I haven't got the hang of AJAX yet so I tried to make a similar way to write into the file using what I read on the internet:
function chat() {
request = new XMLHttpRequest();
request.open("POST", url, true);
request.send("\n" + document.getElementById("chatbox").value);
}
However that does absolutely nothing and I don't understand why. The element "chatbox" is input type textbox and chat() is called by input type submit.
You cannot write to a file using just a POST call. In fact, you cant write to a file using only JavaScript/AJAX. You will need a server-side script in for example PHP that will write to the file for you, and then you need to call this script using AJAX.
I'm creating a simple WebGL project and need a way to load in models. I decided to use OBJ format so I need a way to load it in. The file is (going to be) stored on the server and my question is: how does one in JS load in a text file and scan it line by line, token by token (like with streams in C++)? I'm new to JS, hence my question. The easier way, the better.
UPDATE: I used your solution, broofa, but I'm not sure if I did it right. I load the data from a file in forEach loop you wrote but outside of it (i.e. after all your code) the object I've been filling data with is "undefined". What am I doing wrong? Here's the code:
var materialFilename;
function loadOBJModel(filename)
{
// ...
var req = new XMLHttpRequest();
req.open('GET', filename);
req.responseType = 'text';
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line)
{
readLine(line);
});
}
}
req.send();
alert(materialFilename);
// ...
}
function readLine(line)
{
// ...
else if (tokens[0] == "mtllib")
{
materialFilename = tokens[1];
}
// ...
}
You can use XMLHttpRequest to fetch the file, assuming it's coming from the same domain as your main web page. If not, and you have control over the server hosting your file, you can enable CORS without too much trouble. E.g.
To scan line-by-line, you can use split(). E.g. Something like this ...
var req = new XMLHttpRequest();
req.open('GET', '/your/url/goes/here');
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var lines = req.responseText.split(/\n/g);
lines.forEach(function(line, i) {
// 'line' is a line of your file, 'i' is the line number (starting at 0)
});
} else {
// (something went wrong with the request)
}
}
}
req.send();
If you can't simply load the data with XHR or CORS, you could always use the JSON-P method by wrapping it with a JavaScript function and dynamically attaching the script tag to your page.
You would have a server-side script that would accept a callback parameter, and return something like callback1234(/* file data here */);.
Once you have the data, parsing should be trivial, but you will have to write your own parsing functions. Nothing exists for that out of the box.