Array Display and Alert Function - javascript

I am using the Chicago Employee Data to push the results of Chicago Employee's Salary Information as well as departments. I've been able to get the name and salary to work, but can't seem to get the Department part to work.
Additionally, I am trying to make an alert if there are no matching names after searching for them, but my alert doesn't work either. I don't want anyone to do the code for me, just tell me what I'm doing wrong!
ChicagoEmployeesQuery = function(searchKey) {
var url,
url =
"https://data.cityofchicago.org/api/views/xzkq-xp2w/rows.json" +
"?search=key_word&jsonp=?";
this.query = url.replace("key_word", searchKey);
}
ChicagoEmployeesQuery.prototype.getList = function(callBack) {
$.getJSON(this.query, function(response) {
var i, results;
results = [];
for (i = 0; i < response.data.length; i += 1) {
row = {
name: response.data[i][8],
title: response.data[i][9],
department: response.data[i][10],
salary: response.data[i][14]
}
results.push(row);
}
callBack(results);
})
}
<!doctype html>
<html>
<head>
<title>Salary Info Demo</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="ChicagoEmployees.js"></script>
<script src="demoLS.js"></script>
</head>
<body>
<h1>Salary Info</h1>
<p>Enter first or last name: <input type="text" id="key-word" size="20" /></p>
<p><input type="button" id="start" value="Submit Query" /></p>
<h2>First Matching Employing and Salary</h2>
<div id="result">
First result appears here
</div>
<h2>List of All Matching Names</h2>
<div id="names">
All Matching Names Appear Here
</div>
<h2>List of All Matching Names + Departments</h2>
<div id="namesDepartment">
All Matching Names + Departments Appear Here
</div>
</body>
</html>
postResult = function(list) {
//var nameList, i, glist;
glist = list;
if (list.length > 0) {
$("#result").html(list[0].name + "<br />" + list[0].salary);
}
postResult = function(list) {
//var namesDepartmentList, i, glist;
glist = list;
if (list.length > 0) {
$("#namesDepartment").html(list[0].name + "<br />" + list[0].department);
}
}
nameList = "";
for (i = 0; i < list.length; i += 1) {
nameList = nameList + list[i].name + "<br />";
}
$("#names").html(nameList);
namesDepartmentList = "";
for (i = 0; i < list.length; i += 1) {
namesDepartmentList = nameList + list[i].name + "<br />";
}
$("#namesDepartment").html(namesDepartmentList);
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#result").html("waiting...");
query.getList(postResult);
if (key_word.isEmpty()) {
alert("No Matching Records Found");
}
}
submit = function() {
var searchWord = document.getElementById("key-word").value;
query = new ChicagoEmployeesQuery(searchWord);
$("#namesDepartment").html("waiting...");
query.getList(postResult);
}
$(function() {
$("#start").click(submit);
});

Related

How do I add up all numbers into one variable and show it?

Whenever I try doing the code myself, nothing shows up after I run the function, I'm wanting to add all the numbers from 'fkWynik'.
function mat_WypiszLiczbyNaturalne() {
var T = "";
T = document.getElementById('fkEdit').value;
if ((T.trim() != "") && (Number(T) > 0)) {
var S = "";
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
}
document.getElementById('fkWynik').value = S.substr(2) + " = ";
} else {
document.getElementById('fkWynik').value = "Prosze wprowadzic liczbe!";
}
}
<html>
<body>
<FORM NAME="formularz1" ACTION="">
<TABLE BORDER="0">
<INPUT TYPE="number" ID="fkEdit" STYLE="height:24px; width:55px;">
<INPUT TYPE="button" ID="fkWykonaj" VALUE="Wykonaj" onClick="mat_WypiszLiczbyNaturalne();"> </TD>
</TR>
<TR><TD> <INPUT TYPE="text" ID="fkWynik" STYLE="width:545px; height:24px;" READONLY> </TD></TR>
</TABLE>
</FORM>
</body>
</html>
You need to add the numbers together and concat it to the string:
function mat_WypiszLiczbyNaturalne() {
var T = "";
T = document.getElementById('fkEdit').value;
if ((T.trim() != "") && (Number(T) > 0)) {
var S = "";
var total = 0
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
total += I;
}
document.getElementById('fkWynik').value = S.substr(2) + " = "+total.toString();
} else {
document.getElementById('fkWynik').value = "Prosze wprowadzic liczbe!";
}
}
<html>
<body>
<FORM NAME="formularz1" ACTION="">
<TABLE BORDER="0">
<INPUT TYPE="number" ID="fkEdit" STYLE="height:24px; width:55px;">
<INPUT TYPE="button" ID="fkWykonaj" VALUE="Wykonaj" onClick="mat_WypiszLiczbyNaturalne();"> </TD>
</TR>
<TR><TD> <INPUT TYPE="text" ID="fkWynik" STYLE="width:545px; height:24px;" READONLY> </TD></TR>
</TABLE>
</FORM>
</body>
</html>
The following should work if your HTML code contains an element with the property id="fkWynik"
function mat_WypiszLiczbyNaturalne() {
var elem = document.getElementById('fkEdit');
if(!elem) {
console.error("No element with id 'fkEdit' in the page.");
return;
}
var T = elem.value;
var value = "";
if (T && !isNaN(Number(T))) { // if T not null, not empty, not undefined, not 0 and is a number
var S = "";
for (var I = 1; I < Number(T) + 1; I++) {
S = S + ", " + I.toString();
}
value = S.substr(2) + " = ";
} else {
value = "Proszę wprowadzić liczbę!";
}
console.log("value: " + value);
document.getElementById('fkWynik').value = value;
}
mat_WypiszLiczbyNaturalne();

