Get SPARQL query showing after submitting in Javascript - javascript

I am trying to display the result of a query after user presses submit with the value they have inputted, the query aims to grab this input and generate a result specific to the input. The query does grab the input as I have put the query code in an alert box and it displays the input from the user in the query, this alert box pops up after pressing submit of course. My code are below:
Html
<table id="results">
</table>
<form>
First name:<br>
<input id="messageInput" type="text" name="firstname"><br>
<input id="submit99" type="submit" value="Submit">
</form>
The query result should display in the table after pressing submit. Therefore table was inserted.
Script
<script type="text/javascript">
var table = $("#results");
table.on("click", "td", myFunction);
var url = "http://dbpedia.org/sparql";
$('#submit99').on('click', function (e) {
var userInput = $('#messageInput').val();
var query = [
"PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>",
"PREFIX type: <http://dbpedia.org/class/yago/>",
"PREFIX prop: <http://dbpedia.org/property/>",
"SELECT ?spouse",
"WHERE {",
"?dave dbo:spouse dbr:" + userInput + ".",
"?dave rdfs:label ?spouse.",
"}",
"Limit 1"
].join(" ");
alert("this query: [" + query + "]");
var queryUrl = url + "?query=" + encodeURIComponent(query) + "&format=json";
console.log(queryUrl);
$.ajax({
dataType: "jsonp",
url: queryUrl,
success: function (data) {
console.log(data);
// get the table element
var table = $("#results");
// get the sparql variables from the 'head' of the data.
var headerVars = data.head.vars;
// using the vars, make some table headers and add them to the table;
var trHeaders = getTableHeaders(headerVars);
table.append(trHeaders);
// grab the actual results from the data.
var bindings = data.results.bindings;
// for each result, make a table row and add it to the table.
for (rowIdx in bindings) {
table.append(getTableRow(headerVars, bindings[rowIdx]));
}
}
});
function getTableRow(headerVars, rowData) {
var tr = $("<tr></tr>");
for (var i in headerVars) {
tr.append(getTableCell(headerVars[i], rowData));
}
return tr;
}
function getTableCell(fieldName, rowData) {
var td = $("<td></td>");
var fieldData = rowData[fieldName];
//alert("fieldName = ["+fieldName +"] rowData[fieldName][value] = ["+rowData[fieldName]["value"] + "]");
td.html(fieldData["value"]);
return td;
}
function getTableHeaders(headerVars) {
var trHeaders = $("<tr></tr>");
for (var i in headerVars) {
trHeaders.append($("<th>" + headerVars[i] + "</th>"));
}
return trHeaders;
}
});
</script>
As you noticed the query result should be displayed in a table after user has pressed submit that's why I put almost all the code in the submit99 button. You guys should be able to run the code by copying and pasting it to your own IDE to gain a more familiar understanding. So question is right now after submission nothing shows up besides the alertbox displaying user input.
Thanks for your time :)

So I managed to fix the issue and get the result... all I had to do was insert the form elements in the table like:
<table id="results">
<First name:
<br>
<input id="messageInput" type="text" name="firstname">
<br>
<input id="submit99" type="submit" value="Submit">
</table>
However it is very strange because when I try to input the form tags it doesn't work:S atleast it does what I want it to do now:)

Related

Form response blank

I have some google script that generates an initial form then gathers a number does a lookup and then is supposed to return a second form (getfamily function). The second form which is dynamically generated returns blank. I can see the formHTML variable with data in the logger, but it comes up blank in the browser. Any suggestions would be appreciated.
var ssID="xxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
function doGet() {
var html = HtmlService.createTemplateFromFile('index2').evaluate()
.setTitle('Lookup').setSandboxMode(HtmlService.SandboxMode.NATIVE);
return html;
};
function getfamily(form){
Logger.log(form.familyid);
var ssID="xxxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
var formHTML = "<!DOCTYPE html>";
formHTML +="Hello!";
formHTML += '<form id="students">';
var filteredRows = rows.filter(function(row){
var message="made it";
if (row[0] === form.familyid) {
Logger.log(row[2]);
formHTML+= '<input type="checkbox" name ="students value='+ row[1] + '">'+ row[2] + '<br>';
return row[2];
}
});
formHTML+='<input type="submit" value="CheckIn">';
formHTML+='</form>';
Logger.log(formHTML);
var output = HtmlService.createHtmlOutput(formHTML).setSandboxMode(HtmlService.SandboxMode.NATIVE);
return output;
};
Your input type="checkbox" line is hard to figure out what you want. I presume that you plan in insert this form into an already exist DOM so no need the worrying about other tags just stick it in whatever div you have prepared for it.
function getfamily(form){
var ssID="xxxx";
var rows = SpreadsheetApp.openById(ssID).getSheetByName("studentinfo").getDataRange().getValues();
var formHTML='<form id="students">';
var message="made it";
rows.forEach(function(row){
if (row[0]==form.familyid) {
formHTTML=Utilities.formatString('<input type="checkbox" name="students" value="%s" /><br />',row[2]);//I presume that you want to change the name but I cant tell how you planned to do it.
}
});
formHTML+='<input type="button" value="CheckIn" onClick="proceesForm(this.parentNode);" />';
formHTML+='</form>';
return HtmlService.createHtmlOutput(formHTML);
};
You can use submit if you really must but I find using google.script.run to be a lot easier. We need to see more of what you're doing to provide a complete answer.

