Making a local file hold a value to use by any user - javascript

I am trying to make a webpage that will be able to store a variable, using JavaScript, called heart-count (I was trying it with jQuery and JSON, but didn’t have any luck, I could access the number easily, but I couldn’t change it).
This variable should be easily accessed by the JavaScript and be able to be changed (or in my case incremented).
The way that I have it right now is in a local file called heart.json inside this file is the following code:
{
"hearts": 0,
"heartLog": []
}
I am accessing that file in my JavaScript like this:
$.getJSON("../js/heart.json", function(data) {
$("#num-hearts").text(data.hearts)
})
I was trying to use XMLHttpRequest (a way that was suggested to me):
var myJSON
$.getJSON("../js/heart.json", function(data) {
myJSON = data
setTimeout(() => {
myJSON.hearts++
console.log(myJSON)
console.log(data)
}, 2000);
})
var xhr = new XMLHttpRequest()
xhr.open("PUT","../js/heart.json",true)
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
xhr.send(JSON.stringify(myJSON))
I can’t confirm that this doesn’t work, since the way that the webpage is set up I test it using some interesting methods (interesting, but required…), and those use localhost. The reason I say that I can’t confirm that it doesn’t work, is because when I test the previous code, it says that “PUT” isn’t a valid protocol.
If there are any suggestions or validations of my code, that would help a lot.

How ya doin? I'm sorry to say but you can not write to a file in server directly with jQuery or Javascript because Javascript is frontend language. It doesn't have the capability to do so.
However you can send or receive data with XMLHttpRequest, but you need a server side language/program to process your XMLHttpRequest.

Related

Passing a field value in the URL