How to design UI for multiple selection in a drop down list?

I'm setting up a UI for my application. I would like to have some idea about your guy's experiences.
I need to have multiple selections from different sources.
Input (Sources): Companies, Department. Multiple companies, departments allowed.
Output: People who belong to selected items
For example, I can select company1, company2, and select department1, department2 from a dropdown list.
I select one by one property( Select company1, company2, then go to another dropdown to select department1,2...)
In the end, I have company1,2,3 checked, department 1,2,3 checked.
Then the result will tell me user1...n belong to the selected list above.
The problem is nothing if I have only a few company and department but if coming to be complicated if I have multiple (more than 6 companies and departments). I can't come up with any good UI design for this problem.
I expected the output of (selected(checked company1,2,3... + department1,2,3)) -> result person1,2,3 belong to checked items.
Try the following code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Select Company: </p>
<select name="companySelector" multiple>
</select>
<p>Select Department: </p>
<select name="departmentSelector" multiple>
</select>
<p>Persons: </p>
<ul id="persons">
</ul>
<script>
var companySelector = document.querySelector("[name='companySelector']");
var departmentSelector = document.querySelector("[name='departmentSelector']");
var persons = document.getElementById("persons");
var temp, temp2 = 0;
var database = {
company_1: {
c1_department1: ["c1d1person1", "c1d1person2", "c1d1person3", "c1d1person4"],
c1_department2: ["c1d2person1", "c1d2person2", "c1d2person3", "c1d2person4"],
c1_department3: ["c1d3person1", "c1d3person2", "c1d3person3", "c1d3person4"]
},
company_2: {
c2_department1: ["c2d1person1", "c2d1person2", "c2d1person3", "c2d1person4"],
c2_department2: ["c2d2person1", "c2d2person2", "c2d2person3", "c2d2person4"],
c2_department3: ["c2d3person1", "c2d3person2", "c2d3person3", "c2d3person4"]
},
company_3: {
c3_department1: ["c3d1person1", "c3d1person2", "c3d1person3", "c3d1person4"],
c3_department2: ["c3d2person1", "c3d2person2", "c3d2person3", "c3d2person4"],
c3_department3: ["c3d3person1", "c3d3person2", "c3d3person3", "c3d3person4"]
},
company_4: {
c4_department1: ["c4d1person1", "c4d1person2", "c4d1person3", "c4d1person4"],
c4_department2: ["c4d2person1", "c4d2person2", "c4d2person3", "c4d2person4"],
c4_department3: ["c4d3person1", "c4d3person2", "c4d3person3", "c4d3person4"]
},
company_5: {
c5_department1: ["c5d1person1", "c5d1person2", "c5d1person3", "c5d1person4"],
c5_department2: ["c5d2person1", "c5d2person2", "c5d2person3", "c5d2person4"],
c5_department3: ["c5d3person1", "c5d3person2", "c5d3person3", "c5d3person4"]
}
}
for (temp in database) {
companySelector.innerHTML += '<option value="' + temp + '">' + temp.replace(/_/g, " ") + '</option>';
}
companySelector.onchange = function() {
departmentSelector.innerHTML = "";
var selectedCompnies = document.querySelectorAll("[name='companySelector'] option:checked");
for (var i = 0; i < selectedCompnies.length; i++) {
for (temp2 in database[selectedCompnies[i].value]) {
departmentSelector.innerHTML += '<option value="' + temp2 + '" data-company="' + selectedCompnies[i].value + '">' + temp2.replace(/_/g, " ") + '</option>'
}
}
}
departmentSelector.onchange = function() {
persons.innerHTML = "";
var selectedDepartments = document.querySelectorAll("[name='departmentSelector'] option:checked");
for (var i = 0; i < selectedDepartments.length; i++) {
var temp3 = selectedDepartments[i].dataset.company;
var prsonsArray = database[temp3][selectedDepartments[i].value];
for (var x = 0; x < prsonsArray.length; x++) {
persons.innerHTML += "<li>" + prsonsArray[x] + "</li>";
}
}
}
</script>
</body>
</html>
DEMO