Send javascript generated texbox values with form(GET) to PHP script

I have a form where you can generate automatically additional form boxes and send them to be handeled at PHP-script. How ever as I am quite lousy with Javascript and I am running in the following problem.
When the form is filled out I can see everything is filled out on the URL, except the the boxes created with JS (every box has unique name!). My guess is that the JS generated field drop out of the form tags, but can not figure out how to fix this. I would appreciate if someone could give me pointers or tell me how to fix this. I shortened the code for clarity (if something got left out please tell me). If someone is wondering why I am not using the form action. It´s because drupal tries to forward the site to wrong place if I do (surprise, not too good with drupal either :D)
<?php
require_once('customer.php');
?>
<script type="text/javascript">
var intTextBox=0;
//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement()
{
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.setAttribute('id','strText'+intTextBox);
newTBDiv.innerHTML = "<div class='product'><tr><td>Sku/ID: "+intTextBox+": <input type='text' name='sku_" + intTextBox + "'/></div>";
contentID.appendChild(newTBDiv);
}
function removeElement()
{
if(intTextBox != 0)
{
var contentID = document.getElementById('content');
contentID.removeChild(document.getElementById('strText'+intTextBox));
intTextBox = intTextBox-1;
}
}
</script>
<table>
<form name="activate">
<div class='cu'>
<tr><td>Sku/ID (oma): <input type="text" name="sku"></td>
<td><p><a href="javascript:addElement();" >Add product</a>
<a href="javascript:removeElement();" >Remove product</a></p></td></tr>
<div id="content"></div>
</div>
<tr> <td><input type="submit" value="Submit"></td> </tr>
</form>
Customer.php
<?php
if(isset($_GET["sku_1"]))
{
echo "found it";
}
else
echo "did not find it";
?>
Any help would be much appreciated!
You could dynamically change the url of the form tag to include textbox values:
var textboxes = document.getElementsByTagName("input");
for (var i = 0; i < textboxes.length; i++){
var data = "?";
if (textboxes[i].type == "text") {
data += (data == "?" ? "" : "&") + textboxes[i].name + "=" + textboxes[i].value;
}
}
form.action += data;
I haven't tested this, you might have to dynamically add all elements
[UPDATE]
If you have trouble with the form you can try using an absolute path, if you aren't already.

typeahead not updating field

I am trying to implement typeahead for a city look-up for, but the field does not get updated. The city details show up, but I need to show the name in the city when a city is clicked, but when the form is sent, I need to send only the city code.
This is my HTML:
<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " />
And this is the javascript:
$('#_hotelCity').typeahead({
source: function (query, process) {
airports = [];
map = {};
var data = (function () {
var data = null;
$.ajax({
'async': false,
'global': false,
'url': 'http://localhost/imakeway/forms/finder/iata-aero-codes.json',
'dataType': "json",
'success': function (jdata) {
data = jdata;
}
});
return data;
})();
$.each(data, function (i, airport) {
map[airport.complete_location] = airport;
airports.push(airport.city + ' ( <b>' + airport.iata_code + '</b> - ' + airport.airport_name + ') near ' + airport.complete_location);
});
process(airports);
},
updater: function (item) {
selectedairport = map[item].complete_location;
selectedairport = map[item].iata_code;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp( '(' + this.query + ')', 'gi' );
return item.replace( regex, "<strong>$1</strong>" );
},
});
Thank you for any suggestions
HTML input tag can have only one value. This value is stored internally and displays inside the field.
It seems you are using some kind of AJAX form submission.
So, your solution is to have separate variable in JS to store city code.
Another solution is to use Select2 instead of typeahead.
This is my choice when you provide a SELECT-like field but need external AJAX data source.
Btw, with Select2 you can also force user to choose only an existing value.
Look here for example: http://ivaynberg.github.io/select2/#ajax
I would suggest you to use an additional hidden field which you update aside the normal input field.
<input id="_hotelCity" class="form-control typehead" type="text" value="" placeholder="Enter city name or code " />
<input type="hidden" value="" name="city_code" />
In this hidden field you put the city code eachtime the typeahead is updated. When submitting the form your server side script can parse it (in PHP it would $_POST['city_code']).
Using typeahead, and didnt want to replace very much of your code. I ended up with this fiddle: http://jsfiddle.net/Ydtq9/2/
You will definitely want to refactor some things but the trick is to set some instance variables in the source function, and you can access them in the updater function like so
$("#_hotelCity").typeahead({
"source": function(query, process) {
this.map = ...
},
"updater": function(item) {
var city = this.map(item)
//Then you can do what you need to with the original data.
}
})

How to make a hidden form with a file field

