JSON without jQuery - javascript

Using a version of the example from youmightnotneedjquery.com, I'm trying to get JSON into my page that is stored in the same folder as the HTML and JS. My problem is I'm not familiar with the XMLHttpRequest library and the answer I keep finding is "use jQuery or some other library." I added a console.log(); to the function so I could see if I was reaching success or failure because I'm not getting the data back. The original example is here and my code is below. The cv.json exists, is formatted correctly, and the function is sending Success? to the console, but I can't get the JSON data into my cv variable.
In case it is relevant, I'm hosting the JSON, HTML, and JS files in a public dropbox folder which doesn't seem to be part of the problem.
var cv;
request = new XMLHttpRequest();
request.open('GET', 'cv.json', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
// Success!
console.log("Success?");
console.log(request.resonseText);
cv = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
console.log("Error?");
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Note: There are lots of similar questions on stackoverflow but I haven't been able to find an answer to the specific issue I'm encountering; perhaps for people familiar with JavaScript this answer is too obvious to mention explicitly or I'm phrasing my searches incorrectly.
UPDATE: In the web inspector I can see the json file in the sources, with a response 200 and all the data so the file is accessible and being read, I'm just not getting it into the variable correctly apparently. Code updated to reflect corrected use of request.send();.

request.send does not return anything, it creates a handler that resolves a value. at the top level of this add:
var cv;
and then in the success part of the onload function change your return to:
cv = JSON.parse(request.responseText);

The two issues that were preventing the JSON from being show on the page, but still available from the console were
Not loading the variable correctly (resolved thanks to this answer)
Loading the file asynchronously! (resolved thanks to this similar question and it's answer)
Thanks to this comment, I went out and started my journey of learning about callbacks. The JSON load is now a function made as a callback. It's not optimized I'm sure, but sufficient for my current needs/abilities
Here is the working code. The significant change is the false on line 3.
var cv;
var loadJSON = function() {
request = new XMLHttpRequest();
request.open('GET', 'cv.json', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400){
cv = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
};

Related

Adblocker blocks XMLHttpRequest

I understand the fact, that adblockers try to deny loading (image) data later on. Anyway, I want to send some data to a php script (/log.php) to save it in a sql database. So in fact I don't care about the responsetext. This is my current js function I use to call the php script:
function log(id, unix_ms, frameid, eventtype, targetid, value){
var parameters = "";
parameters = parameters.concat("id=", encodeURI(id), "&unix_ms=", encodeURI(unix_ms), "&frameid=", encodeURI(frameid), "&eventtype=", eventtype, "&targetid=", targetid, "&value=", value);
var httprequest = new XMLHttpRequest();
httprequest.open("POST", "/scripts/log.php", true);
httprequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
httprequest.onreadystatechange = function() {
if(httprequest.readyState == 4 && http.status == 200) {
console.log(httprequest.responseText);
}
}
httprequest.send(parameters);
}
What can I change to pass the adblocker? I mean facebook uses things like ajax in masses to load text and even images in the timeline.
Is there maybe a way to use frames in the background since I don't care about the answer?
After analysing the log as suggested in a comment I found out that log.php seems to be in the blocklist, even if it's on the same server. So name you php files a little more complex to avoid this.
log.php -> submitlog.php

Understanding of ajax complete call

I'm struggling with stabilizing Selenium automation for jQuery/AJAX application hence referred to
https://www.swtestacademy.com/selenium-wait-javascript-angular-ajax/
and it has ajaxComplete() method which has following code -
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open('GET', '/Ajax_call', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send();
);
I haven't work on JavaScript before and this code which I'm not able to understand completely. I've following questions with this, if someone can help to understand it -
What is Ajax_call in this? Is it generic call to check ajax completion? Or do I need to have my own endpoint there? If yes, does single end point enough or do I need to identify all calls and add them in the method?
Please check the documentation for XMLHttpRequest.open. If you do, you will the second argument listed is
url
A DOMString representing the URL to send the request to.
This means that it is simply the URL you want to request. I can be anything you want. The / prefix means that you are request relative to the root of the website (so if you are requesting from https://example.com/somedir/somepage the request will be made to https://example.com/Ajax_call.

AJAX POST request to Python method - Post hits right file location, but shows 404

I've been looking at how to integrate AJAX calls into a Python Django application and I'm somewhat new to both. I have been following the advice here:
https://www.quora.com/Can-I-execute-a-Python-function-from-JavaScript
Which led to this and this respectively for AJAX and Django advice.Both made pretty good sense to me. The desired end result is that a template in this fourth folder down (dashboard) call a function in a file called logic.py under the api folder above it:
In a JavaScript file hooked up to my django template, I have the following code I stole from the AJAX resource I listed above and made some light edits to:
window.onerror = function() {
debugger;
}
// browser - safety
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if(window.ActiveXObject) { // ie
try {
request = new ActiveXObject('Msxml2.XMLHTTP');
}
catch(e) {
try {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
catch(e) {}
}
}
function step2() {
console.log('something');
}
function testLogin() {
request.open('POST', '../../../api/logic');
// I've also been trying ^^^ logic.py, if it matters
request.send(null);
console.log('testLogin ran');
step2();
}
request.onreadystatechange = function () {
if(request.readystate === 4) {
if(request.status === 200) {
console.log(request.responseText);
}
}
}
It still is hooked up to a URL POST action in the django views, so when I hit the submit button in question I see the following two requests get generated:
That is the correct filepath for that location:
So I'm wondering if I'm missing something either about the AJAX setup, or the way it needs to interact with Django, or some combination of the two. Other resources I've been consulting in looking into this:
Call Python function from Javascript code
https://codehandbook.org/python-flask-jquery-ajax-post/
https://www.makeuseof.com/tag/python-javascript-communicate-json/
https://bytes.com/topic/javascript/answers/737354-how-call-python-function-javascript
And I originally started way earlier in the day so there were a few more, but needless to say I didn't see my issue immediately from looking at any of them. Any help is much appreciated.
So this wound up being a quirk of the Django url setup, I can't believe I didn't figure it out but I hadn't been in that part of the code base for some time.
In our urls.py script, the place I was pinging (which was in the location of the URL described) had a redirect on it and for that reason, the traffic wasn't going to the place I thought.

Spark POST returns 404 not found seemingly-arbitrarily

Spark has been acting weird lately. I have a button which when clicked calls a POST method with some query parameters:
post("/test", (request, response) -> {
model.put("reason", "some reason here");
...
LOG.info("Returning from /test with reason: " + model.get("reason"));
// the above line always executes and always prints the correct output (never 404)
return new ModelAndView(model, "test.vtl");
}, new VelocityTemplateEngine());
The file test.vtl contains only this: $reason
(which is used in the JS code below to show an alert with the contents of the reason key in the model map).
JS relevant code:
xmlHttp.open("POST", "/test", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var params = "file=" + file + "&searchStr=" + searchStr;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == XMLHttpRequest.DONE) {
alert(xmlHttp.responseText);
}
}
xmlHttp.send(params);
When I click it, sometimes it work perfectly, and when I click again I get a 404 Not Found with:
MatcherFilter:152 - The requested route [/test] has not been mapped in Spark
This happens in a matter of seconds. I click - it works - I click again if fails - again it fails - again it fails - again it suddenly succeeds...
How can that be?
P.s. I have logging inside the post request, so I know Spark is actually accessing it. But it is not returning from it. Does this perhaps have to do with the code inside the post that suddenly raises the 404 (I am not accessing other pages from it though).
There seem to be 2 possible answers to this (why do they solve is a different question):
Adding a Thread.sleep(250); // or even lower.
Changing the request to GET.
I could not find what is the root cause of these arbitrary failures, but ended up choosing option #2.

Load json into javascript

So I have a json html link that like below
www.pretendJsonLink.com/getData
and the data i receive is below:
{"Items":[{"date":1498850140373,"displayId":"003","sentId":"121213",
"customer":"ME"}, {"date":1452870140571,"displayId":"007","sentId":"152713",
"customer":"YOU"}],"Count":2,"ScannedCount":2}
I need to load this into a js file so i can then call them as needed in a html file in an id="" tag
Like Items.date and Items.customer or something like it
Any help would be great and I understand that this should be a simple task, but i can also forward my search history as well :) i have been looking for solutions that work, but just cant seem to find anything that fits my needs
Use JSON.parse() function. Here is the link to documentation
You can use XMLHttpRequest . I found a gist that gives a good example and included it (simplified), below:
var req = new XMLHttpRequest();
req.open('GET', 'www.pretendJsonLink.com/getData');
req.onload = function() {
if (req.status == 200) {
// do what you want, here, with the req.response
// take a look at the object that gets returned, you may need
// to call JSON.parse(), etc.
console.log('success', req.response);
} else {
console.log('error', req.statusText);
}
};
// Handle network errors
req.onerror = function() {
console.log("Network Error");
};
// Make the request
req.send();

Categories

Resources