Load json into javascript - 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();

Related

Laravel #include in js being immediatly executed

I am currently creating a feature on a webpage that aims to create an HTTP request to a server with js when a certain dropdown menu value is changed and the change the webpage based on the request response.
To accomplish this, I am using a Laravel #include to include the view that will build the page based on the json response.
The problem lies on this line allNews.innerHTML+=(`#include('partials.news.post',['news'=>`+news.data[i]+`])`)
The problem here is that an error (in the view caused by the argument news.data[i] being null) is immediately thrown by js when the page is loaded, it doesn't even wait for the EventListener to be triggered or for the request to be answered. If I delete this line of code it does not throw any error and works as expected, but if I comment it, the same error happens, which seems odd to say the least. What seems to be the problem here?
I used this stackoverflow question to base my development on.
I know the view is well built and does not throw errors because I use it in other instances.
<script defer>
let select = document.getElementById("sort-select");
let allNews = document.getElementById("posts-result");
let xhttp = new XMLHttpRequest();
console.log(js_query)
select.addEventListener("change",function(){
xhttp.open("GET", "/api/load-posts-search?sortBy="+ select.value +"&search=" + js_query, false);
xhttp.send();
let news = JSON.parse(xhttp.responseText);
console.log(news);
allNews.innerHTML=""
for(i=0;i<news.total;i++)
{
console.log(news.data[i]);
allNews.innerHTML+=(`#include('partials.news.post',['news'=>`+news.data[i]`])`)
}
})
</script>
The XMLHttpRequest will be asynchronous, so I think you need to change this:
select.addEventListener("change",function(){
xhttp.open("GET", "/api/load-posts-search?sortBy="+ select.value +"&search=" + js_query, false);
xhttp.send();
let news = JSON.parse(xhttp.responseText);
console.log(news);
allNews.innerHTML=""
for(i=0;i<news.total;i++)
{
console.log(news.data[i]);
allNews.innerHTML+=(`#include('partials.news.post',['news'=>`+news.data[i]`])`)
}
})
to:
select.addEventListener("change",function(){
xhttp.open("GET", "/api/load-posts-search?sortBy="+ select.value +"&search=" + js_query, false);
xhttp.send();
// wait on the response from the request
xhttp.onload = function() {
let news = JSON.parse(xhttp.responseText);
console.log(news);
allNews.innerHTML=""
for(i=0;i<news.total;i++)
{
console.log(news.data[i]);
allNews.innerHTML+=(`#include('partials.news.post',['news'=>`+news.data[i]`])`)
}
}
})
I'm not sure about using the #include within the JavaScript, it's not something I've done to know how well it would work. If the included blade file was static I think it would be fine, I'm just not sure how it would work passing it a dynamic news property that comes from an ajax request, i.e. one part of the #include is server side and one is client side, but I could be wrong and it will work completely fine.
You might need to refactor and return the html of the generated partial from the controller instead of trying to do it within the success stage of the ajax request.

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

How to capture all requests with javascript?

I want to create a javascript interceptor in order to capture all requests that i see in the network tab and print them in the website.
Is that possible?
I have found the following code but it doesnt seem to work
let oldXHROpen = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, url, async, user, password) {
// do something with the method, url and etc.
console.log(url);
this.addEventListener('load', function() {
// do something with the response text
console.log('load: ' + this.responseText);
});
return oldXHROpen.apply(this, arguments);
}
Is that possible?
No.
have found the following code but it doesnt seem to work
That will only intercept requests made using the XMLHttpRequest object (not by anything else such as fetch, <script src="...">, <img src="..."> etc.).

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.

JSON without jQuery

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();
};

Categories

Resources