getJSON JSON Array - Search Functionality Crashing Client - javascript

I'm running into a problem when trying to add in the search functionality, showList().
It seems to bog down the client so much that Chrome wants to kill the page each time I type into the input field. I'm clearly a novice JS writer, so could I be running an infinite loop somewhere I don't see? Also, any advice to get the search functionality working properly would be hugely appreciated. I don't think I'm using the correct selectors below for the show/hide if statement, but I can't think what else to use.
$(document).ready(function(){
showList();
searchBar();
});
function showList() {
$("#show-records").click(function(){
$.getJSON("data.json", function(data){
var json = data;
$("show-list").append("<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
$("#show-list").append("<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>");
$("show-list").append("</table>");
}
//end getJSON inner function
});
//end click function
});
//end showList()
};
function searchBar() {
//AJAX getJSON
$.getJSON("data.json", function(data){
//gathering json Data, sticking it into var json
var json = data;
for(var i = 0; i < json.length; i++) {
//putting the json objects into var obj
var obj = json[i];
function contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
//whenever anything is entered into search bar...
$('#search').keyup(function(obj) {
//grab the search bar content values and...
var searchEntry = $(this).val().toLowerCase();
//grab each td and check to see if it contains the same contents as var searchEntry - if they dont match, hide; otherwise show
$("td").each(function() {
if (!contains($(this).text().toLowerCase(), searchEntry)) {
$(this).hide(400);
} else {
$(this).show(400);
};
})
})
}
});
};
body {
background-color: lightblue;
}
tr:first-child {
font-weight: bold;
}
td {
padding: 3px;
/*margin: 10px;*/
text-align: center;
}
td:nth-child(6) {
padding-left: 50px;
}
td:nth-child(7) {
padding-left: 10px;
padding-right: 10px;
}
#filter-count {
font-size: 12px;
}
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="javascript" src="process.js"></script>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
</head>
<body>
<a href="#" id='show-records'>Show Records</a><br>
<label id="searchBar">Search: <input id="search" placeholder="Enter Specialist Name"></label>
<span id="search-count"></span>
<div id="show-list"></div>
</body>
</html>

Problem appears to be that you can't treat append as if it was a text editor and you are writing html.
Anything that gets inserted needs to be a proper element ... not a start tag, then some text...then a close tag.
We can however modify your code slightly to produce html strings and then add that at the end
$.getJSON("data.json", function(data){
var json = data;
var html="<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
html+= "<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>";
}
html+= '</table>';
$("#show-list").html(html);
//end getJSON inner function
});

Related

Trouble with script-generated dynamic html element

