new line in JS-function - javascript

I would like to get a longer string with line breaks, but it's not working with all the common commands like \n, \r\n, ... Also not with HTML-Tags for breaking a line.
I am new to the ASP-Framework and JS-Scripting and I can't find the solution on my own. Till now I didn't find the right hint on the internet, you can help me when you have a look at my specific code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DataGen App</title>
</head>
<body>
<div>
<h3>Mitarbeiter</h3>
</div>
<div>
<input type="button" value="generateSQL" onclick="generate();" />
<p id="ma" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/mitarbeiter';
function formatItem(item) {
return 'INSERT INTO Mitarbeiter VALUES (' + item.Id + ', ' + item.Name + ', ' + item.Vorname + ', ' + item.Bereich + ');';
}
function generate() {
var str = "";
$.getJSON(uri)
.done(function (data) {
$.each(data, function (key, item) {
str = str + "\n" + formatItem(item);
$('#ma').text(str);
});
})
}
</script>
</body>
</html>
The line break should be generated in the last function.
Thank's a lot and have a nice week!

You can use <br> tag. The <br> tag inserts a single line break.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>DataGen App</title>
</head>
<body>
<div>
<h3>Mitarbeiter</h3>
</div>
<div>
<input type="button" value="generateSQL" onclick="generate();" />
<p id="ma" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/mitarbeiter';
function formatItem(item) {
return 'INSERT INTO Mitarbeiter VALUES (' + item.Id + ', ' + item.Name + ', ' + item.Vorname + ', ' + item.Bereich + ');';
}
function generate() {
var str = "";
$.getJSON(uri)
.done(function (data) {
console.log(data);
$.each(data, function (key, item) {
str = str + "<br>" + formatItem(item);
$('#ma').html(str);
});
})
}
</script>
</body>
</html>

Related

Numeric to alphabet code is not working in Javascript

