query database with python with date range from html form - javascript

I have this html code to enter the starting and ending date ranges
<input id="fechaInicio" type="text"
<input id="fechaFinal" type="text"
<a onclick = "listadoConsulta()" href="#" class="btn"
the javascript code
async function listadoConsulta() {
document.getElementById('fechaInicio').value = date1
document.getElementById('fechaFinal').value = date2
var url = URLSERVIDOR + 'listado/consulta'
var respuesta = await fetch(url, {
"method": 'GET',
"headers":{
"Content-Type": 'application/json'
}
})
listado = await respuesta.json();
var html = ''
for (registro of listado) {
var row = `<tr>
<td>${registro.folio}</td>
<td>${registro.lote}</td>
<td>${registro.tabla}</td>
<td>${registro.cajas}</td>
<td>${registro.peso_neto}</td>
</tr>`
html = html + row;
}
document.querySelector('#tablaFechas> tbody').outerHTML = html
and database query in python
#app.route('/api/listado/consulta')
#cross_origin()
def listadoConsulta():
ejecutarListado = mysql.connection.cursor()
#date1 = "20220920"
#date2 = "20220921"
ejecutarListado.execute('SELECT id, folio, lote, tabla, cajas, peso_neto FROM
`registrocorte` WHERE `fecha` BETWEEN ' + date1 + " AND " + date2 + ';')
datos = ejecutarListado.fetchall()
resultadoLista = []
for fila in datos:
contenido = {'id': fila[0],
'folio': fila[1],
'lote': fila[2],
'tabla': fila[3],
'cajas': fila[4],
'peso_neto': fila[5]
}
resultadoLista.append(contenido)
return jsonify(resultadoLista)
It works well if I put the dates directly in the query in python, the question is how can I make it do the query using the dates that I give to the html?

Related

XML parse : table data to Google Spreadsheet via App Script

I need to parse table data to my spreadsheet, there is no error in log, but cells in spreadsheet are blank. The problem is that I can't use built-in importhtml function, becouse the date-related data in the tag is enered dynamically on the website. I tryied to getchild getchildren but it doesn't work.
The structure of html site looks like this:
<html>
<head>
<title>TITLE AAAAA</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta content="IE=EmulateIE7" http-equiv="X-UA-Compatible">
<style type="text/css">
body {
font-size: 12px;
font-family: Arial
}
td {
font-size: 12px;
line-height: 20px;
font-family: Arial
}
</style>
<script type="text/javascript" language="javascript" src="Function.js"></script>
</head>
<body>
<p align="center">
<b>AAAA: AAAAAA</b>
</p>
<table width="300" border="0" align="center" cellpadding="1" cellspacing="1" bgcolor="#0066cc">
<tbody>
<tr align="center" bgcolor="#333399" class="font13">
<td width="150">
<b>
<font color="#ffffff">TO_CELL_A1_TEXT</font>
</b>
</td>
<td width="150">
<b>
<font color="#ffffff">TO_CELL_B1_TEXT</font>
</b>
</td>
<td width="150">
<b>
<font color="#ffffff">TO_CELL_C1_TEXT</font>
</b>
</td>
<td width="150">
<b>
<font color="#ffffff">TO_CELL_D1_TIME_TEXT</font>
</b>
</td>
</tr>
<tr align="center" bgcolor="#FFFFFF">
<td height="20">
<b>
<font color="red">TO_CELL_A2_TEXT</font>
</b>
</td>
<td>
<b>
<font color="red">TO_CELL_B2_TEXT</font>
</b>
</td>
<td>
<b>
<font color="red">TO_CELL_C2_TEXT</font>
</b>
</td>
<td>
<script>
showtime(2023, 01 - 1, 13, 23, 01, 12)
</script>"TO_CELL_D2_TIME_TEXT"
</td>
</tr>
</tbody>
</table>
<br>
<p align="center">SITE_NAME</p>
</body>
</html>
Is there any solution to this problem?
The code is not importing anything because it's looking for <tr> as children of <table> but, assuming that the HTML included in the question is the response given by the server, they are children of <tbody>. One simple fix is to replace
var rows = table.getChildren("tr");
by
var tbody = table.getChild("tbody");
var rows = tbody.getChildren("tr");
There are more elegant solutions like using specialised libraries on parsing HTML/XML documents but before entering on using them you should spend some time learning the basics of Google Apps Script and Document Object Model (DOM).
Related
Extracting a table in Google Apps Script using UrlFetchApp
How to pull HTML table data with Cheerio in Google Apps Script?
Scraping data to Google Sheets from a website that uses JavaScript
Using the cheerio library, I solved the problem, also added the code that in the D2:D cells it replaces the values, for example: showtime(2023,01-1,20,21,09,48)" into the correct date and time format.
I recommend reading the materials linked here by users #rubén and #doubleunary. If you run into a problem like me and you are a beginner, loading the Cheerio library via clasp into the cloned script on your computer will not work, because for const cheerio = require('cheerio');, require is a function available in the CJS module system that handles imports, basically. GitHub users came up against this problem and you should look for a solution to implement Cheerio in GAS, bearing in mind that these are not libraries recommended by Google, but created by users.
Here is working script in my case:
function importData() {
var url = 'http://urlsite.com';
var res = UrlFetchApp.fetch(url, {
muteHttpExceptions: true
}).getContentText();
res = res.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(match, capture) {
return capture;
});
const $ = Cheerio.load(res);
var col1 = $('table tr td:nth-child(1)').toArray().map(x => $(x).text());
var col2 = $('table tr td:nth-child(2)').toArray().map(x => $(x).text());
var col3 = $('table tr td:nth-child(3)').toArray().map(x => $(x).text());
var dateValues = $('table tr td:nth-child(4)').toArray().map(x => $(x).text());
var table = dateValues.map((d, i) => [col1[i], col2[i], col3[i], d]);
var range = SpreadsheetApp.getActiveSheet().getRange(1, 1, table.length, table[0].length);
range.setValues(table);
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("D2:D");
var values = range.getValues();
var convertedDates = values.map(function(value) {
var match = value[0].match(/showtime\((\d+),(\d+)-1,(\d+),(\d+),(\d+),(\d+)\)/);
if (match) {
var year = match[1];
var month = match[2];
var day = match[3];
var hour = match[4];
var minute = match[5];
var second = match[6];
var date = new Date(year, month - 1, day, hour, minute, second);
return Utilities.formatDate(date, "GMT", "yyyy-MM-dd HH:mm");
}
return "";
});
range.setValues(convertedDates.map(function(x) {
return [x];
}));
}
Moreover, while studying, I wrote a script to check ability to fetch data from website, what data is fetched and how does the tree of html looks like. You can use it in doc.new script.
function addMenuTab() {
var document = DocumentApp.getActiveDocument();
var menu = DocumentApp.getUi().createMenu("MY PROGRAMS")
.addItem("1_CLEAN DOC", "menuItem1Function")
.addItem("2_GENERATE", "menuItem2Function")
.addItem("3_BOLD RESPONSES", "menuItem3Function")
.addToUi();
}
function menuItem1Function() {
DocumentApp.getActiveDocument().getBody().clear();
}
function menuItem2Function() {
var ui = DocumentApp.getUi();
var result = ui.prompt(
'Check ability to parse website!',
'Please enter your url:',
ui.ButtonSet.OK_CANCEL);
var button = result.getSelectedButton();
var url = result.getResponseText();
if (button == ui.Button.OK) {
ui.alert('Your URL is ' + url + '.');
} else if (button == ui.Button.CANCEL) {
ui.alert('I didn\'t get your URL.');
} else if (button == ui.Button.CLOSE) {
ui.alert('You closed the dialog box.');
}
var body = DocumentApp.getActiveDocument().getBody();
body.clear();
var response = UrlFetchApp.fetch(url);
var responseOpts1 = UrlFetchApp.fetch(url, opts1);
/**
var responseOpts2 = UrlFetchApp.fetch(url, opts2);
*/
var opts1 = {
// methods: get, delete, patch, post, put - by default: get
'method': 'get',
// contentType: 'application/json' ; 'application/xml' ; 'application/html' - by default: application/x-www-form-urlencoded&#39
'contentType': 'text/javascript',
// key/value map of the HTTP headers for the request;
'headers': '1',
}
/**
var Opts2 = {
//methods: get, delete, patch, post, put - by default: get
'method' : 'get',
'payload' : 'formdata'
}
*/
var responseCode = response.getResponseCode();
Logger.log("Response Code: " + responseCode);
var headers = response.getHeaders();
Logger.log("Headers: " + headers);
var headersText = JSON.stringify(response.getHeaders());
Logger.log("HeadersText: " + headersText);
var contentLength = response.getContentText().length;
Logger.log("Content Length: " + contentLength);
var allHeaders = response.getAllHeaders();
Logger.log("All Headers: " + allHeaders);
var allHeadersText = JSON.stringify(response.getAllHeaders());
Logger.log("All HeadersText: " + allHeadersText);
var document = DocumentApp.getActiveDocument();
var body = document.getBody();
var contentText = response.getContentText();
Logger.log("Content Text: " + contentText);
var contentText2 = responseOpts1.getContentText();
Logger.log("Content Text & Opts1: " + contentText2);
/**
var contentText3 = responseOpts1.getContentText();
// Replace html elements
contentText3 = contentText3.replace(/(<(?=link|meta)[^>]*)(?<!\/)>/ig, '$1/>');
contentText3 = contentText3.replace(/&(?!amp;)/ig, '&');
contentText3 = contentText3.replace(/ /ig, " ");
contentText3 = contentText3.replace(/<table[^>]*>/ig, "<table>");
contentText3 = contentText3.replace(/<tr[^>]*>/ig, "<tr>");
contentText3 = contentText3.replace(/width[^>]*>/ig, "<width>");
contentText3 = contentText3.replace(/<td[^>]*>/ig, "<td>");
contentText3 = contentText3.replace(/<font[^>]*>/ig, "<font>");
contentText3 = contentText3.replace(/<p[^>]*>/ig, "<p>");
contentText3 = contentText3.replace(/width[^>]*>/ig, "<width>");
contentText3 = contentText3.replace(/<br>|<\/br>/ig, "");
contentText3 = contentText3.replace(/<style[^>]*>/ig, "<style>");
contentText3 = contentText3.replace(/(<(p|script|style)[^>]*>)/ig, '$1<![CDATA[').replace(/(<\/(p|script|style)[^>]*>)/ig, ']]>$1')
Logger.log("Content Text & Opts: " + contentText3);
var contentText4 = XmlService.parse("<!DOCTYPE html>" + contentText3);
var root = contentText4.getRootElement().getChild("body");
var table = root.getChild("table");
var tbody = table.getChild("tbody");
var tr = table.getChild("tr");
var td = tr.getChild("td");
var font = td.getChildren("font");
var script = td.getChildren("script");
*/
body.appendParagraph("Response Code: " + responseCode);
body.appendParagraph("");
body.appendParagraph("Headers: " + headers);
body.appendParagraph("");
body.appendParagraph("HeadersText: " + headersText);
body.appendParagraph("");
body.appendParagraph("Content Length: " + contentLength);
body.appendParagraph("");
body.appendParagraph("All Headers: " + allHeaders);
body.appendParagraph("");
body.appendParagraph("All HeadersText: " + allHeadersText);
body.appendParagraph("");
body.appendParagraph("Content Text: " + contentText);
body.appendParagraph("");
/**
body.appendParagraph("Content Text & Opts1: " + contentText2);
body.appendParagraph("");
body.appendParagraph("Content Text3: " + contentText3);
body.appendParagraph("");
body.appendParagraph("Content Text4: " + contentText4);
body.appendParagraph("");
body.appendParagraph("Root: " + root);
body.appendParagraph("");
body.appendParagraph("Table: " + table);
body.appendParagraph("");
body.appendParagraph("Tbody: " + tbody);
body.appendParagraph("");
body.appendParagraph("Tr: " + tr);
body.appendParagraph("");
body.appendParagraph("Td: " + td);
body.appendParagraph("");
body.appendParagraph("font: " + font);
body.appendParagraph("");
body.appendParagraph("script: " + script);
body.appendParagraph("");
*/
}
function menuItem3Function() {
var doc = DocumentApp.getActiveDocument();
var text = doc.getBody().getText();
var searchString1 = "Response Code: ";
var searchIndex = text.indexOf(searchString1);
var responseCode = text.substring(searchIndex + searchString1.length, searchIndex + searchString1.length + 3);
var textSearched = doc.getBody().findText(searchString1 + responseCode);
var element1 = textSearched.getElement();
if (responseCode === "200") {
element1.setBold(true);
element1.setForegroundColor("#9cd161");
} else {
element1.setBold(true);
element1.setForegroundColor("#ff0000");
}
var body = doc.getBody();
var searchString = ["Headers", "HeadersText", "Content Length", "All Headers", "All HeadersText", "Content Text", "Content Text & Opts:", "Content Text3:"];
for (var i = 0; i < searchString.length; i++) {
var searchResult = body.findText(searchString[i]);
while (searchResult !== null) {
var searchResultElement = searchResult.getElement();
var start = searchResult.getStartOffset();
var end = searchResult.getEndOffsetInclusive();
searchResultElement.setBold(start, end, true);
searchResult = body.findText(searchString[i], searchResult);
}
}
}

how to make more efficient js for loop inside php while loop JSON

I'm selecting values from my db in mysql and comparing them with values from JSON. I'm receiving the right results but since I'm using append the results shows up one by one, which looks like animation I would like to get them all at once and show some kind of loading icon while the loop is running, I've tried few different ways but nothing worked.
<?php $sql= "select a_id,b_id,res_a,res_b from betts_gr where u_id='".$u_id[0]."'";
$user_bets = mysqli_query($conn,$sql);
while($user_bets1 = mysqli_fetch_array($user_bets)){
?>
<script>
$(document).ready(function() {
var a_id = "<?php echo $user_bets1[0]?>";
.....
var car = [];
$.getJSON('http://api.football-api.com/2.0/matches?
comp_id = 1204 & from_date = '+today+' & to_date = '+plusmonth+' & Authorization ',
function(data) {
var html = "";
console.log(data);
$.each(data, function(index, value) {
var teama = value.localteam_name;
var teamb = value.visitorteam_name;
.......
function add(name, point) {
car.push({
teamb: teamb,
teama: teama,
form: form,
data: data,
teama_id: teama_id,
teamb_id: teamb_id,
a_res: a_res,
b_res: b_res
});
}
add(teama, teamb, data, form, teama_id, teamb_id, a_res, b_res);
});
for (var n = 0; n < car.length; n++) {
if (car[n].teama_id == a_id && car[n].teamb_id == b_id) {
html += "<tr><td><input type='hidden' name='aid" + n + "'
value = '"+car[n].teama_id+"' > < input type = 'hidden'
name = 'bid"+n+"'
value = '"+car[n].teamb_id+"' > " +
car[n].data +
"</td><td> " + car[n].teama + "</td><td>" + car[n].a_res + "-" +
car[n].b_res + "</td><td> " +
car[n].teamb + '</td><td> you predicted ->' + pred_resa + ' - ' + pred_resb +
'</tr>';
}
}
$(".message").append(html);
});
});
</script>
<?php } ?>
the example for using the Array.map and the template literals instead of the for loop and the plain string concat:
const isTargetTeam = item => item.teama_id == a_id && item.teamb_id == b_id;
const html = car.slice(0) // copy the array car
.filter(isTargetTeam)
.map((item, index) =>
`<tr>
<td>
<input type='hidden' name='aid${index}' value='${item.teama_id}'>
<input type='hidden' name='bid${index}' value='${item.teamb_id}'>
${item.data}
</td>
<td>
${item.a_res}-${item.b_res}
</td>
<td>
${item.teamb}
</td>
<td> you predicted -> ${pred_resa} - ${pred_resb}
</tr>`
).join('')
You should not mix PHP and Javascript like that. Currently this will result in X document.ready functions with X getJSON requests.
If you want to do the API requests from the local client, you should do ONE javascript function where you pass in the selected user_bets as an array. There are different possibilities to determine if all loadings have been finished: either counting up and checking after every callback if the max number is reached, or using Promises and Promise.all().
<script>
var user_bets = <?php echo json_encode($user_bets);?>;
$(document).ready(function () {
Promise.all(user_bets.map(function (id) {
return fetchFromApi(id);
})).then(function(array){
var html = "";
for(var i = 0; i < array.length; i++){
html += processData(array[i]);
}
$(".message").append(html);
});
});
function fetchFromApi(user_id) {
return new Promise(function (resolve, reject) {
$.getJSON()
.done(function (data) {
resolve(data);
})
.fail(function (error) {
reject(error);
});
});
}
function processData(data){
var html = '';
// do your html processing of a single api call here
return html;
}
</script>
Alternatively you can use CURL to do the API requests server-side already.
Thanks for advise I just realize I should get data with one request. I've passed the whole array to js and since I'm not sure how promise.all is working I did two for loops nested and is working fine, the only thing I still can't figure out how to check if the loops are finished so I could add loading icon while loop is running.
function add(name, point) {
car.push({ teamb : teamb, teama : teama, form:form, data:data, teama_id:teama_id,
teamb_id:teamb_id, a_res:a_res, b_res:b_res});
}
add(teama,teamb,data,form,teama_id,teamb_id,a_res,b_res);
});
for(var n=0;n<car.length;n++){
var taba = [<?php echo json_encode($at1)?>];
var tchild = taba[0];
for(var u=0;u<tchild.length;u++){
if(car[n].teama_id == tchild[u].localteam_id
&& car[n].teamb_id == tchild[u].visitorteam_id){
html += "<tr><td><input type='hidden' name='aid"+n+"'
value='"+car[n].teama_id+"'>
<input type='hidden' name='bid"+n+"'
value='"+car[n].teamb_id+"'>"
+car[n].data
+"</td><td> "+car[n].teama + "</td><td>"+ car[n].a_res
+ "-"+ car[n].b_res + "</td><td> "
+ car[n].teamb + '</td><td> you predicted -
>'+tchild[u].localteam_score +' - '+tchild[u].visitorteam_score +
'</td></tr>';
}
}
}
$(".message").append(html);