Can I dynamically edit the url of the datatable depending on the value of the “Value” field of the search form in another file?
For example:
{ view:"text", label:"input data", value:"apple" }
In datatable.js
url: 'resource->/api/archive/apple'
Okay, I was told that I can send AJAX requests, but now I can't figure out how to get them correctly on another page
Sending:
webix.ajax().post('apples', get_form())
routie('apples')
In devtools I get the form value
I'm trying to get the formData value to substitute it in the URL
function get_data() {
let result;
webix.ajax("apples").then(function (data) {
data = data.text();
result = data;
});
return result;
}
URL
url: 'resource->/api/archive/all/'.concat(get_data()),
On the backend side, this controller works well, but I can't call it from the front side. I'm just learning frontend, so any help would be greatly appreciated.
In general, the way to do this is: When the value is changed (the onChange event), call clearAll() and load(newUrl) methods of the datatable. You cannot change the url property at runtime (well, you can, but it won't work).
As for different files, people usually build SPAs with Webix, so files here might be modules, not pages. Do you use Webix Jet? If yes, then communication between the form and the datatable can be done via the app event bus. If not, then they can communicate directly (import both files in some other file and do it there). If this is a multiple-page app, then yes, you do need some server side communication between them (maybe even with sockets).

Script error: "Unable to get value of the property 'split': Object is null or undefined

I searched around, and couldn't find an answer to my question. I'm very new at coding, and at work, we have an application that current names that are logged in, and what they are doing.
Recently, they have changed from jquery 1.4.1 to jquery 1.8.3. Ever since then, I cannot get the results to process correctly, because of the following error;
"Unable to get value of the property 'split': Object is null or undefined"
I have the code setup to grab the results and split them;
function processAgents(xData, status) {
var avail = xData.responseText.split("|")[0];
var acw = xData.responseText.split("|")[1];
var total = xData.responseText.split("|")[2];
var breaks = xData.responseText.split("|")[3];
var pending = xData.responseText.split("|")[4];
The application is setup to open as an HTA file which opens up the PHP script.
Any help would be appreciated, please let me know if I left anything out!
Thanks!
EDIT 1
I did some more investigating, and it looks like I'm not getting data from my process request. This is how it is currently setup
function updateAgents() {
var ts1 = new Date().getTime();
$.ajax({
url: "http://SERVER/AgentSrc.php?x=" + ts1,
complete: processAgents
I'm not sure if this is processing correctly since they went to jquery 1.8.3.
EDIT 2
So after looking into it more, it doesn't appear that the script is getting the data from the server, even though I have access. If I make a local file and put the information in it, it will pull the information and split it, but if I point to the path of the file on the server, it won't get the information. But the strange thing is, if I run it using jquery 1.4.1, it pulls the data fine, but can't display it. But with 1.8.3, it doesn't allow me to pull it from the server.
thanks again!
This will give some clarity
xData.responseText.toString().split("|")[0];
(split is part of string not jQuery)
Here is a possible explanation: in earlier versions of jQuery, ajax calls returned an xmlHttpRequest (XHR) object. Recent versions return a promise (jqXHR) instead.
See this page for more details.

How to pass variables from an HTTPObject

I'm very, very new to Javascript, and to web programming in general. I think that I'm misunderstanding something fundamental, but I've been unable to figure out what.
I have the following code:
function checkUserAuth(){
var userAuthHttpObject = new XMLHttpRequest();
var url = baseURL + "/userAuth";
userAuthHttpObject.open("POST",url,true);
userAuthHttpObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
userAuthHttpObject.onload=function(){
if (userAuthHttpObject.readyState == 4) {
var response = json.loads(userAuthHttpObject.responseText);
return response; //This is the part that doesn't work!
}
};
userAuthHttpObject.send(params);
}
I would love to call it from my page with something like:
var authResponse = checkUserAuth();
And then just do what I want with that data.
Returning a variable, however, just returns it to the userAuthObject, and not all the way back to the function that was originally called.
Is there a way to get the data out of the HttpObject, and into the page that called the function?
Working with AJAX requires wrapping your head around asynchronous behavior, which is different than other types of programming. Rather than returning values directly, you want to set up a callback function.
Create another JavaScript function which accepts the AJAX response as a parameter. This function, let's call it "takeAction(response)", should do whatever it needs to, perhaps print a failure message or set a value in a hidden field and submit a form, whatever.
then where you have "return response" put "takeAction(response)".
So now, takeAction will do whatever it was you would have done after you called "var authResponse = checkUserAuth();"
There are a couple of best practices you should start with before you continue to write the script you asked about
XMLHTTTPRequest() is not browser consistent. I would recommend you use a library such as mootools or the excellent jquery.ajax as a starting point. it easier to implement and works more consistently. http://api.jquery.com/jQuery.ajax/
content type is important. You will have have problems trying to parse json data if you used a form content type. use "application/json" if you want to use json.
true user authorization should be done on the server, never in the browser. I'm not sure how you are using this script, but I suggest you may want to reconsider.
Preliminaries out of the way, Here is one way I would get information from an ajax call into the page with jquery:
$.ajax({
//get an html chunk
url: 'ajax/test.html',
// do something with the html chunk
success: function(htmlData) {
//replace the content of <div id="auth">
$('#auth').html(htmlData);
//replace content of #auth with only the data in #message from
//the data we recieved in our ajax call
$('#auth').html( function() {
return $(htmlData).find('#message').text();
});
}
});

Javascript + jQuery UI: After externalizing a JSON variable to a file, how to read the value back?

I'm quite a beginner in JS and even more in jQuery UI. I don't understand if my problem has a very simple synchronous solution, or if I need to write callback functions to cope with something that cannot be anything else than asynchronous...
I had this in a script associated with an HTML document:
var json = "[{ ... some object ... }]"
As the JSON object must be changed, I've created a text file and moved the value into it. Now I've to read the value from the file to assign it to the variable.
I see that when in production, the HTML page will be served by an HTTP server, and the file must be remotely retrieved using HTTP on the server. But also that if I want to test the page on my development machine, with no server, this is just reading a local file.
Is there a single piece of code that can read the JSON value in both situation, in a synchronous mode, so that something like this would be possible:
var json = ... piece of code...
I initially thought using:
$.getJSON("file.json", function(obj) { json = obj; });
expecting a read error would lead to json variable being the empty or null, but it seems the call is asynchronous and requires more code in callback functions.
Any guidance appreciated.
First of all, the call definitely should be synchronous. Just move the rest of your code into the callback, it's not that hard - and it will make your browser responsive while the file is downloaded.
If this is really a big problem, you can use the async option in $.ajax:
$.ajax({
async: false,
url: 'file.json',
dataType: 'json',
success: function (value) { json = value; }
});
Note: This will only work if the file you're requesting is from the same domain, and may or may not fail for local files, depending on the browser.

Passing JavaScript variable to Python

For example:
#!/usr/bin/python
print "This is python."
print "<script type="text/javascript">
var pass_to_python = new Number(7)
</script>"
the_number = pass_to_python???
How do I get the pass_to_python in python?
With pyv8 you can execute javascript from within Python.
import PyV8
class Global(PyV8.JSClass):
pass
with PyV8.JSContext(Global()) as ctxt:
the_number = ctxt.eval("var pass_to_python = new Number(7)")
see http://code.google.com/p/pyv8/
You can GET or POST to the Python script. If you need to do this dynamically, you can use AJAX.
Here is a good link: How are POST and GET variables handled in Python?
i am using flask and ajax to pass values from javacript to python
function pass_values() {
var pass_to_python = new Number(7)
$.ajax(
{
type:'POST',
contentType:'application/json;charset-utf-08',
dataType:'json',
url:'http://127.0.0.1:5000/pass_val?value='+pass_to_python ,
success:function (data) {
var reply=data.reply;
if (reply=="success")
{
return;
}
else
{
alert("some error ocured in session agent")
}
}
}
);
}
python:
#app.route('/pass_val',methods=['POST'])
def pass_val():
name=request.args.get('value')
print('name',name)
return jsonify({'reply':'success'})
HTTP is a simple request-response protocol, it doesn't let you pause mid-stream and wait for more information from the client — and since your JS runs in the browser (JS can run on the server, but most people wouldn't be attempting this if they didn't need the code to run in the browser, so I'm assuming that using server side JS is out of the question) and the Python runs on the server, that is what you need for your code to work (as well as fixing your broken quote nesting in the Python code).
You need to load the complete document, and then issue a new HTTP request.
This might involve having the JS set location.href (making sure you have a fallback for non-JS clients), it might involve using XMLHttpRequest to load new data asynchronously, it might be best using another technique (it is hard to say for sure as your example simplifies too much to tell what X is)
I think using JSON is the best way.you can create a JSON file as intermidiary between JavaScript and Python, both languages can access and modify JSON file

Categories