I want to integrate the user's input into a SPARQL query. Here's my existing code but I cannot get it to work.
javascript in external JS file:
$('#submit99').on('click', function(e) {
var userInput = $('#messageInput').val();
var query = "PREFIX own: <http://www.owl-ontologies.com/travel.owl#>" +
"PREFIX trvl: <http://www.owl-ontologies.com/travel.owl#>" +
"select distinct ?label where {" +
"?s a trvl:" + userInput + " ."
"OPTIONAL {" +
"?type rdfs:label ?label }" +
"}";
var endpoint = 'http://localhost:5820/finalProject/query';
var format = 'JSON';
$.get('/sparql',data={'endpoint': endpoint, 'query': query, 'format': format}, function(json){
var pre = $('<pre></pre>');
pre.text(JSON.stringify(json));
$('#linktarget99').html(pre);
});
});
my form:
<div class="header">
<div class="container">
<h1> Zoek de plek voor je favoriete activiteiten </h1>
<p class="beschrijving"> Wil je weten op welke plek jij bepaalde activiteiten kunt doen? Vul hieronder de activiteit in en wij zoek het voor je uit! tutorial </p>
<form role='form'>
<div class='form-group'>
<textarea class='form-control' id='messageInput' placeholder='type some nifty schilderij' row='1'> </textarea>
</div>
</form>
<div><a id="submit99" class='btn btn-primary'>Zoek de locatie van het schilderij</a></div>
</div>
</div>
This is the error I get from the terminal:
127.0.0.1 - - [14/Oct/2015 20:02:52] "GET /sparql?endpoint=http%3A%2F%2Flocalhost%3A5820%2FfinalProject%2Fquery&query=PREFIX+own%3A+%3Chttp%3A%2F%2Fwww.owl-ontologies.com%2Ftravel.owl%23%3EPREFIX+trvl%3A+%3Chttp%3A%2F%2Fwww.owl-ontologies.com%2Ftravel.owl%23%3Eselect+distinct+%3Flabel+where+%7B%3Fs+a+trvl%3A++BedAndBreakfast.&format=JSON HTTP/1.1" 200 -
It's fixed. The value given by the userinput container spaces which (...) up the code.
Related
I would like to pass a list of String from Spring Controller to Javascripts.
The Controller :
#PostMapping("/level1")
public String login (Model model){
List<Question> questions = frageRepository.findAllQuestions();
List<String> questionText = questions.stream().map(Frage::getText).toList();
model.addAttribute("questionText", questionText);
log.info(spieler.toString());
return "level1";
}
the body of level1.html
<body>
<div class="container mx-auto">
<label class="text-center mt-4" id="thetext">Du liebst Abenteuer und möchte endlich reisen.
<br>
Du hast ein bisschen Geld und das reicht für ein Ticket zur nächsten Insel.<br>
Unglücklicherweise ist dein Schiff in einem Sturm gesunken. <br>
Du hat glück, an einen Strand zu landen. <br><br>
Jetzt musst du die Herausforderungen mit deinen SQL-Kenntnissen meistern.<br>
Je schneller du die Probleme löst, desto besser ist dein Ranking.<br><br>
Viel Spaß !!!<br>
</label>
<div class="d-flex justify-content-center">
<input id="startButton" onclick="myFunction()" class="btn-secondary mt-4"
type="button" value="next">
</div>
</div>
<script>
var questionText = [[${questionText}]];
</script>
<script th:src="#{/script/questions.js}"></script>
</body>
the question.js file
var i = 0;
function myFunction() {
document.getElementById("thetext").innerHTML = questionText[i];
i++;
}
How can i pass the list questionText to Javascripts code? I want that when the user clicks the next button, the browser will show him the next question in label "thetext" from the list.
Or Is there another way to do this?
I hope, you can understand me :(
Thank you very much !
just input th:inline="javascript" in the script tag
<script input th:inline="javascript">
var questionText = [[${questionText}]];
</script>
I have a form which is composed of an ng-repeat (for each demand).
The user will be able to edit the "date réalisation" or the "motif refus" inside this ng-repeat, and will click on the button submit "Valider la modification", still inside this ng-repeat (to edit the demand in demands).
Here is the code :
<div class="jumbotron" ng-controller="gestDemInstallController">
<h1 class="text-center">{{ soustitre }}</h1>
<p>{{presentation}}</p>
<!--une ligne pour chaque demande
utilisation de getDataDemandesInstall.php
et de getDataDemandesInstallApplis.php
-->
<form>
{{ reussite }}<!-- indique un msg au clic du gestionnaire -->
<br><!-- on affiche chaque demande d'installation -->
<div ng-repeat="dem in demandesInstallations" class="tableau">
<br>
<label>ID :</label>
{{dem.id}}
<br>
<label>Ordinateur :</label>
{{dem.nomPC}}
<br>
<label>Date demande :</label>
{{dem.dateDemande}}
<br>
<label>Date réalisation :</label>
<input ng-model="date_real" type="date" value="{{dem.dateRealisation}}" class="form-control input-normal bouton">
Date enregistrée: {{dem.dateRealisation}}
<br><br>
<label>Motif refus :</label>
<input ng-model="motif_refus" type="text" value="{{dem.motifRefus}}" class="form-control input-normal bouton">
<br>
<label>Unité :</label>
{{dem.unite}}
<br>
<label>Demandeur :</label>
{{dem.demandeur}}
<br>
<!--boucle ng-repeat affichant chaque appli et profil choisi-->
<div ng-repeat="a in demandesInstallApplis">
<label><i>Applications demandées</i></label><br>
<label>Nom application :</label>
{{a.nom}}
<br>
<label>Profil demandé :</label>
{{}}
</div><!--fin ligne les applications-->
<input ng-model="btn{{dem.id}}" ng-click="checkGestDemInstall()" type="button" value="Valider la modification" class="form-control">
</div><!--fin de la demande, fin du ng-repeat-->
</form>
And here is the Controller (AngularJS)
//----RECUPERATION DES DONNEES : METHODE POST---------//
//----------------------------------------------------//
$scope.checkGestDemInstall = function(){
//on valide les données entrées
//on peut ensuite les envoyer au script PHP
//en utilisant la méthode HTTP Post
var error=0;
/*---- Le mot de passe est vérifié --*/
//si pas d'erreur (ni d'erreur mdp ni d'erreur id/mail)
if (error === 0) {
//on lance la méthode POST de la requête HTTP
var request = $http({
method: "post",
url: "/sio2/projets/gedeon_php/pages/postGestDemInstall.php",
data: {
//celui qui a été cliqué
date_real: $scope.date_real,
motif_refus: $scope.motif_refus
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
/* Check whether the HTTP Request is Successfull or not. */
request.success(function (data) {
$scope.reussite = "Données bien envoyées : "+data +" (information réceptionnée de PHP)";
});
}
else {
$scope.reussite = "Vous avez mal rempli le formulaire. Erreur de type : " + error;
}
}; //fin fonction checkGestDemInstall()
As you can see in my Controller, I would like to get my data, I mean the dem.date_real and the dem.motif_refus, whereas I have the same ng-model for each input... Indeed I have several inputs (one by ng-repeat) and I don't really know how to get data from the "date_real" edited and the "motif refus" edited.
Thanks for any advices !
////////////////////
Thanks to your advice I now have these codes but still with some errors :
ERROR 1 : $parse:syntax
ERROR 2 : ngRepeat:dupes
here inside my ng-repeat dem in demands :
<label>Date réalisation :</label>
<input ng-model="dem.dateRealisation" type="text" value="{{dem.dateRealisation}}" class="form-control input-normal bouton">
Date enregistrée: {{dem.dateRealisation}}
<br><br>
<label>Motif refus :</label>
<input ng-model="dem.motifRefus" type="text" value="{{dem.motifRefus}}" class="form-control input-normal bouton">
and here in my Controller :
data: {
//celui qui a été cliqué
date_real: $scope.dateRealisation, //= new Date(dateRealisation),//error ngModel:datefmt
motif_refus: $scope.motifRefus
},
And then here to POST my data, I want to check by echoing it in PHP as I usually do before doing an insert...
include('../bdd/conn.php');
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$date_real = $request->dateRealisation;
#$motif_refus = $request->motifRefus;
echo 'date real : '. $date_real . ' motif refus : '. $motif_refus;
I like everything to be understandable so I made a small scheme to explain :
If I understand correctly, change your ng-model to dem.dateRealisation and dem.motifRefus instead of date_real and motif_refus. If you use the variables defined on the scope then for every demand that you change the dates for it will update these variables, only ever returning one value for each.
If you want the data you are sending in your Post request to contain the dates for every demand, then you'll have to send a different object. You could send demandesInstallations and then change how this data object is handled
i found this code in jquery / ajax i edited a little but for some reason the output doesn't have a value.
here my code (javascript file):
function fototoevoegen(){
var fotonaam = document.getElementById('fotonaam').value
var text = document.getElementById('text').value
var file = new FormData();
console.log(fotonaam);
console.log(text);
console.log(file);
file.append('file',$('.file')[0].files[0]);
$.ajax({
url: "../assets/fototoevoegen.php",
type: "POST",
data:{ file, fotonaam, text},
processData: false,
contentType: false,
cache:false,
beforeSend:function(){
$(".result").text("Loading ...");
},
success:function(data){
$(".result").html(data);
alert(data);
}
});
return false;
}
the console.log does have value's but the output file (fototoevoegen say's undifend index to all vars :/
can someone help me on this ! thanks
//HTML file//
<!DOCTYPE html>
<html>
<head>
<title>CMS V1.2</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="../css/style2.css">
</head>
<body>
<div class="content">
<h2>Foto Database</h2>
<br/>
<form method="post">
<input type="hidden" name="size" required="required" value="">
<div>
<input type="file" id="file" class="file">
</div>
<br/>
<div>
<input type="text" id="fotonaam" placeholder="fotonaam">
</div>
<br/>
<div>
<textarea id="text" cols="40" rows="4" placeholder="foto omschrijving"></textarea>
</div>
<br/>
<div>
<input type="button" value="Upload Foto" onclick="fototoevoegen();">
</div>
<br/>
</form>
</div>
<div class="container3Titel">
<h2>Alle foto's in het database </h2>
</div>
<div class="container3">
<?php foreach ($fotos as $foto){ ?>
<div class ="container3item">
<form method ="get">
<h2><?= $foto['foto_naam']?></h2>
<img src="<?= $foto['foto_url']?>" width="300" height="170"/>
<p> <?= $foto['foto_omschrijving']?> </p>
<p> <?= $foto['foto_url']?> </p>
<input type=hidden id="fotourl" value="<?= $foto['foto_url']?>">
<input type=hidden id="foto_id" value="<?= $foto['foto_id']?>">
<input type="button" name="verwijderen" value="Foto Verwijderen" onclick="fotoverwijderen();">
</form>
</div>
<?php } ?>
</div>
</div>
</body>
</html>
Sent information to this file (../assets/fototoevoegen.php)
<?php
include_once('../includes/connection.php');
// de folder waar alle foto's worden opgeslagen
$folder = "../foto/";
$info = $_FILES["file"]["name"];
// extentie herkennen van het bestand en deze toevoegen aan de url
$ext = pathinfo($info, PATHINFO_EXTENSION);
$ext = '.'.$ext;
$naam = $_POST['fotonaam'].$ext;
$full_path = $folder.$naam;
// omschrijving en foto naam aan variable geven voor insert query
$omschrijving = $_POST['text'];
$fotonaam = $_POST['fotonaam'];
echo($naam);
echo($fotonaam);
echo($omschrijving);
echo($info);
// de foto of het bestand opslaan in een map (foto's)
if (move_uploaded_file($_FILES['foto']['tmp_name'], $full_path)) {
//als het uploaden gelukt is voer je een query uit naar de database zodat deze later nog gebruikt kan worden.
$query = $pdo->prepare("INSERT INTO fotobibliotheek (foto_naam,foto_omschrijving,foto_url) VALUES(?,?,?)");
$query->bindValue(1,$fotonaam);
$query->bindValue(2,$omschrijving);
$query->bindValue(3,$full_path);
$query->execute();
// succes melding weergeven en redirect naar pagina bibliotheek
echo "De foto is opgeslagen";
} else {
//fout melding als er niet geupload kan worden
echo 'uploaden mislukt';
}
?>
I think the problem is here:
data:{ file, fotonaam, text}
You need to append your values to your formData object and then send that object.
If you rearrange your code a little so that you handle the "submit" event of your form, instead of your button, then this becomes quite straightforward:
HTML:
<form id="fotoForm" method="post" enctype="multipart/form-data">
<input type="hidden" name="size" required="required" value="">
<div>
<input type="file" id="file" name="file" class="file">
</div>
<br/>
<div>
<input type="text" id="fotonaam" name="fotonaam" placeholder="fotonaam">
</div>
<br/>
<div>
<textarea id="text" cols="40" rows="4" name="text" placeholder="foto omschrijving"></textarea>
</div>
<br/>
<div>
<input type="submit" value="Upload Foto">
</div>
<br/>
</form>
JavaScript:
$(function() {
$("#fotoForm").submit(function(event) {
event.preventDefault(); //prevent default non-ajax postback
var data = new FormData(this); //pass the form into the formData object
$.ajax({
url: "../assets/fototoevoegen.php",
type: "POST",
data: data,
processData: false,
contentType: false,
cache: false,
beforeSend: function() {
$(".result").text("Loading ...");
},
success: function(data) {
$(".result").html(data);
alert(data);
}
});
});
});
See also Uploading both data and files in one form using Ajax? for a similar example
I'm having issues running my code can any one verifiy it and tell me why it's not working properly?. My javascript doesn't seems to be working fine and the best that I got was the first vars to display. I'm really new to javascript thought.
<!DOCTYPE html>
<html>
<head>
<title> Template Suivi Client </title>
<link rel="icon" href="icone.ico" type="image/x-icon">
<link rel="stylesheet" href="aidememoire.css">
<script>
function myFunction {
alert();
var compte = form.inputcompte.value;
var nom = form.inputnom.value;
var telephone = form.inputtelephone.value;
var quand = form.inputdate.value;
var hdebut = form.inputheuredebut.value;
var hfin = form.inputheurefin.value;
var info = form.inputdescription.value;
document.getElementById("displaycompte").innerHTML = ("Numéro de Compte Client: " + compte);
document.getElementById("displaynom").innerHTML = ("Nom du Client : " + nom);
document.getElementbyId("displaytelephone").innerHTML = ("Numéro de téléphone : ");
document.getElementbyId("displayquand").innerHTML =("Date :" + quand);
document.getElementbyId("displayheured").innerHTML = ("Heure de début : " + hdebut);
document.getElementById("displayheuref").innerHTML = ("Heure de fin: " +hfin);
document.getElementById("displaydescription").innerHTML =("Déscription :" + info);
}
</script>
</head>
<body>
<h2 style="text-align: Center">
Template Suivi Client
</h2>
<form method="get">
Numéro de Compte Client :
<input type="text" name="inputcompte">
<br><br>
Nom du Client :
<input type="text" name="inputnom">
<br><br>
Numéro de téléphone :
<input type="text" name="inputtelephone">
<br><br>
Date :
<input type="date" name="inputdate">
<br><br>
Heure de début :
<input type="time" name="inputheuredebut">
<br><br>
Heure de fin :
<input type="time" name="inputheurefin">
<br><br>
Description du problème :
<input type="text" name="inputdescription">
<br><br>
<button type="button" onclick="myFunction(from.here)"> Soummettre </button>
</form>
<br><br><br>
<p id="displayfinal"> Produit final s'affichera ici </p>
<p id="displaycompte">
</p>
<p id="displaynom">
</p>
<p id="displaytelephone">
</p>
<p id="displayquand">
</p>
<p id="displayheured">
</p>
<p id="displayheuref">
</p>
<p id="displaydescription">
</p>
</body>
</html>`
You are using a variable form that is not defined anywhere.
You can sent the reference to the form from the button:
onclick="myFunction(this.form)"
Catch the parameter in the function:
function myFunction(form) {
try giving the form an id, like <form id="abc" method="GET">...</form>
then use $("#abc").off('submit'); (after the end of the form)
The info that I got from the console [ Uncaught TypeError: Cannot read property 'inputcompte' of undefined ] . It happens to all my variables
I have a API script from my hosting provider and with this .php script I can only check if a Domain name is availble or not. But right now if I check a domain name, the page will refresh and then it will show the results.
But I want the results to show without refreshing. Is that possible? Can someone have a good solution for me?
Here is the results portion:
<center> <font color="#FFF "> <?=$result?> </font> </center>`
And this is the whole .php script:
<?php
require_once('Transip/DomainService.php');
if(isset($_GET['domain']) && strlen($_GET['domain']) > 0) {
$domain = $_GET['domain'];
try {
// Request the availability of a domain by using the Transip_DomainService API;
// we can get the following different statusses back with different meanings.
$availability = Transip_DomainService::checkAvailability($domain);
switch($availability) {
case Transip_DomainService::AVAILABILITY_INYOURACCOUNT:
$result = htmlspecialchars($domain)
. ' is helaas al <font color="red">bezet</font>, verhuizen is niet mogelijk ';
break;
case Transip_DomainService::AVAILABILITY_UNAVAILABLE:
$result = htmlspecialchars($domain)
. ' is ge-lockt, verhuizen is niet mogelijk!';
break;
case Transip_DomainService::AVAILABILITY_FREE:
$result = htmlspecialchars($domain)
. ' is <font color="green">beschikbaar!</font> <br>Klik hier en registreer direct je domeinnaam! ';
break;
case Transip_DomainService::AVAILABILITY_NOTFREE:
$result = htmlspecialchars($domain)
. ' is helaas al <font color="red">bezet</font>, verhuizen is mogelijk ';
break;
}
}
catch(SoapFault $e) {
// It is possible that an error occurs when connecting to the TransIP Soap API,
// those errors will be thrown as a SoapFault exception.
$result = 'Oeps... Vul een geldige domeinnaam in. ';
}
}
else {
$domain = '';
$result = '';
}
?>
<head>
<link rel="stylesheet" href="assets/css/main.css">
</head>
<body style="background:transparent">
<form name="domainChecker" id="notifyMe" class="news-form" style="">
<div class="form-group">
<div class="form-inline">
<input type="text" style="text-align:center;" name="domain" value="<?=htmlspecialchars($domain)?>" required type="text" id="mail-sub" placeholder="Check of jouw domeinnaam beschikbaar is!" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Check of jouw domeinnaam beschikbaar is!'" class="form-control email srequiredField" required >
<button class="btn btn-lg submit" style="background:#ffc000;border:#eeb300;color:black" type="submit">Controleer</button>
</div>
</div>
<center><font color="#FFF "><?=$result?></font></center>
</form>
</body>
I'm sure #Chad Collins will have something that works, but I was in the middle of writing this quick script, so I figure I'll post it even though you have accepted his answer. You can try it...or not (I have not tried it, so if it doesn't work, I will delete my answer):
index.php
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="assets/css/main.css">
</head>
<body style="background:transparent">
<form name="domainChecker" id="notifyMe" class="news-form" style="">
<div class="form-group">
<div class="form-inline">
<input type="text" style="text-align:center;" name="domain" value="" required type="text" id="mail-sub" placeholder="Check of jouw domeinnaam beschikbaar is!" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Check of jouw domeinnaam beschikbaar is!'" class="form-control email srequiredField" required >
<button class="btn btn-lg submit" style="background:#ffc000;border:#eeb300;color:black" type="submit">Controleer</button>
</div>
</div>
<center><font color="#FFF " id="resp"></font></center>
</form>
<script>
$("form").submit(function() {
$.ajax({
url: 'checkdomain.php',
data: $(this).serialize(),
type: 'post',
success: function(response) {
var DataResp = JSON.parse(response);
// Access the domain with-> DataResp.domain
// Access the result with-> DataResp.result
if(DataResp.result)
$("#resp").html(DataResp.result);
else
$("#resp").html("Empty message here.");
}
});
return false;
});
</script>
</body>
checkdomain.php
<?php
function CheckDomain($domain = false)
{
$domain = trim($domain);
if(empty($domain))
return array("domain"=>false,"result"=>false);
require_once('Transip/DomainService.php');
try {
// Request the availability of a domain by using the Transip_DomainService API;
// we can get the following different statusses back with different meanings.
$availability = Transip_DomainService::checkAvailability($domain);
switch($availability) {
case Transip_DomainService::AVAILABILITY_INYOURACCOUNT:
$result = htmlspecialchars($domain).' is helaas al <font color="red">bezet</font>, verhuizen is niet mogelijk ';
break;
case Transip_DomainService::AVAILABILITY_UNAVAILABLE:
$result = htmlspecialchars($domain).' is ge-lockt, verhuizen is niet mogelijk!';
break;
case Transip_DomainService::AVAILABILITY_FREE:
$result = htmlspecialchars($domain).' is <font color="green">beschikbaar!</font> <br>Klik hier en registreer direct je domeinnaam! ';
break;
case Transip_DomainService::AVAILABILITY_NOTFREE:
$result = htmlspecialchars($domain).' is helaas al <font color="red">bezet</font>, verhuizen is mogelijk ';
break;
}
}
catch(SoapFault $e) {
// It is possible that an error occurs when connecting to the TransIP Soap API,
// those errors will be thrown as a SoapFault exception.
$result = 'Oeps... Vul een geldige domeinnaam in. ';
}
// Sorry, my original post didn't return anything here! Whoops!
$response['domain'] = (!empty($domain))? $domain: "";
$response['result'] = (!empty($result))? $result:"";
return $response;
}
echo json_encode(CheckDomain((isset($_POST['domain']))? $_POST['domain']:""));
?>
Yes it is possible. Use jQuery if you like...
Using your Main.php UI file add some jQuery that calls eg: getDomainAvail.php.
So
create getDomainAvail.php file
in the new getDomainAvail.php file copy all the code given to you for the domain check and modify it with print statments of the resulting lookups.
then back in Main.php when your jquery ajax call gets returned with the result/response just assign it to a result element in the Main.php page.
Need more example than that? I can likely modify the code given to you if you want.
Cheers