I am very new to programming and I am stumped with this problem.
I want to create am autocomplete textbox.
From what I see I would need to use json. However for the source of the json I need a url to a file script, and I do not quite get this part.
This is an example from http://jqueryui.com/demos/autocomplete/#option-source
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
Does it mean that whenever I type something in the autocomplete textbox it accesses the file in the url and the file script would change dynamically according to my input?
Also, I can only see some examples of the url file in php. Can it be done in Django? such as specifying a url as the source and link that url with a view outputting the data?
Whenever you type something in the autocomplete textbox it accesses the url to retrieve the array of data. (Use firebug or chrome developer tools while testing the demo to see the HttpRequests sent as you type)
From the documentation you linked:
"When a String is used, the Autocomplete plugin expects that string to
point to a URL resource that will return JSON data."
So yes, you can use Django as long as the URL returns JSON data.
Related
I'm using Hansontable to allow users to create a matrix of input variables. How do I pass this matrix back to my views.py without it being part of the input form? I can add a form field for a 2-dimensional array, but I don't actually need it since the hansontable is creating the "input field".
I need to compute a set of results using the matrix before echoing it back to the user along with the results and storing it in a bd.
Any guidance is greatly appreciated.
Thanks.
To do pass any data to a backend without using a HTML form (without refreshing the page) you have to utilize AJAX methodologies/practice. Using jQuery you can do this like so:
$.ajax({
method: "POST",
url: "/some/url",
data: JSON.stringify(<handsontabledom>.getData())
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
Also note there is a tutorial on the Handson Tables documentation all about saving the data via a ajax request.
http://docs.handsontable.com/0.19.0/tutorial-load-and-save.html
I'm trying to get autocomplete working in my rails application using Magic Suggest.
I think this is the correct question: How can I get MagicSuggest to grab the JSON that is at the URL I give it?
This is the error that console returns when I type letters:
POST http://localhost:3000/search_foods 404 (Not Found) jquery.js:8706
Uncaught Could not reach server
Here's the magic suggest code:
input.magicSuggest({
data: "/foods/search/",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});
The Routes
resources :search_foods
The Controller and Action
class SearchFoodsController < ApplicationController
def index
render json: %['Crack', 'Cocain', 'Gorilla Test', 'Horse Test']
end
end
When I visit the /search_foods url directly I get
'Crack', 'Cocain', 'Gorilla Test', 'Horse Test'
as my code is designed to do.
I think the issue is in that MagicSuggest, by default, sends a POST request, although I'm not sure if that's entirely relevant:
You can pass the url from which the component will fetch its JSON data.Data will be fetched
* using a POST ajax request that will * include the entered text as 'query' parameter. The results
* fetched from the server can be:
* - an array of JSON objects (ex: [{id:...,name:...},{...}])
* - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
* - a JSON object whose data will be contained in the results property
* (ex: {results: [{id:...,name:...},{...}]
Try this:
input.magicSuggest({
data: "http://localhost:3000/search_foods",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});
The doc states that the component expects one of the following:
* - an array of JSON objects (ex: [{id:...,name:...},{...}])
* - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
* - a JSON object whose data will be contained in the results property
* (ex: {results: [{id:...,name:...},{...}]
When you visit /search_foods you get
'Crack', 'Cocain', 'Gorilla Test', 'Horse Test'
This does not fit any of the 3 supported cases.
My suspicions about the POST request was correct.
My friend helped out so that's why I was able to fix this.
This is what I did..
Eliminated the FoodSearch Controller, because that's not needed at all.
Created a search action in my Food Controller like so:
def search
render json: ['cocain', 'crack', 'gorilla testosterone']
end
Edited my routes to a POST request instead of a get *This was the key:
resources :foods do
collection do
post :search
end
end
--- Another option, as karlipoppins suggests, is to simply change the type of request that magicSuggest makes by including the method attribute like so:
input.magicSuggest({
method: 'get',
data: "/foods/search/",
placeholder: "Search Foods...",
valueField:'idFood',
displayField:'foodName'
});
Then I wouldn't need to change the route to post.
Added this path to the data attribute in the js
data: "/foods/search/"
This will be a huge help to anyone trying to get magicSuggest to work in rails. It's a pretty damn easy setup to be honest. That one bit and the JSON formatting was the only thing that was tripping me up here.
i am using django and cloudinary direct upload to upload iamges
it is working if the form is valid.
but if my form is not valid, my page reloaded, and then the form will ask the user to upload the image again.
any way to solve this?
my code is attached below.
since i use direct upload, after an image is uploaded. it will be displayed immediately on the front end.
but when the form is invalid and the form is refreshed, the image is gone. ( after your latest update, it is true i do not need to re upload the photo again. but the photo is gone. how to display that again?)
thanks.
<script>
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
var imag_var = $.cloudinary.image(data.result.public_id, {
format : data.result.format,
version : data.result.version,
transformation : 'form_preview'
});
$('.preview').html(imag_var);
$('.status_value').text('Uploaded:' + data.result.public_id);
$('#id_cover_image').val(data.result.public_id);
return true;
});
$('.cloudinary-fileupload').bind('fileuploadprogress', function(e, data) {
$('.progress').attr({
style : "visibility:show",
});
$('.status_value').text('Uploading...');
});
</script>
The Cloudinary javascript plugin puts the preloaded resource URI in a hidden field.
See here.
From the above one sees that if the field already exists the javascript plugin will populate it. Otherwise, it will create it.
In order to retain that URI across invalid form submissions you should create a hidden field named according to the field name you specified for cloudinary_direct_upload_field and which is populated with the value from the failed submission.
Another way to work around the issue would be to submit the form using an AJAX call. That way the data on page is retained even if validation failed and resubmission is possible. See here for an example of how that may be done.
EDIT:
Version 1.0.12 of the Cloudinary Python client library now adds the hidden field when needed out of the box so resubmissions should work. See the change log.
EDIT 2:
In order to regenerate a preview image in case of form validation error you can add something like this to the javascript code you run on page load (assuming the field name in the form is "image"):
//If form validation failed have the posted preloaded URI from the earlier
//submission so we can show preview
//pull the value from the hidden field
var imageUri = $('#direct_upload input[name="image"]').val();
//preloaded image URI structure
//{resource_type}/{type}/v{version}/{filename}#{signature}
var regex = /^([^\/]+)\/([^\/]+)\/v(\d+)\/([^#]+)#([^\/]+)$/;
//if there is value and it matches the pattern:
if (imageUri && regex.test(imageUri)) {
var uriParts = regex.exec(imageUri);
var version = uriParts[3];
var filename = uriParts[4];
//reconstruct a viable source
var src = "v" + version + "/" + filename;
//generate a cloudinary image tag and add it to the 'preview' div
$(".preview").append(
$.cloudinary.image(src, {
transformation: "form_preview" //your named transformation
})
);
}
I created a small app that takes a search query and returns mock content. You can see the app here: http://embersherpa.com/wip/search-example/app/#/search
It work correctly when entering the query via the search but not via the url.
How do I correctly handle search queries with "/" when entered via url?
You should probably not put your keyword directly into the URL. Instead escape it first with encodeURIComponent and unescape it with decodeURIComponent in your model hook. The rough code look like this:
serialize : function(model){
// model is the keyword in your case
return {keyword: encodeURIComponent(model)};
},
model : function(params){
var keyword = decodeURIComponent(params.keyword);
// do what you need to do with the keyword
}
I own a small website that display to the users an html template (with css). Each user can change the template (customizable).
By default i have a template i copy everytime to a new user or if i get nice template (high rates) users can choose it.
instead of copying the template over and over, is there an easy way for me to create 1 template and then when the page load, it shows on the user page and then he can interact (ajax calls, href links etc...)
for example:
new user logged for the first time, the "user license agreement" shows then he click accept and his page shows up. this "home" page has forms, links, images etc... using a default template. that is the one i want to load dynamically instead of copying this template to each users.
why: i found HTML error in the page and now i need to copy this template to 127 users ... which is a pain.
i am using LAMP
thanks
yes using jQuery!
$('#divID').load('pathToHTMLTemplate') is your answer as long as you have the html file stored on same domain :)
This will fetch the html template using ajax and append its content to the div you want. It can also be 'body'.
Here is the documentation which should tell you everything you need to.
Once the template is loaded you can load the user specific data using ajax or any app server you are using. .load function provides a callback:
$('#divID').load('pathToHTMLTemplate', function(){
// now the template is loaded and you can maniupulate it further or load user specific data
});
It sounds to me (just going off of your post) that you have a directory somewhere with a bunch of files "user1.html", "user2.html" or something similar. All of these are either the same or similar, since they're basically the same template.
My recommendation:
Have a database table (or a flat file, but I recommend a database table) that maps a user ID (or name, however you have them arranged) to a template. For example, if user1 and user2 use template_default.html, but user3 uses template_popular.html, you would have the following in your database:
name|template
user1|template_default.html
user2|template_default.html
user3|template_popular.html
Then in whatever code is currently deciding which page to show the user, change it to pull the user's chosen template out of the database and display that instead. So then you only have 1 or 2 pages instead of 127.
If the user is allowed to make edits to their template, that could be stored as metadata in the table as well, then you could use substitution parameters to add it into the template.
Example:
MySQL table:
CREATE TABLE user_templates (
`user` varchar(100),
template varchar(100)
);
Upon receiving a new user:
INSERT INTO user_templates(`user`,template) VALUES("<username>","default_template.html");
Upon user choosing a new template:
UPDATE user_templates set template = "<new template>" WHERE `user` = "<username>";
Upon user loading the user's page (this done in php):
$template = "default_template.html";
$query = "SELECT template FROM user_templates WHERE `user` = \"" . mysql_real_escape_string($username) . "\"";
$result = mysql_query($query,$databaseHandle);
if ($result && mysql_num_rows($result) > 0) {
$template = mysql_result($result,0,"template");
}
// 1st way to do it
$pageToLoad = "http://www.someserver.com/templates/$template";
header("Location: $pageToLoad");
// 2nd way, if you want it embedded in a page somewhere
$directory = "/var/www/site/templates/$template";
$pageContents = file_get_contents($directory);
print "<div id=\"userPage\">$pageContents</div>";
I assume you mean that you have an HTML file that is customized for each user (look, feel, etc):
User1-theme.html
User2-theme.html
User3-theme.html
User4-theme.html
User4-theme.html
Then you would have a file that has all of your ajax calls, links, etc that you want for each user:
User-Controls.html
What you need to do is
Ensure jQuery is downloaded and included on each of your User Theme Pages.
Add this code snipplet to each of your User Theme Pages:
$("#myDiv").load("User-Controls.html")
(where #myDiv is the div ID on the template page that you want to load the controls into
and User-Controls.html is the path to the html file containing the controls you want to load