Send from data from .jsp file to a javascript function in aome .jsp file

The following is OneEmployee.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<form>
<td> <c:out value="${emp.getEmpid()}"/></td>
<td> <input type="text" id="fname" value="<c:out value="${emp.getFname()}"/>"></td>
<td> <input type="text" id="lname" value="<c:out value="${emp.getLname()}"/>"></td>
<td> <input type="text" id="dob" value="<c:out value="${emp.getDob()}"/>"></td>
<td> <input type="text" id="salary" value="<c:out value="${emp.getSalary()}"/>"></td>
<td><button type="button" class="btn btn-xs" onclick="update(<c:out value="${emp.getEmpid()}"/>)">Update</button></td>
</form>
Following is Welcome.jsp //homepage JSP
<script>
function update(id) {
var empid = "?empid=" + id;
var formdata = "xyz";
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var dob = document.getElementById("dob").value;
var salary = document.getElementById("salary").value;
var paramlist = "?empid=" + empid + "&fname=" + fname + "&lname=" + lname + "&dob=" + dob + "&salary=" + salary;
$.ajax({
type: "post",
data: formdata,
url: "UpdateEmployee" + paramlist,
success: function (data) {
$('#row' + id).html(data);
}
});
}
</script>
Following is a java servlet UpdateEmployee.java
String id = request.getParameter("empid");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String dob = request.getParameter("dob");
String sal = request.getParameter("salary");
double salary = Double.parseDouble(sal);
int empid = Integer.parseInt(id);
I am trying to fetch input data from OneEmployee.jsp in update() of Welcome.jsp and send the data to servlet UpdateEmployee.java.
Glassfish server responds:
Warning: StandardWrapperValve[UpdateEmployee]: Servlet.service() for servlet UpdateEmployee threw exception
java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.lang.Double.parseDouble(Double.java:538)
What is the problem? what went wrong in here? Why is the OneEmployee.jsp passing empty strings to Welcome.jsp and hence UpdateEmployee,jsp?
You're trying to parse an empty String so the exception is thrown :
the problem Is that you're getting an empty value from Front end code ( ajax req ) . ( recheck in browser console before send ) .
Check first if it's not null or empty when you parse otherewise return 0:
String id = request.getParameter("empid");
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
String dob = request.getParameter("dob");
String sal = request.getParameter("salary");
double salary = 0;
if (sal != null && sal.length() > 0) {
try{
salary = Double.parseDouble(sal);
}catch(Exception e) {
salary = 0;
}
}
int empid = 0;
if (id != null && id.length() > 0) {
try{
empid = Integer.parseInt(id);
}catch(Exception e) {
empid = 0;
}
}

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).

