I am working on an element of an application I am developing. I have a small web app dedicated to keep track of clients for a business. Currently my capability is pretty limited. I store the note along with other attributes in the clients table. I decided to try and make it a bit better by adding a note table and updating an ext js panel with the notes.
Everything works if I only have one note in my notes query.
Otherwise I receive this error.
SyntaxError: invalid property id
..._date":"2013-10-08","note_body":"abcd"},{"username":"rcox","bdev_firstname":"Tre...
This is the PHP I am using.
case 'note':
$userid = $_REQUEST['clientID'];
$query = $dbh->prepare("SELECT a.username, b.bdev_firstname, b.bdev_lastname, n.note_date, n.note_body FROM admin a, bdevs b, clients c, notes n WHERE c.clientID=".$userid.";");
$query->execute();
while($cli = $query->fetch()) {
$json = '{"username":"'.$cli['username'].'","bdev_firstname":"'.$cli['bdev_firstname'].'","bdev_lastname":"'.$cli['bdev_lastname'].'","note_date":"'.$cli['note_date'].'","note_body":"'.$cli['note_body'].'"},';
$note .= $json;
}
$note = trim($note, ',');
echo '{success: true, data:'.$note.'}';
break;
This is my ext js function.
function getNote(){
var selectedNote = userGrid.getSelectionModel().getSelected();
Ext.Ajax.request({
url: 'inc/template.php',
params: {list: 'note',
clientID: selectedNote.get('clientID')
},
method: 'POST',
success: function(f,a){
var jsonData = Ext.util.JSON.decode(f.responseText);
if(jsonData.success == true)
{
var username = jsonData.data.username;
var bdev_firstname = jsonData.data.bdev_firstname;
var bdev_lastname = jsonData.data.bdev_lastname;
var note_date = jsonData.data.note_date;
var note_body = jsonData.data.note_body;
RightPanel.update('<b>Admin:</b> ' + username + '<br/><b>Buissiness Dev Rep:</b> ' + bdev_firstname + bdev_lastname + '<br/><b>Note Date:</b> ' + note_date + ' <br/>----------<br/> ' + note_body);
}
else
{
RightPanel.update('Access Denied');
}
},
failure: function(f,a){
Ext.Msg.alert("Error", "Access Denied");
}
});
}
This has been answered below. For more troubleshooting on this topic you can visit my question on Sencha Forums. http://www.sencha.com/forum/showthread.php?273478-MOVED-POST-Posting-a-JSON-array-with-multiple-values-to-ext-js-panel&p=1002545#post1002545
What's the point of using json if you actually don't use it.
case 'note':
$userid = $_REQUEST['clientID'];
$query = $dbh->prepare("SELECT a.username, b.bdev_firstname, b.bdev_lastname, n.note_date, n.note_body FROM admin a, bdevs b, clients c, notes n WHERE c.clientID = ?");
$query->execute(array($userid));
$response = json_encode(array('success'=> true, data => $query->fetchAll(PDO::FETCH_ASSOC)));
echo $response;
break;
And then ext.js part where your error lies - if data is an array, you need to iterate over it, before you can access associative fields, right?
if(jsonData.success == true)
{
var i, item;
for( i = 0; i < jsonData.data.length; i++; ) {
item = jsonData.data[i];
RightPanel.update('<b>Admin:</b> ' + item.username + '<br/><b>Buissiness Dev Rep:</b> ' + item.bdev_firstname+" "+item.bdev_lastname + '<br/><b>Note Date:</b> ' + item.note_date + ' <br/>----------<br/> ' + item.note_body);
}
}
Related
I have an AJAX request which serializes form data and sends it to a database. When teh data is serialised, I see it renders the full text inout, but when it stores it in the database, it only saves the first letter of every word?
For example it will serialize this to be sent:
splashText=Silver Glaze
but the database will save if there is none line:
S
if there are multiple rows in the submitted table data is captured in the database as follows:
row 1 would = S
row 2 would = i
Where as I'm trying to get it as follows:
row 1 would = Silver Glaze
row 2 would = Next option selected in the row and so on...
The serialised data POSTed is as follows (with 2 rows):
job_ref=3123&job_desciption=321&sil_cost=1&sil_cost_price=2.00&sub_total=119.75&item_name%5B%5D=1&item_quantity%5B%5D=1&item_unit%5B%5D=1&item_glass%5B%5D=110&item_splash%5B%5D=20&item_colour%5B%5D=-&item_HQuan%5B%5D=1&item_HDiam%5B%5D=2.25&item_CQuan%5B%5D=1&item_Total%5B%5D=56.25&item_cil_row%5B%5D=0.000001&item_name%5B%5D=1&item_quantity%5B%5D=1&item_unit%5B%5D=1&item_glass%5B%5D=110&item_splash%5B%5D=20&item_colour%5B%5D=-&item_HQuan%5B%5D=1&item_HDiam%5B%5D=7.5&item_CQuan%5B%5D=1&item_Total%5B%5D=61.50&item_cil_row%5B%5D=0.000001&glassText=6mm Toughened Extra Clear6mm Toughened Extra Clear&splashText=Rainbow SparkleRainbow Sparkle&holeText=22mm27mm
The code to serialise the form:
var form_data = $(this).serialize() + '&glassText=' + $('.item_glass').children("option").filter(":selected").text() + '&splashText=' + $('.item_splash').children("option").filter(":selected").text() + '&holeText=' + $('.item_HDiam').children("option").filter(":selected").text();
The + is for getting the text value of the input instead of the value. I think this may be the problem but im not sure how to fix it?
PHP Post:
for($count = 0; $count < count($_POST["item_name"]); $count++)
{
$query = "INSERT INTO tbl_order_items
(order_id, item_name, item_quantity, item_unit,item_glass, item_splash, item_HQuan,item_HDiam,item_CQuan,item_colour,item_total,user_id)
VALUES (:order_id, :item_name, :item_quantity, :item_unit,:item_glass,:item_splash,:item_HQuan,:item_HDiam,:item_CQuan,:item_colour,:item_total,:user_id)";
$statement = $connect->prepare($query);
$statement->execute(
array(
':order_id' => $order_id,
':item_name' => $_POST["item_name"][$count],
':item_quantity' => $_POST["item_quantity"][$count],
':item_unit' => $_POST["item_unit"][$count],
':item_glass' => $_POST["glassText"][$count],
':item_splash' => $_POST["splashText"][$count],
':item_HQuan' => $_POST["item_HQuan"][$count],
':item_HDiam' => $_POST["holeText"][$count],
':item_CQuan' => $_POST["item_CQuan"][$count],
':item_colour' => $_POST["item_colour"][$count],
':item_total' => $_POST["item_Total"][$count],
':user_id' => $user_id
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
echo 'ok';
}
}
It is a dynamic table being saved. Thats what the count is.
To put context on the dynamic table here is a screenshot:
:
Because you don't provide the html code, so I assume the 'Review Quote' button is the submit button. So, try this:
change from
var form_data = $(this).serialize() + '&glassText=' + $('.item_glass').children("option").filter(":selected").text() + '&splashText=' + $('.item_splash').children("option").filter(":selected").text() + '&holeText=' + $('.item_HDiam').children("option").filter(":selected").text()
To:
var glassText = '';
$('.item_glass').each(function(){
glassText+='&glassText[]='+$(this).find(":selected").text().replace(' ','+');
});
var splashText = '';
$('.item_splash').each(function(){
splashText+='&splashText[]='+$(this).find(":selected").text().replace(' ','+');
});
var holeText = '';
$('.item_HDiam').each(function(){
holeText+='&holeText[]='+$(this).find(":selected").text().replace(' ','+');
});
var form_data = $(this).serialize() + glassText + splashText + holeText;
So i am creating a simple form that checks whether or not the value that the user is inputting exists or not in my DB using jQuery. Everything up until now is working so far however i find myself stuck at this next part.
To easily explain i will just show an example of what i am trying to achieve.
For this example i will be "weeden"
weeden has an ID of 255 in the company table of my database.
If the user types in "weeden" into the client field
To the right of the client field (on the web form), the text "weeden is unavailable" will appear
what i would like to have happen instead is this: "ID 255 is unavailable"
Here is the relevant code.
HTML FORM
<form action="addrecord.php" method="post" autocomplete="off"/>
<div class="form-field">
<label for="client">Client: </label>
<input type="text" name="client" id="client" class="check-exists" data-type="client" placeholder="#">
<span class="check-exists-feedback" data-type="client"></span>
</div>
jQuery Function
$.fn.existsChecker = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function(){
var self = $(this),
selfType = self.data('type'),
selfValue,
feedback = $('.check-exists-feedback[data-type=' + selfType + ']');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()){
selfValue = self.val();
if(selfValue.length >= 1){
$.ajax({
url: 'check.php',
type: 'get',
dataType: 'json',
data: {
type: selfType,
value: selfValue
},
success: function(data){
if(data.exists !== undefined){
if (data.exists === true){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is available');
}
}
},
error: function(){
}
});
}
}
}, 1000);
}
});
});
};
Check.php
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,
array('client')
)
){
switch($type){
case 'client':
$check = $db->prepare("
SELECT COUNT(*) AS count
FROM company
WHERE name = :value
");
break;
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
Any help/suggestions would be greatly appreciated. I consider myself a beginner, this is my first time working on a web project.
Just to clarify ahead of time, there are many other input fields on the same webform such as: email, date, first, last, etc.
I hope my question was clear enough. Thank you
You have to change your Query to something like this:
$check = $db->prepare("
SELECT id, COUNT(*) AS count
FROM company
WHERE name = :value
");
I assume that your primary key field on the company-table is named id.
And finally store the id in the output-Array
$result = $check->fetchObject();
$output['exists'] = $result->count ? true: false;
$output['id'] = $result->id;
Then you can output the id like so:
if (data.exists === true){
feedback.text('ID ' + data.id + ' is unavailable');
}
You can handle everything in query
$db= new PDO('mysql:host=host;dbname=mydb', 'user', 'pass');
if(isset($_GET['type'], $_GET['value'])){
$type = strtolower(trim($_GET['type']));
$value= trim($_GET['value']);
$output = array('exists' => false);
if(in_array($type,array('client'))){
switch($type){
case 'client':
$check = $db->prepare("
SELECT (CASE WHEN(COUNT(id)>0) THEN id ELSE FALSE END) AS count
FROM company WHERE name = :value ");
break;
}
$check->execute(array('value'=> $value));
$output['exists'] = $check->fetchObject()->count ? true: false;
echo json_encode($output);
}
In Ajax success
if(data.exists !== undefined){
if (!data.exists){
feedback.text(selfValue + ' is already taken.');
}else {
feedback.text(selfValue + ' is already taken.');
}
}
Good evening.
I have this jquery code which allows me, once you press the Enter key, to post a comment.
Fattio that I run an append with the username and the content that the user wants to publish.
In addition to the username I would also like to "hang" the profile picture using their path. How do I post a photo?
Thanks for your help. Here's the code:
function commento_post(id_post)
{
$('.form-commento'+id_post).click(function ()
{
$('#ins_commento'+id_post).keydown(function (e)
{
var message = $("#commento"+id_post).val();
var username = $("#username").val();
var id_user = $("#id_user").val();
if(e.keyCode === 13)
{
$.ajax(
{
type: 'POST',
url: 'http://localhost/laravel/public/index.php/post/ins_commento',
data: { commento: message, id_post: id_post },
success: function(data)
{
$('#commento'+id_post).val('');
$('#commentscontainer'+id_post).append
(
/*$(".username-commento"+id_post).html
(*/
$('<a/>',
{
text : username, href : 'http://localhost/laravel/public/index.php/utente/'+id_user
}).css({'font-weight':'bold'})
//)
).append(' ').append(message).append($('<br/>'));
var el = $('#numero_commenti'+id_post);
var num = parseInt(el.text());
el.text(num + 1);
}
});
}
});
});
}
In your success function, you could simplify everything quite a bit in the following way while not using jQuery append so much, but just using a variable to store your code and then appending it in one go. This will allow you to append all sort of elements, it's easily parseable for the you and it reduces the amount of calls you have to make.
// Add whatever you want your final HTML to look like to this variable
var html = "<a href='http://localhost/laravel/public/index.php/utente/" + id_user + "' style='font-weight: bold;'>" + username + "</a>";
html += message;
// add an image
html += "<img src='path/to/image.jpg' />"
html += "<br />";
// append to code you constructed above in one go
$('#commentscontainer' + id_post).append(html);
Update
I amended an incorrect quote and changed + id_user + "to + id_user + "', which makes everything after it work.
I have an HTML + SPARQL + JSON + JavaScript program that works correctly, shown here: http://ontomatica.com/public/test/clavius.html
Here is the SPARQL + JSON + JavaScript code:
function retrieveData() {
var query = "PREFIX : <http://dbpedia.org/resource/> PREFIX dbp: <http://dbpedia.org/ontology/> PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> PREFIX dbpprop: <http://dbpedia.org/property/> SELECT ?person ?b_date ?d_date ?abstract ?thumbnail WHERE { ?person rdf:type dbp:Person ; dbp:birthDate ?b_date ; dbp:deathDate ?d_date ; dbp:abstract ?abstract . OPTIONAL { ?person dbp:thumbnail ?thumbnail } FILTER ( ?b_date >= '1488-01-01'^^xsd:date && ?b_date < '1600-01-01'^^xsd:date && ?d_date < '1650-01-01'^^xsd:date ) FILTER ( langMatches(lang(?abstract), 'EN')) } ORDER BY ?person ?b_date";
var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['person']['value'].replace("http://dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> (" + value['b_date']['value'] + " - " + value['d_date']['value'] + ")</h3></div>";
if (value['thumbnail'] != null)
html += "<div class='inline thumb'><img style='width: 200px' src='" + value['thumbnail']['value'].replace("200px", "150px") + "'/></div>";
else
html += "<div class='inline thumb'><img src=''/></div>";
html += "<div class='inline abstract'>" + value['abstract']['value'] + "</div><div class='clear'></div><br>";
$('#output_div').append(html);
}
);
}
However, a new version of the program does not work correctly. Here are the components.
The modified SPARQL query works correctly:
PREFIX : <http://dbpedia.org/resource/>PREFIX dbp: <http://dbpedia.org/ontology/>PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>PREFIX dbpprop: <http://dbpedia.org/property/>SELECT ?food ?abstract ?thumbnail ?caption WHERE { ?food rdf:type dbp:Food ; dbpprop:name ?name ; dbpprop:caption ?caption ; dbp:abstract ?abstract . OPTIONAL { ?food dbp:thumbnail ?thumbnail } FILTER ( regex(?name, "Calzone" )) FILTER ( langMatches(lang(?abstract), "EN"))} ORDER BY ?food
I've tested the query on the DBpedia Virtuoso SPARQL end point. Here is the result:
http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=PREFIX+%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2F%3EPREFIX+dbp%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fontology%2F%3EPREFIX+rdf%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23%3EPREFIX+dbpprop%3A+%3Chttp%3A%2F%2Fdbpedia.org%2Fproperty%2F%3ESELECT+%3Ffood+%3Fabstract+%3Fthumbnail+%3Fcaption+WHERE+{+%3Ffood+rdf%3Atype+dbp%3AFood+%3B+dbpprop%3Aname+%3Fname+%3B+dbpprop%3Acaption+%3Fcaption+%3B+dbp%3Aabstract+%3Fabstract+.+OPTIONAL+{+%3Ffood+dbp%3Athumbnail+%3Fthumbnail+}+FILTER+%28+regex%28%3Fname%2C+%22Calzone%22+%29%29+FILTER+%28+langMatches%28lang%28%3Fabstract%29%2C+%22EN%22%29%29}+ORDER+BY+%3Ffood&format=text%2Fhtml&timeout=30000&debug=on
So far, so good.
Here is the modified JSON + JavaScript program (with the operational SPARQL query).
function retrieveData() {
var query = "PREFIX : <http://dbpedia.org/resource/>PREFIX dbp: <http://dbpedia.org/ontology/>PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>PREFIX dbpprop: <http://dbpedia.org/property/>SELECT ?food ?abstract ?thumbnail ?caption WHERE { ?food rdf:type dbp:Food ; dbpprop:name ?name ; dbpprop:caption ?caption ; dbp:abstract ?abstract . OPTIONAL { ?food dbp:thumbnail ?thumbnail } FILTER ( regex(?name, "Calzone" )) FILTER ( langMatches(lang(?abstract), "EN"))} ORDER BY ?food";
var url = 'http://dbpedia.org/sparql?default-graph-uri=http%3A%2F%2Fdbpedia.org&query=' + encodeURIComponent(query) + '&output=json';
$.ajax({
url: url,
dataType: "json",
success: function (data) {
$('#results').show();
$('#raw_output').text(JSON.stringify(data, null, 3));
handle_json(data);
},
error: function(e) {}
});
}
function handle_json(json) {
$('#output_div').text("");
$.each(
json['results']['bindings'], function(index, value) {
var html = "";
name = value['food']['value'].replace("http://dbpedia.org/resource/", "");
name = decodeURIComponent(name.replace(/_/g, " "));
html += "<div><h3><b>" + name + ":</b> (" + value['caption']['value'] + ")</h3></div>";
if (value['thumbnail'] != null)
html += "<div class='inline thumb'><img style='width: 200px' src='" + value['thumbnail']['value'].replace("200px", "150px") + "'/></div>";
else
html += "<div class='inline thumb'><img src=''/></div>";
html += "<div class='inline abstract'>" + value['abstract']['value'] + "</div><div class='clear'></div><br>";
$('#output_div').append(html);
}
);
}
Here are the differences between the correct program and the incorrect program.
The DBpedia ontology term is changed from 'person' to 'food'.
The query field to be formatted in HTML output (encoded by <div><h3></div></h3>) is changed from ['b_date'] to ['caption'].
I suspect the problem is local to the $.ajax clause and the JSON.stringify statement:
$('#raw_output').text(JSON.stringify(data, null, 3));
Bottom line: I would like to generalize the first program for other applications, but am fumbling the JSON statements.
Why does the second program fail when it is based on the first program? What am I doing wrong?
Is there a better way to generalized the program (1) for other SPARQL queries with different terms; (2) with different numbers of terms; (3) for a SPARQL query of federated databases (only DBpedia is used in the example, but I'd like to format terms from a federated query - mashing up data from different RDF triplestores).
Working Example
Non-working Example
The problem is that you've got unescaped quotes in the second query, which means that the Javascript engine sees a syntax error (an unexpected identifier). The relevant part is in:
var query = "…FILTER ( regex(?name, "Calzone" )) FILTER ( langMatches(lang(?abstract), "EN"))} ORDER BY ?food";
Notice in the syntax highlighting that the string ends at the " immediately before Calzone, etc.
I found this by looking at the Javascript console in Google Chrome when loading your second sample page:
You can fix this by doing:
var query = "…FILTER ( regex(?name, 'Calzone' )) FILTER ( langMatches(lang(?abstract), 'EN'))} ORDER BY ?food";
Once you've done that, you get the kinds of results you'd expect:
I'm posting ckeditor content via Ajax to php. But getting 4-5 sentence of posted material in my db table. I wonder, Is there any size limitation for ajax post? is there any way to post big text contents via ajax?
My js looks like that
function postViaAjax(autosaveMode) {
var name = $("#name").val();
var title = $("#title").val();
var menu = $("#menu").val();
var parentcheck = $(".parentcheck:checked").val();
var id = $("#id").val();
if (parentcheck == 0) {
var parent = parentcheck;
} else {
var parent = $("#parent").val();
}
var content = CKEDITOR.instances['content'].getData();
var dataString = 'name=' + name + '&title=' + title + '&menu=' + menu + '&parentcheck=' + parentcheck + '&id=' + id + '&parent=' + parent + '&content=' + content;
$.ajax({
type: "POST",
url: "processor/dbadd.php",
data: dataString,
dataType: "json",
success: function (result, status, xResponse) {
var message = result.msg;
var err = result.err;
var now = new Date();
if (message != null) {
if (autosaveMode) {
$('#submit_btn').attr({
'value': 'Yadda saxlanıldı ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
} else {
$.notifyBar({
cls: "success",
html: message + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds()
});
}
}
if (err != null) {
$.notifyBar({
cls: "error",
html: err
});
}
}
});
};
The HTTP specification doesn't impose a specific size limit for posts. They will usually be limited by either the web server or the programming technology used to process the form submission.
What kind of server do you use?
There isn't any size limitation for POSTs in HTTP.
Maybe you have an & in your content variable. Then everything after that would be stripped after that.
Other than that what type do you use for your data column in the database? Is it, by any chance, something like varchar(1000)? Then anything bigger would also get stripped.
Check what you actually receive on the server end, so you know if you've got a problem with the code or the database.
You have a limitation on the Apache server. Look for LimitRequestBody directive.
This may be helpful:
http://gallery.menalto.com/node/14870
In theory the limits on AJAX requests are the same on all the other requests, so it depends on your web server/app setup. See also Max length of send() data param on XMLHttpRequest Post