I have a dynamically generated table which is editable. On clicking any cell in the table I can change its text.
In one column there is an image displayed. When the user clicks on it I change the html for that column to <input type='file'> and trigger a click hence making the user choose a file to upload as the an icon.
In the last column of the table I have a commit button. If the user makes some changes and presses commit I have to pick up the whole row ( some text fields and one file field ) and add all the contents to a form including the file the user chose and send it to a python script to upload it to an s3 server.
My question is: How do I send this form?
I'm currently using script this but it is not working as it is only sending text as request.Files turns out empty at the python(django) script side.
function update(a) {
try {
var button = $(a);
var row = $(button.parent());
var rowcount = button.parent().parent().parent().children().index(button.parent().parent());
var filerow = '';
var formrow = new Array();
var rowkey = new Array('Topic', 'TopicDescription');
var cnt = 0;
var form = $('#dyno_form');
row.siblings().each(function () {
if ($(this).find($('input:file')).length > 0) {
$(this).find($('input:file')).appendTo($(form));
} else if ($(this).find($('img')).length == 0) {
formrow[cnt++] = '<input type="text" value="' + $(this).html() + '" name="' + rowkey[cnt - 1] + '"/>';
}
});
$(form).append(formrow[0]);
$(form).append(formrow[1]);
$(form).submit();
} catch (a) {
alert(a);
}
}
and here is the HTML:
<form id='dyno_form' action='' method="post" style="visibility:hidden">{% csrf_token %}</form>
How do I go about doing this?
When you want to upload a file the form element needs to have the correct enctype attribute and the method must be post.
<form enctype="multipart/form-data" method="post" ...
Otherwise only the values of your inputs will be uploaded.

A table row is causing content adding to not work

I have a piece of code below which works fine when it comes to adding text from a modal window into a textarea:
<script type="text/javascript">
var plusbutton_clicked;
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $plusrow = $("<td class='plusrow'></td>");
var $question = $("<td class='question'></td>");
$('.questionTextArea').each( function() {
var $this = $(this);
var $questionText = $("<textarea class='textAreaQuestion'></textarea>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$question.append($questionText);
});
$('.plusimage').each( function() {
var $this = $(this);
var $plusimagerow = $("<a onclick='return plusbutton(this);'><img src='Images/plussign.jpg' width='30' height='30' alt='Look Up Previous Question' class='imageplus'/></a>").attr('name',$this.attr('name')+"[]")
.attr('value',$this.val());
$plusrow.append($plusimagerow);
});
$tr.append($plusrow);
$tr.append($question);
$tbody.append($tr);
form.questionText.value = "";
$('.questionTextArea').val('');
}
function closewindow() {
$.modal.close();
return false;
}
$('.plusimage').live('click', function() {
plusbutton($(this));
});
function plusbutton(plus_id) {
// Set global info
plusbutton_clicked = plus_id;
// Display an external page using an iframe
var src = "previousquestions.php";
$.modal('<iframe src="' + src + '" style="border:0;width:100%;height:100%;">');
return false;
}
function addwindow(questionText) {
if(window.console) console.log();
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
$('#mainTextarea').val(questionText);
} else {
$(plusbutton_clicked).parent('td').next('td.question').find('textarea.textAreaQuestion').val(questionText);
}
$.modal.close();
return false;
}
</script>
But the problem is that if I include this code below which I need into the function insertQuestion(form) {, then it stops the text adding into the textarea, why is it doing this?
var $qid = $("<td class='qid'>" + qnum + "</td>" );
...
$tr.append($qid);
$qid is the question number for each row, so everytime a row is added, it adds a question number by plus 1 each time.
Blow is the html code of where it appends the textarea from the top into a table row:
<table id="question">
<tr>
<th colspan="2">
Question Number <span class="questionNum">1</span>
<input type="hidden" class="num_questions" name="numQuestion" value="1">
</th>
</tr>
<tr>
<td rowspan="3">Question:</td>
<td rowspan="3">
<textarea class="questionTextArea" id="mainTextarea" rows="5" cols="40" name="questionText"></textarea>
</td>
</tr>
</table>
UPDATE:
I have included links to both applications. One that works but does not include $qid, and one that includes $qid and doesn't work but which I do need working. Please follow steps in both applications so you can test it yourself and see what is happening:
Application 1: No $qid but working.
Aplication 2: Contains $qid but not working:
Follow steps below for both applications:
Click on "Add Question" button, then will add a textarea within a new row.
Click on the "Green Plus" button within the table row you just added, a modal window will appear.
In modal window it displays a search bar, in search bar type in "AAA" and click on "Search" button
Results will appear of your search, click on "Add" button to add a row. You will find out modal window is closed but the content from the "Question" field is not added in the textarea within the row you clicked on the green plus button
Try explicity setting the td value with
var $qid = $("<td class='qid'></td>" ).text(qnum);
$tr.append($qid);
And then replace the text setting code from
$(plusbutton_clicked).parent('td').next('td.question').find('textarea.textAreaQuestion').val(questionText);
to
$(plusbutton_clicked).closest('tr').find('textarea.textAreaQuestion').val(questionText);
You can try it easily if you try with text:
var $qid = $("<td class='qid'>"+ qnum + "</td>" );
$tr.append($qid);
or
$("<td class='qid'></td>" ).text('hello').appendTo($tr);

Categories

Resources