Validating dynamically created group of check box

I have constructed a table dynamically using Xml file for Multiple choice questions having input type as check boxes instead of radio button.
I wanna know to how to restrict user to check only one check box in a question having for options
Preview of my xml file is
<QA id="1">
<number>1</number>
<q><![CDATA[ <span id="q">Which of the Following is Called "SHRIMP CAPITAL OF INDIA"?</span>]]></q>
<inputType><![CDATA[ <input type = "checkbox" name="UserID" >]]></inputType>
<a><![CDATA[ <label>Stratosphere</lable>]]></a>
<a><![CDATA[ <label>Troposphere</lable>]]></a>
<a><![CDATA[ <label>Mesosphere</lable>]]></a>
<a><![CDATA[ <label>Thermosphere</lable>]]></a>
</QA>
<QA id="2">
<number>2</number>
<q><![CDATA[ <span id="q">Which of the Following is Called "SHRIMP CAPITAL OF INDIA"?</span>]]></q>
<inputType><![CDATA[ <input type = "checkbox" name="UserID1">]]></inputType>
<a><![CDATA[ <label>GOA_MANGLORE</lable>]]></a>
<a><![CDATA[ <label>ROHA-MANGLORE</lable>]]></a>
<a><![CDATA[ <label>KANYAKUMARI-MANGLORE</lable>]]></a>
<a><![CDATA[ <label>KANYAKUMARI-MUMBAI</lable>]]></a>
script for dynamic table ...
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "data1.xml",
dataType: "xml",
success:function(xml){
$(xml).find('Root').each(function()
{
var title = $(this).find('title').text();
var submit = $(this).find('submit').text();
var subtitle = $(this).find('subtitle').text();
var image = $(this).find('image').text();
var inputType1=$(this).find('inputType1').text();
var inputType2=$(this).find('inputType2').text();
document.getElementById("yt1").value = title;
document.getElementById("yt2").value = submit;
document.getElementById("sub").innerHTML = subtitle;
document.getElementById("middle").src = image;
document.getElementById("yt1").type = inputType1;
document.getElementById("yt2").type = inputType2;
});
var data = "";
var startTag = "<table width='50%'CELLPADDING='1' CELLSPACING='1' id='example'><tbody>";
var endTag = "</tbody></table>";
$(xml).find('QA').each(function() {
var $qa = $(this);
var number =$qa.find('number').text();
var inputType=$qa.find('inputType').text();
var q = $qa.find('q').text();
data += '<tr><td><h3>' + number + '</h3></td>';
data +='<td><h3>'+ q +'</h3></td>';
$(this).find('a').each(function() {
data += '<tr><td>'+ inputType + '</td>';
data += '<td>' + $(this).text()+ '</td></tr></tr>';
});
});
$(xml).find('inputType').each(function() {
$('input:checkbox').click(function() {
$(this).siblings(':checked').attr('checked', false);
});
});
$("#content").html(startTag + data + endTag);
} }); });
</script>

Categories

Resources