I developing comment section for my HTMl page. I place it in div container in body section in my page, like that:
<body>
...
<div id='commentsTree'></div>
...
</body>
Commment section generated by script, here it is
function createCommentsTree(commentsData) {
resultHTML = "";
let commentsArray = JSON.parse(commentsData);
//let result = "";
resultHTML = resultHTML + "<ul id='myUL'>";
commentsArray.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
});
resultHTML = resultHTML + "</ul>";
return resultHTML;
}
function createCommentsTreeHyerarchycally(source) {
resultHTML = resultHTML + "<ul class='nested'>";
source.subordinates.forEach(element => {
if (element.hasOwnProperty("subordinates")){
resultHTML = resultHTML + "<li>" +
"<span class='caret'></span><textarea class='textFieldRoot'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>";
createCommentsTreeHyerarchycally(element);
resultHTML = resultHTML + "</li>";
}
else{
resultHTML = resultHTML + "<li>" +
"<textarea class='textField'>" + element.content + "</textarea>" +
"<div align='right'>" +
"<button>Save</button>" +
"<button>Answer</button>" +
"<button>Delete</button>" +
"</div>" +
"</li>";
}
})
resultHTML = resultHTML + "</ul>";
}
in result i have hyerarchycally comments tree, you can see it on example here
https://jsfiddle.net/Obliterator/wogurs6L/, or, on picture "comment section" added below.
On picture you can see "caret" symbol, looks like black small arrow near textareas, i mark it on picture. When i click it, comment line must unfold, and show subordinate comment lines. You can try it in example here https://jsfiddle.net/Obliterator/wogurs6L/, in this example it works totally correct. But, in my web page, when i click on "caret" symbol, nohing happens, comment line do not unfold. And this is a problem.
For unfold by clicking "caret" symbol i make this script and css:
script:
var toggler = document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
css:
/* Remove default bullets */
ul, #myUL {
list-style-type: none;
}
.textFieldRoot {
position: relative;
left: 15px;
width: 100%;
}
.textField {
position: relative;
width: 100%;
}
/* Remove margins and padding from the parent ul */
#myUL {
margin: 0;
padding: 0;
}
/* Style the caret/arrow */
.caret {
cursor: pointer;
user-select: none; /* Prevent text selection */
position: absolute;
}
/* Create the caret/arrow with a unicode, and style it */
.caret::before {
content: "\25B6";
color: black;
display: inline-block;
margin-right: 6px;
vertical-align: top;
}
/* Rotate the caret/arrow icon when clicked on (using JavaScript) */
.caret-down::before {
transform: rotate(90deg);
}
/* Hide the nested list */
.nested {
display: none;
}
/* Show the nested list when the user clicks on the caret/arrow (with JavaScript) */
.active {
display: block;
}
i add css and script in my page, for which i trying add comment section, that way (treeListScript.js and treeListStyle.css):
<head>
...
<script type="text/javascript" src="http://localhost/testapp/lib/others/treeList/treeListScript.js"></script>
<link rel="stylesheet" href="http://localhost/testapp/lib/others/treeList/treeListStyle.css">
...
</head>
<body>
...
<div id='commentsTree'></div>
...
</body>
i create my web page this way:
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
line windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments); creates comment section.
So, what i am doing wrong, what i mus do for my unfold fucntional works correct on my web page? If something unclear, ask, i try explain.
I solve problem by myself. Reason is i just incorrect add event handler to the .caretelements, i add it as script in head section, but i need to add it after i generate comment section, this way:
//creating new HTML page +++
var windowTask = window.open("http://localhost/testapp/site/windows/formTask.html", "taskForm");
windowTask.onload = function(){
windowTask.document.getElementById("formTitle").innerText = "Task " + selectedRow.taskID;
windowTask.document.getElementById("taskID").value = selectedRow.taskID;
windowTask.document.getElementById("title").value = selectedRow.title;
windowTask.document.getElementById("status").value = selectedRow.status;
windowTask.document.getElementById("creator").value = selectedRow.creator;
windowTask.document.getElementById("responsible").value = selectedRow.responsible;
windowTask.document.getElementById("description").value = selectedRow.description;
windowTask.document.getElementById("dateCreation").value = selectedRow.dateCreation;
windowTask.document.getElementById("dateStart").value = selectedRow.dateStart;
windowTask.document.getElementById("dateFinish").value = selectedRow.dateFinish;
//creating new HTML page ---
//creating comment section +++
var comments = getCommentsTree(selectedRow.taskID, 'task');
windowTask.document.getElementById('commentsTree').innerHTML = createCommentsTree(comments);
//creating comment section ---
//adding event handler +++
var toggler = windowTask.document.getElementsByClassName("caret");
var i;
for (i = 0; i < toggler.length; i++) {
toggler[i].addEventListener("click", function() {
this.parentElement.querySelector(".nested").classList.toggle("active");
this.classList.toggle("caret-down");
});
}
//adding event handler ---
now everything works fine. If anyone spend some time for my question, thx.

Error binding Click Event in for loop in Javascript

I am trying to get array elements(which may be objects) in alert onclick. But, message is not binding on click.
this.openLink() method not getting alert for message and correct value.
I am missing something here while binding click events?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myBox(){
this.create = (id, id3 , arrData) => {
var html = "<div id='box1' class='col-12'></div>";
$("#box").append(html);
var html1 = "<div id='box2' class='col-12'></div>";
$("#box").append(html1);
this.createList(id, id3 , arrData)
}
this.createList = (id, id3 , arrData) =>{
var html = '';
html +='<ul id="' + id + '_List" class="col-12 rmpm" style="overflow-x:scroll;overflow-y:hidden;list-style- type:none;white-space:nowrap;font-size:0;padding: 0px 0px 10px 0px;">';
for (var i = 0; i < arrData.length; i++) {
var iD = id + '_utt' + i;
html += '<li id="' + iD + '" class="col-12 rmpm" style="display:inline;width:auto;border:1px solid #ccc;display:inline-block;font-size:14px;padding: 5px;border-radius: 5px;margin: 10px 10px 10px 0px; cursor: pointer;">';
html += arrData[i];
html += '</li>';
}
html += '</ul>';
$(id3).append(html);
// ---> here, some error for binding click event on li
arrData.forEach((element) => {
$(document).on('click', '#' + iD, () => {
this.openLink(element);
});
});
}
this.openLink = (message) =>{
alert(message); //a,b,c,as,bqsq,csqs <--- alert expecting here
}
}
</script>
<script>
function abc(){
var arrData = ['a','b','c'];
var arrData2 = ['as','bqsq','csqs'];
var bx = new myBox();
bx.create('arrData',"#box1" , arrData);
bx.create('arrData2',"#box2" , arrData2);
}
</script>
</head>
<body>
<button onclick="abc()">Clcik</button>
<div id="box" style=""></div>
</body>
</html>
You are assembling the id, in the for loop above your foreach, then you are using that id to set the clicklistener, you need to assemble the correct id at every loop in the foreach or else you will only put a listener on the last button.
Change your forEach to this:
arrData.forEach((element, index) => {
var clickId = id + '_utt' + index;
$(document).on('click', '#' + clickId, () => {
this.openLink(element);
});
});
To put it into the html as an onclick="function()" you need to assign it in the first loop when you are creating the HTML. and move openlink outside myBox()
function myBox() {
this.create = (id, id3, arrData) => {
var html = "<div id='box1' class='col-12'></div>";
$("#box").append(html);
var html1 = "<div id='box2' class='col-12'></div>";
$("#box").append(html1);
this.createList(id, id3, arrData)
}
this.createList = (id, id3, arrData) => {
var html = '';
html += '<ul id="' + id + '_List" class="col-12 rmpm" style="overflow-x:scroll;overflow-y:hidden;list-style- type:none;white-space:nowrap;font-size:0;padding: 0px 0px 10px 0px;">';
for (var i = 0; i < arrData.length; i++) {
var iD = id + '_utt' + i;
html += '<li ' + 'onclick="openLink(\'' + arrData[i] + '\')" id="' + iD + '" class="col-12 rmpm" style="display:inline;width:auto;border:1px solid #ccc;display:inline-block;font-size:14px;padding: 5px;border-radius: 5px;margin: 10px 10px 10px 0px; cursor: pointer;">';
html += arrData[i];
html += '</li>';
}
html += '</ul>';
$(id3).append(html);
}
}
openLink = (message) => {
alert(message); //a,b,c,as,bqsq,csqs <--- alert expecting here
}
function abc() {
var arrData = ['a', 'b', 'c'];
var arrData2 = ['as', 'bqsq', 'csqs'];
var bx = new myBox();
bx.create('arrData', "#box1", arrData);
bx.create('arrData2', "#box2", arrData2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<body>
<button onclick="abc()">Clcik</button>
<div id="box" style=""></div>
</body>
' + 'onclick="openLink(\'' + arrData[i] + '\')" . How does this worked. Can you please explain or provide some link so that I can understand
The line renders as onclick="openLink('a')" onclick="openLink( renders to the DOM as written. the \' renders a ' in the DOM and javascript sees it as a character that way i dont break the string, but it renders as a ' in the DOM. Then i add arrData[i] that is the n'th (or i'th) index in the array. then i use the same trick to close the onclick function off.

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.

how can we write visited function for the dynamically printed anchor tags

when we click on anchor tag it got hover but its not working for the visited function like if we visit to that link it should change its color and then if we visit to second link the color of first link should revert to its previous color and second link color should change as visited.please anyone help me to solve this problem below is my code:
script
$(document).ready( function() {
var st="1";
var clLiID = 100;
var fdevLiID = 300;
var sdevLiID = 400;
$('.p').click(function(e){
//alert("123");
//e.preventDefault();
var bid=2;
//var bid="1";
$.ajax({
url:"<?php echo base_url(); ?>/afcks/search",
data:{'b_id': bid},
type:"POST",
cache:false,
success:function(data)
{
//alert(data);
var sta="";
var obj = $.parseJSON(data);
var result = "<ul id='loct' >";
$.each(obj, function()
{
sta=this['branch_id'];
//alert(this['course_name']);
if(sta==2)
{
result = result + "<li item-checked='true' item-expanded='true' class='treeLi'> <a Class='cours' id='alink' temp_id='" + fdevLiID + "' temp_id1='" + sdevLiID + "' cid='"+this['course_id']+"' bid='"+this['branch_id']+"' href='javascript:void(0);'>" + this['course_name'] + "</a></li><div class='" + clLiID + "' id='" +fdevLiID + "'></div><div id='" + sdevLiID + "'></div>";
fdevLiID++;
sdevLiID++;
clLiID++;
}
});
result = result + "</ul>";
//alert(result);
if(st=="1")
{
document.getElementById("cour1").innerHTML =result;
st="2";
}
else
{
document.getElementById("cour1").innerHTML ="";
st="1";
}
}
});
});
});
another script
<script>
var st1="1";
$(document).on('click', '.cours', function() {
$('.cours').removeClass("visited");
$('.cours').addClass("visited");
</script>
CSS
#loct a
{
color:white;
//line-height:15px;
text-align:right;
font-size: 17.5px;
font-family:Trebuchet MS;
list-style-type: none;
text-decoration:none;
//font-style:italic;
/*a {color:#FF0000;} */
}
#loct a:hover
{
color:#F1C40F ;
transform: scale(1.2);
text-decoration:none;
}
#loct a.visited
{
color:#F1C40F ;
font-size:17.5px;
font-family:Trebuchet MS;
//transform: scale(1);
//background-color:white;
}
You need to change the small script:
<script>
var st1="1";
$(document).on('click', '.cours', function() {
$('.cours').removeClass("visited");
$(this).addClass("visited"); /* Use this to address the clicked element */
})
</script>

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