Cannot read property 'Drivers' of undefined - javascript

Its my first time posting here but i'm desperate for a solution. I'm sorry in advance if my question format is not proper. So basically what i'm struggling with is appending json data to paragraphs in my html. My API is okay, i checked with console.log the data is there, but every time i try to append the data, an error pops up in my console stating: Uncaught TypeError: Cannot read property 'Drivers' of undefined.
I've tried removing MRData from function but that didn't seem to do anything.
$.getJSON("http://ergast.com/api/f1/2016/drivers.json", function(MRData) {
console.log(MRData);
var drId = MRData.DriverTable.Drivers[0].driverId;
var permanentNum = MRData.DriverTable.Drivers[0].permanentNumber;
var kod = MRData.DriverTable.Drivers[0].code;
$('#p0').append(drId);
$('#p1').append(permanentNum);
$('#p2').append(kod);
})
<body>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
</body>
What I'm hoping to accomplish here is to get the strings from each of the variables and to append them to my paragraphs.

the problem is that you think that the result data is MRData but instead it is an object which holds MRData.
data = {
MRData: {...}
}
accessing to MRData will make your code to work.
$.getJSON("http://ergast.com/api/f1/2016/drivers.json", function(data) {
//data is an object which will have MRData inside.
var MRData = data.MRData;
var drId = MRData.DriverTable.Drivers[0].driverId;
var permanentNum = MRData.DriverTable.Drivers[0].permanentNumber;
var kod = MRData.DriverTable.Drivers[0].code;
$('#p0').append(drId);
$('#p1').append(permanentNum);
$('#p2').append(kod);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
</body>

you must use
var MRData =data.MRData;
console.log(data.MRData);
var drId = MRData.DriverTable.Drivers[0].driverId;
var permanentNum = MRData.DriverTable.Drivers[0].permanentNumber;
var kod = MRData.DriverTable.Drivers[0].code;
$('#p0').append(drId);
$('#p1').append(permanentNum);
$('#p2').append(kod);
})
your reciver data has field MRData and you use var MRData =data.MRData;