Read formatted text from form through javascript

class Storedata {
constructor(name, desc, price, qty) {
this.name = name;
this.desc = desc;
this.price = price;
this.qty = qty;
}
}
var arr = [];
var btnform = document.getElementById('clicktoadd');
var btnlist = document.getElementById('clicktoshow');
var rem = document.getElementById('main');
var cancelform;
var submit;
function addData() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
arr.push(new Storedata(proname.value, prodesc.value, propric.value, proqty.value));
}
function showlist() {
var data = document.createElement('table');
data.setAttribute("id", "data");
data.innerHTML += "<tr><th>Product Name</th><th>Description</th><th>Price</th><th>Quantity</th><th></th></tr>";
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td>" + arr[i].desc + "</td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
document.getElementById('listing').appendChild(data);
document.getElementById('showbutton').removeAttribute("hidden", false);
}
function removelist() {
var data = document.getElementById("data");
data.parentNode.removeChild(data);
}
function addformtopage() {
var form = document.createElement('div');
form.setAttribute("id", "remform");
form.innerHTML += "<div id=\"lblname\">Product Name:</div><input id=\"inpname\" type=\"text\"><div id=\"chkname\" hidden=\"true\">Enter a Product Name</div><div id=\"lbldesc\">Description:</div><textarea id=\"inpdesc\" rows=\"10\" cols=\"35\"></textarea><div id=\"chkdesc\" hidden=\"true\">Enter a Product Desciption</div><div id=\"lblprice\">Price in INR:</div><input id=\"inpprice\" type=\"number\"><div id=\"chkprice\" hidden=\"true\">Enter a Product Price</div><div id=\"lblqty\">Quantity:</div><input id=\"inpqty\" type=\"number\"><div id=\"chkqty\" hidden=\"true\">Enter a Product Quantity</div><br><br><button id=\"submitproduct\">Submit</button><button id=\"cancel\">Cancel</button>";
document.getElementById('panel').appendChild(form);
cancelform = document.getElementById('cancel');
submit = document.getElementById('submitproduct');
}
function validateform() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
var errname = document.getElementById("chkname");
var errdesc = document.getElementById("chkdesc");
var errpric = document.getElementById("chkprice");
var errqty = document.getElementById("chkqty");
if ((proname.value) && (prodesc.value) && (propric.value) && (proqty.value)) {
errname.setAttribute("hidden", true);
errdesc.setAttribute("hidden", true);
errpric.setAttribute("hidden", true);
errqty.setAttribute("hidden", true);
return true;
}
if (proname.value) {
errname.setAttribute("hidden", true);
}
if (prodesc.value) {
errdesc.setAttribute("hidden", true);
}
if (propric.value) {
errpric.setAttribute("hidden", true);
}
if (proqty.value) {
errqty.setAttribute("hidden", true);
}
if (!proname.value) {
errname.removeAttribute("hidden", false);
}
if (!prodesc.value) {
errdesc.removeAttribute("hidden", false);
}
if (!propric.value) {
errpric.removeAttribute("hidden", false);
}
if (!proqty.value) {
errqty.removeAttribute("hidden", false);
}
return false;
}
function clearform() {
var proname = document.getElementById("inpname");
var prodesc = document.getElementById("inpdesc");
var propric = document.getElementById("inpprice");
var proqty = document.getElementById("inpqty");
proname.value = null;
prodesc.value = null;
propric.value = null;
proqty.value = null;
}
function removeform() {
var elem = document.getElementById("remform");
elem.parentNode.removeChild(elem);
}
function removebuttons() {
rem.setAttribute("hidden", true);
}
function showbuttons() {
rem.removeAttribute("hidden", false);
}
btnform.addEventListener('click', function() {
addformtopage();
removebuttons();
cancelform.addEventListener('click', function() {
showbuttons();
removeform();
});
submit.addEventListener('click', function() {
if (validateform()) {
alert("Values Added");
addData();
clearform();
}
});
});
btnlist.addEventListener('click', function() {
showlist();
removebuttons();
document.getElementById('showbutton').addEventListener('click', function() {
showbuttons();
removelist();
document.getElementById('showbutton').setAttribute("hidden", "true");
});
});
#chkname,
#chkdesc,
#chkprice,
#chkqty {
color: red;
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 70%;
}
td,
th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
<!DOCTYPE HTML>
<html>
<head>
<link href="style.css" rel="stylesheet" />
<title>
JS Form
</title>
</head>
<body>
<div id="main">
<p><button id="clicktoadd">Add Product</button> <button id="clicktoshow">Show List</button></p>
</div>
<div id="panel">
</div>
<div id="listing">
</div>
<button id="showbutton" hidden="true">< Back</button>
<script src="script.js"></script>
</body>
</html>
I want to take input in form for description of the item as formatted text. And then output it in the same format as input, but right now I am getting text separated by space where should be there. Please help..
Steps to perform
1. Run this code snippet.
2. Click on 'Add Product' button.
3. Fill the form (For testing give a description of more than one line) and Submit.
4. Click on 'Cancel' button to return.
5. Click on 'Show List' button.
6. Observe Description column.
This is output I am getting separated by spaces
This is form input I am providing
Well, you have two options. Add a <pre> tag:
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td><pre>" + arr[i].desc + "</pre></td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
This way it will display the new lines and you keep your string clean.
Or you can replace the new lines with <br> this way:
for (let i = 0; i < arr.length; i++) {
data.innerHTML += ("<tr><td>" + arr[i].name + "</td><td>" + arr[i].desc.replace(/\n/g, "<br>") + "</td><td>" + arr[i].price + "</td><td>" + arr[i].qty + "</td><td><button id=\"delete" + i + "\">Delete</button></tr>");
};
Remember that the new lines are not shown by default in HTML, if you want a new line put a <br>
Test it online
Hope it helps! :)
Add this into your code:
var text = arr[i].desc;
text = text.replace(/\n/g, '<br />');
JSfiddle
See JavaScript: How to add line breaks to an HTML textarea? too.