Recently I made a function called Converter. It was working perfectly in the morning and now when I am using it, the code is not being able to run when I type numeric like 3 it should print like Three but I do now know what is the problem and problem also not showing. I am new in Javascript
Here is the code
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function abc()
{
// alert('hello');
var amt=parseInt(document.getElementById('t1'));
var d="";
var ones=Array("","One","Two","Three","four","five");
var tens=Array("","","Twenty","Thirthy","Fourthy","fifthy");
var hundreds=Array("","One hundred","Two hundred","Three hundred","Four hundred","Five hundred");
if(amt>=1&&amt<=19)
{
d=ones[amt];
}
document.getElementById('p1').innerHTML=d;
// document.write(d);
}
</script>
</head>
<body>
<input type="text" id="t1" />
<input type="button" value="Convert" onclick="abc()" />
<p id="p1"></p>
</body>
</html>
You forgot to parse the value of textbox
it should be
document.getElementById('t1').value
In addition to my comment on not grabbing the value.
Use let amt = document.getElementById('t1').value. This returns the value inside the input.
Someone made a good example for what you are trying to do here: Convert digits into words with JavaScript
var a = ['', 'one ', 'two ', 'three ', 'four ', 'five ', 'six ', 'seven ', 'eight ', 'nine ', 'ten ', 'eleven ', 'twelve ', 'thirteen ', 'fourteen ', 'fifteen ', 'sixteen ', 'seventeen ', 'eighteen ', 'nineteen '];
var b = ['', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'];
function inWords(num) {
if ((num = num.toString()).length > 9) return 'overflow';
n = ('000000000' + num).substr(-9).match(/^(\d{2})(\d{2})(\d{2})(\d{1})(\d{2})$/);
if (!n) return;
var str = '';
str += (n[1] != 0) ? (a[Number(n[1])] || b[n[1][0]] + ' ' + a[n[1][1]]) + 'crore ' : '';
str += (n[2] != 0) ? (a[Number(n[2])] || b[n[2][0]] + ' ' + a[n[2][1]]) + 'lakh ' : '';
str += (n[3] != 0) ? (a[Number(n[3])] || b[n[3][0]] + ' ' + a[n[3][1]]) + 'thousand ' : '';
str += (n[4] != 0) ? (a[Number(n[4])] || b[n[4][0]] + ' ' + a[n[4][1]]) + 'hundred ' : '';
str += (n[5] != 0) ? ((str != '') ? 'and ' : '') + (a[Number(n[5])] || b[n[5][0]] + ' ' + a[n[5][1]]) + 'only ' : '';
return str;
}
document.getElementById('number').onkeyup = function() {
document.getElementById('words').innerHTML = inWords(document.getElementById('number').value);
};
<span id="words"></span>
<input id="number" type="text" />
Your bug was caused of this line: parseInt(document.getElementById('t1'));
You were trying to parseInt(html input element). There is no way to parse HTML value to int, so it was returning NaN, which cannot be converted to "Three" or any other number.
Here's working code:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function abc()
{
var amt=document.getElementById('t1').value;
var d="";
var ones=Array("","One","Two","Three","four","five");
var tens=Array("","","Twenty","Thirthy","Fourthy","fifthy");
var hundreds=Array("","One hundred","Two hundred","Three hundred","Four hundred","Five hundred");
if(amt>=1&&amt<=19)
{
d=ones[amt];
}
document.getElementById('p1').innerHTML=d;
// document.write(d);
}
</script>
</head>
<body>
<input type="text" id="t1" />
<input type="button" value="Convert" onclick="abc()" />
<p id="p1"></p>
</body>
</html>

Nested JSON to HTML in JavaScript

I have a json file and I'd like to display it:
Item 1
- Subitem 1.1
- Subitem 1.2
...
Item 2
...
etc.
I have
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
$.getJSON("file.json", function(result){
$.each(result.items, function(key, val){
$("#01").append('<p>' + val.item + '</p>');
var id_item;
id_item = '0' + key;
$.each(val.subitems, function(key, val){
$("#02").append('<p><input type="radio" name =' + id_item + ' id =' + key + '>' + val.content + '</input></p>');
});
});
});
});
</script>
Home
<div position="relative" id="01">
<div position="absolute" id="02"></div>
</div>
</body>
</html>
and the result I get is:
Subitem 1.1
Subitem 1.2
...
etc.
Item 1
Item 2
...
etc.
thank you
This snippet shows how you can transform a simple JS object into a HTML representation - does this help?
var items = {
foo: {
bar: 1,
baz: 2,
},
foobar: 3
}
$.each(items, function(key, val){
$("#01").append('<p>' + key + '</p>');
$.each(val, function(key, val){
$("#01").append('<p>- ' + key + ':' + val + '</p>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="01">
</div>
If all you need to do is display print out the data on the page:
var data = [
{key: [1,2,3]}
];
// Clean output, with 4 indentation spaces
var string = JSON.stringify(data, null, ' ');
$('body').append('<pre>' + string + '</pre>');
// Remove brackets
var noBrackets = string.replace(/[,\[\]:{}]/gi, '');
$('body').append('<pre>' + noBrackets + '</pre>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Geo Location Trace getElementById not working

I am working on a challenge by freecodecamp, Task is to show the local weather and hence I have to get the location of the user. I can get the location from here but after printing that i was trying to getElementById of a div i have printed using JS which gives null in response. I want to get the key value pair so that i can do stuff with them. Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Location Trace | freecodecamp Challanges</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="GeoResults"></div>
<script>
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
var count = 0;
$.each(data, function(k, v) {
//JSON.stringify(j); // '{"name":"binchen"}'
table_body += '<div id=Coun_'+count+'>'+v+'</div>';
//table_body += "<tr><td id='FC_"+count+"'>" + k + "</td><td><b id='SC_"+count+"'>" + v + "</b></td></tr>";
count++;
});
$("#GeoResults").html(table_body);
});
</script>
<script>
var x = document.getElementById('Coun_1') /*= 'Dooone!!!'*/;
console.log(x);
</script>
</body>
</html>
Thanks in Advance!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Location Trace | freecodecamp Challanges</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div id="GeoResults"></div>
<script>
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
var count = 0;
$.each(data, function(k, v) {
//JSON.stringify(j); // '{"name":"binchen"}'
table_body += '<div id=Coun_'+count+'>'+v+'</div>';
//table_body += "<tr><td id='FC_"+count+"'>" + k + "</td><td><b id='SC_"+count+"'>" + v + "</b></td></tr>";
count++;
});
$("#GeoResults").html(table_body);
var x = document.getElementById('Coun_1').innerHTML; /*= 'Dooone!!!'*/;
console.log(x);
});
</script>
</body>
</html>

How do I see what data AJAX is passing

I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.

AJAX is not passing data via POST to its intended URL

I want to pass an array through AJAX but I am not getting any feed back on what it is I am sending. I tried to do a var_dump($_POST); on the PHP side (next.php) but nothing is showing up. I'm guessing there is something wrong with my code.
function sendToServer(data) {
$.ajax({
type: "POST",
data: { arr: JSON.stringify(data) },
url: "next.php",
success: function() {}
});
}
next.php:
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']));
foreach ($data as $item) {
echo $item;
// insert to db
}
?>
Full snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem is when you try to echo the item. As $item is an object (stdClass), and the echo command expects a string, the echo command fails with "stdClass could not be converted to a string". You can either change to:
echo print_r($item, true);
or:
var_dump($item);

Categories