Inside the json file you have a variable mrData so your start should be
MRData.MRData.DriverTable.Drivers
if you have a look at your json file it says
{
MRData={}
}
adding MRData= MRData.MRData; should fix the problem. or you could simple modify the jsonfile content to {DriverTable:{// bla bla bla }}
$.getJSON("http://ergast.com/api/f1/2016/drivers.json", function(MRData) {
console.log(MRData);
MRData= MRData.MRData; // here is a simple workout
var drId = MRData.DriverTable.Drivers[0].driverId;
var permanentNum = MRData.DriverTable.Drivers[0].permanentNumber;
var kod = MRData.DriverTable.Drivers[0].code;
$('#p0').append(drId);
$('#p1').append(permanentNum);
$('#p2').append(kod);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p id="p0"></p>
<p id="p1"></p>
<p id="p2"></p>
</body>

Related

Getting "undefined" return in readAsDataURL

I'm trying to get a image file from a input field in my form, transform it to a base64 string, and then send it to my backend using AJAX, but it's returning undefined. Weird thing is that I managed to do it in a JSFiddle, but am not achieving this in the server.
P.S.: I'm not gonna write the AJAX call and server interactions, as they are not relevant for this issue. I'm sending more data, and it's getting sent just right.
<form method="post">
<input type="file" id="documento" accept="image/*"/><br>
<button type="submit" id="continuar">Continuar</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript">
$("#continuar").click(function (){
var fileInputDoc = document.getElementById('documento');
var readerDoc = new FileReader();
readerDoc.readAsDataURL(fileInputDoc.files[0]);
readerDoc.onload = function () {
var docb64 = readerDoc.result; //This is the point where everything goes wrong. Here I get the following error: "Cannot read property 'indexOf' of null".
var doc_aux = docb64.indexOf('base64,');
doc_aux += 7;
var doc = docb64.slice(doc_aux);
}
}
</script>
It might also be important to say that I've tested separate parts of the code, such as:
document.getElementById('documento'); (doesn't return null, meaning it found the actual element)
readerDoc.readAsDataURL(fileInputDoc.files[0]); (returns [object FileReader])
Functional JSFiddle
My sources:
https://www.codegrepper.com/code-examples/javascript/convert+input+image+to+base64+javascript
https://developer.mozilla.org/pt-BR/docs/Web/API/FileReader/readAsDataURL

How to append Ajax Json respond to html?

I use ajax get a json like this:
{"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"}
How to append "delete_flag" , "id" , "icon_img" to 3 different places on html ?
You can use this pure javascript method like below.
The code basically uses document.getElementById() to get the element, and .innerHTML to set the inside of the element to the value of the object.
This code (and the code using jQuery) both use JSON.parse() to parse the data into the correct object that our code can read. The [0] at the end is to select the object we wanted since it would give us an array (and we want an object).
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
document.getElementById("delete_flag").innerHTML = parsedData.delete_flag;
document.getElementById("id").innerHTML = parsedData.id;
document.getElementById("icon_img").src = parsedData.icon_img;
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
Or you can use jQuery (which in my opinion, is much simpler). The code below uses .html() to change the inside of the divs to the item from the object, and .attr() to set the attribute src to the image source you wanted.
const result = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(result.dataStore)[0];
$("#delete_flag").html(parsedData.delete_flag);
$("#id").html(parsedData.id);
$("#icon_img").attr("src", parsedData.icon_img);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="delete_flag"></div>
<div id="id"></div>
<img id="icon_img">
you can use jQuery .html() or .text()
For example:
var json = {"id" : "74"};
$( "#content" )
.html( "<span>This is the ID: " + json.id + "</span>" );
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Just use some simple JavaScript parsing:
const jsonData = {"dataStore":"[{\"delete_flag\":\"false\",\"id\":\"74\",\"icon_img\":\"img/a5.jpeg\"}]"};
const parsedData = JSON.parse(jsonData.dataStore)[0];
document.getElementById("delFlag").textContent = "Delete Flag: " + parsedData["delete_flag"];
document.getElementById("id").textContent = "ID: " + parsedData["id"];
document.getElementById("img").textContent = "Image: " + parsedData["icon_img"];
<p id="delFlag"></p>
<p id="id"></p>
<p id="img"></p>
Note that you can't parse the full object jsonData because it's not JSON - only the data inside it is JSON.
I've upvoted the other answers, but maybe this will help someone else. On your ajax success function, do something like this:
success: function(data){
// console.log('succes: '+data);
var delete_flag = data['delete_flag'];
$('#results').html(delete_flag); // update the DIV or whatever element
}
if you got real fancy, you could create a for loop and put all the json variable you need into an array and create a function to parse them all into their proper elements; you could learn this on your own fairly easily.
var data = {
"dataStore": {
"delete_flag": "false",
id: "74"
}
}
$('.flag').html(data.dataStore.delete_flag);
$('.id').html(data.dataStore.id);
span {
color: red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Flag: <span class="flag"></span>
<hr />
ID: <span class="id"></span>

How do I use this JavaScript variable in HTML?

I'm trying to make a simple page that asks you for your name, and then uses name.length (JavaScript) to figure out how long your name is.
This is my code so far:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
</body>
I'm not quite sure what to put within the body tags so that I can use those variables that I stated before. I realize that this is probably a really beginner level question, but I can't seem to find the answer.
You don't "use" JavaScript variables in HTML. HTML is not a programming language, it's a markup language, it just "describes" what the page should look like.
If you want to display a variable on the screen, this is done with JavaScript.
First, you need somewhere for it to write to:
<body>
<p id="output"></p>
</body>
Then you need to update your JavaScript code to write to that <p> tag. Make sure you do so after the page is ready.
<script>
window.onload = function(){
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
</script>
window.onload = function() {
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('output').innerHTML = lengthOfName;
};
<p id="output"></p>
You can create a <p> element:
<!DOCTYPE html>
<html>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
p = document.createElement("p");
p.innerHTML = "Your name is "+lengthOfName+" characters long.";
document.body.appendChild(p);
</script>
<body>
</body>
</html>
You can create an element with an id and then assign that length value to that element.
var name = prompt("What's your name?");
var lengthOfName = name.length
document.getElementById('message').innerHTML = lengthOfName;
<p id='message'></p>
<head>
<title>Test</title>
</head>
<body>
<h1>Hi there<span id="username"></span>!</h1>
<script>
let userName = prompt("What is your name?");
document.getElementById('username').innerHTML = userName;
</script>
</body>
Try this:
<body>
<div id="divMsg"></div>
</body>
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length;
document.getElementById("divMsg").innerHTML = "Length: " + lengthOfName;
</script>
You cannot use js variables inside html. To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.
The HTML tags that you want to edit is called the DOM (Document object manipulate), you can edit the DOM with many functions in the document global object.
The best example that would work on almost any browser is the document.getElementById, it's search for html tag with that id set as an attribute.
There is another option which is easier but works only on modern browsers (IE8+), the querySelector function, it's will find the first element with the matched selector (CSS selectors).
Examples for both options:
<script>
var name = prompt("What's your name?");
var lengthOfName = name.length
</script>
<body>
<p id="a"></p>
<p id="b"></p>
<script>
document.getElementById('a').innerHTML = name;
document.querySelector('#b').innerHTML = name.length;</script>
</body>
You could get away with something as short as this:
<script>
const name = prompt("What's your name?") ?? "";
document.write(`<p>${name.length}</p>`);
</script>
It's not a very clean way of doing it but using document.write is not much worse than calling prompt() as soon as the page loads.
A more user-friendly approach would be to have an actual text input on the page and to dynamically update the length as they type using an event listener.
<label>Name: <input id="name-input"></label><br>
Length: <output id="name-length-output" for="name-input">0<output>
<script type="module">
const nameInput = document.getElementById("name-input");
const nameLengthOutput = document.getElementById("name-length-output");
nameInput.addEventListener("input", e => {
nameLengthOutput.textContent = nameInput.value.length;
});
</script>
If you want to learn how to manipulate pages with JavaScript, the Mozilla Developer Network has a good tutorial about the DOM.

Toggle text with JavaScript

I am learning JavaScript.
I am trying toggle the text on a page using the replaceChild() method. I came up with the code below. I don't understand why it will not work. Pls help.
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
if (b4[0].innerHTML=="Before"){
be.replaceChild(l8,b4[0])
}
if (b4[0].innerHTML=="After") {
be.replaceChild(l88,b4[0]);
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>
As CBrone wrote, you have to create h1 instance first, store it to variable and then call innerHML on the variable.
Another problem is if structure. First you replace the element and then test the same element for another condition and do another operation. In this case is better to use if ... else if ... statement instead of if ... if ..., which is the root of your problem.
Here is working toggleText function
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1");
var l8 = document.createElement("h1");
l8.innerHTML="After";
var l88 = document.createElement("h1");
l88.innerHTML="Before";
if (b4[0].innerHTML == "Before")
{
be.replaceChild(l8, b4[0]);
}
else if (b4[0].innerHTML=="After")
{
be.replaceChild(l88, b4[0]);
}
}
Here is working fiddle
In addition to what’s been said in comments already:
var l8 = document.createElement("h1").innerHTML="After";
var l88 = document.createElement("h1").innerHTML="Before";
After this your variables do not contain references to the created elements, but the string values that you assigned to their innterHTML. (The result of an assignment operation is the assigned value.) And trying to pass text values instead of element references to replaceChild afterwards must fail for that reason.
Do this in two steps – create the elements first and save their reference into the variables – and then manipulate their innerHTML afterwards.
var l8 = document.createElement("h1");
l8.innerHTML="After";
var l88 = document.createElement("h1");
var l88 = .innerHTML="Before";
(And maybe use better suited variable names, because if you keep your current “naming scene” up you’ll get confused sooner or later.)
May I suggest the following, for better readability:
<html>
<head>
<script>
function toggleText() {
var be= document.getElementById("main");
var b4= be.getElementsByTagName("h1")[0];
if (b4.innerHTML=="Before") {
b4.innerHTML = "After";
}
else if (b4.innerHTML=="After") {
b4.innerHTML = "Before";
}
}
</script>
</head>
<body>
<div id="main" onclick="toggleText()">
<h1>Before</h1>
</div>
</body>
</html>

How to grab text from URL and place in JS array?

I've stated previously that I am very new to JavaScript and HTML. I'm creating a small search tool and I'm very confused as to how to get text from a URL and put it in my JS array.
For example, let's say the URL is: http://www.somethingrandom.com/poop
In that URL, there's a couple of words: "something", "everything", "nothing"
Literally just that. It's in a pre tag in HTML, and that's it.
Now, my JS code, I want it to open up that URL, and take those words and place them in a string/list/array, whatever, it could be anything as long as it can happen, I can manipulate it further later.
I have this so far:
<html>
<head>
<script type = "text/javascript">
function getWords(){
var url = "http://www.somethingrandom.com/poop"
var win = window.open( url );
window.onload = function(){
var list = document.getElementsByTagName("pre")[0].innerHTML;
var listLength = list.length;
alert( listLength);
}
}
</script>
</head>
<body>
<button id="1" onClick="getWords();">Click Here</button>
</body>
</html>
It doesn't work however.. And I'm not sure why. :( Please help.
Make an AJAX request and you will have access to the returned content.
Using jQuery:
function getWords(){
var url = "http://www.somethingrandom.com/poop"
$.get(url, function(data) {
var list = $('pre:eq(0)', data).html;
var listLength = list.length;
alert( listLength);
}, 'html');
}

Categories

Resources