Don't show the correct value JAVASCRIPT ARRAY

Today I was working to script, when I wanted to test it, I could see that it didn't works correctly it show the value [object Object] and not the real value (It didn't change the value too). It shows: Click here for see the picture
Its necessary click on "Edit" near of Google or Yahoo. I want to show the correct value when I click "Edit" near Google and Edit it when I click edit. I tried to change the value Checked[Item] for Checker[Name] but it only shows undefined.
html:
<!DOCTYPE html>
<html>
<head>
<title>SSL Checker</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/script.js"></script>
<script type="text/javascript" src="js/json.json" charset="utf-8"></script>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
js:
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = Checker[item];
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el.value;
if (url) {
self.Checker.splice(item, 1, name.trim());
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
json:
var Checker = [{
name:"Google",
url: "google.es",
},
{
name:"Yahoo",
url: "yahoo.com",
}
]
Add another input tag for each attribute of Checkers objects.
<input type="text" id="edit-name">
<input type="text" id="edit-url">
And set each input separately
var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;
Working code:
var Checker = [{
name: "Google",
url: "google.es",
},
{
name: "Yahoo",
url: "yahoo.com",
}
]
document.getElementById('edit').style.display = 'none';
function start() {
var SSL = new function() {
//List urls to check
this.el = document.getElementById('urls');
this.Count = function(data) {
var el = document.getElementById('counter');
var name = 'url';
if (data) {
if (data > 1) {
name = 'urls';
}
el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
} else {
el.innerHTML = 'No ' + name;
}
};
//Buttons configuration
this.FetchAll = function() {
var data = '';
if (Checker.length > 0) {
for (i = 0; i < Checker.length; i++) {
data += '<tr>';
data += '<td>' + Checker[i].name + '</td>';
data += '<td><button onclick="SSL.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="SSL.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(Checker.length);
return this.el.innerHTML = data;
};
//Add name
this.Add = function() {
el = document.getElementById('add-name');
el1 = document.getElementById('add-link')
var url = el.value;
var url1 = el1.value;
if (url) {
if (url) Checker.push({
"name": url,
"url": url1
})
el.value = '';
this.FetchAll();
}
}
//Edit
this.Edit = function(item) {
var el = document.getElementById('edit-name');
el.value = Checker[item].name;
var el2 = document.getElementById('edit-url');
el2.value = Checker[item].url;
document.getElementById('edit').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function() {
var url = el2.value;
var name = el.value;
if (url && name) {
Checker[item].name = name;
Checker[item].url = url;
self.FetchAll();
CloseInput();
}
}
};
//Delete
this.Delete = function(item) {
Checker.splice(item, 1);
this.FetchAll();
};
};
SSL.FetchAll();
function CloseInput() {
document.getElementById('edit').style.display = 'none';
}
window.CloseInput = CloseInput;
window.SSL = SSL;
}
<html>
<head>
<title>SSL Checker</title>
</head>
<body onLoad="start()">
<div id="title">
<h1>SSL Checker</h1>
</div>
<div id="data">
<form action="javascript:void(0);" method="POST" onsubmit="SSL.Add()">
<input type="text" id="add-name" placeholder="Name"></input>
<input type="text" id="add-link" placeholder="Link"></input>
<input type="submit" value="Add">
</form>
<div id="edit" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-url">
<input type="submit" value="Edit" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
</div>
<div id="table">
<table style="overflow-x:auto;">
<tr>
<th>Sites:</th>
</tr>
<tbody id="urls">
</tbody>
</table>
</div>
</body>
</html>
You are getting correct output with [object Object], because Object.toString() returns exactly [object Object].
To represent your object in a custom format you can change the part of your SSL.Edit() method where you do el.value = Checker[item] to something like
el.value = Checker[item].name; // To show the name
el.value = Checker[item].url; // To show the url
el.value = Checker[item].url + ' ' + Checker[item].url; // To show both

How do I insert an object data array into a database with AJAX

I want to insert data from an array into a database table in the submit() function where the sql syntax is at. I want to insert the data then redirect to another page after successful. I don't know how to do this with ajax.
I tried to make ajax syntax but I don't know if i'm passing the data correctly for obj.name and obj.books corresponding to their own values in the array.
example:
[{"name":"book1","books":["thisBook1.1","thisBook1.2"]},{"name":"book2","books":["thisBook2.1","thisBook2.2","thisBook2.3"]}]
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);
});
//sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
//mysqli_query(sql);
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
/////////////////////////////////
//I tried this:
$.ajax({
type: "POST",
data: {arr: arr},
url: "next.php",
success: function(){
}
});
/////////////////////////////////
<!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 + '\')" style="font-size: 20px; background-color: red; cursor:pointer; margin-left:1%;">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
//var val = confirm("Are you sure ..?");
//if(val){
$("#" + 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);
});
// sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
// mysqli_query(sql);
arr.push(obj);
}
$("#result").html(JSON.stringify(arr));
}
</script>
</body>
</html>
Send your array to server ,stringify array before sending it to server so in server you can decode json and recover your array, and then insert received data to database
JS
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);
});
//sql = ("INSERT INTO table (author, book) VALUES ('obj.name', 'obj.books')");
//mysqli_query(sql);
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(){
}
});
}
PHP (next.php)
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $d;
// insert to db
}
Please Keep the following in mind
Javascript/JQuery is client side and hence cannot access the database which is on the server.
You can Send data via AJAX to next.php and then use this data to insert into your database.
To improve debugging, use the following code to ensure the correct data is being delivered in next.php
var_dump($_POST);
Your SQL statements must be executed in next.php using the data passed by $_POST (since your "type" of AJAX request is post).

Categories

Resources