X editable django and jquery yu - ajax

I'm trying to update a field using X Editable but I do not make it till the end.
Here is my code:
#views.py
def update_task(request, task_id):
if request.is_ajax():
task = request.GET.get('task')
updated_task = Task.objects.get(pk=task_id)
updated_task.task = task
updated_task.save()
return HttpResponse('true')
else:
return HttpResponse('not ajax')
#urls.py
url(r'^update_task/(?P<task_id>\d+)/$', 'todo.views.update_task', name='update_task'),
#html file
<script>
$(document).ready(function () {
$("#task").editable({
type: 'text',
pk: 144,
url: '/update_task/144/',
title: 'Enter task',
});
});
</script>
When I'm trying to update it console gives me:
link/update_task/144 404 (Not found)

I don't see that you have a url defined to capture the task_id
I think you need to either put the task_id in the parameter, so something like url + '?task_id=144.
If you do this, you need to change your javascript line to look like this:
url: '/update_task/' + '?task_id=144',
or, you need to leave it as is, and add a line to your url conf to capture the parameter:
url(r'^update_task/(?P<task_id>\d+)/$', 'todo.views.update_task', name='update_task'),
and then in your views:
def update_task(request, task_id=None):#if task_id is optional, set it to =None or something
if request.is_ajax():
do stuff here with task_id
also, you will need to take out the task_id = request.GET.get('task_id')
because task_id is not in the GET body.

Related

Ideal way to ajax load a view in Drupal 8 with contextual filters

I have a taxonomy called category.
I have a menu with links to each of these taxonomy items.
The Taxonomy page for each of these items has that menu and also contains a view which uses a contextual filter from the URL to filter the content of the view to content with that taxonomy term.
I wanted to Ajax load the view content when one of these menu items is clicked.
I've been able to achieve the desired result by enabling ajax on the view and using the following JavaScript.
(function ($) {
Drupal.behaviors.course_browser = {
attach: function (context, settings) {
// should only be one menu, but guard against 0, and avoid the if statement.
context.querySelectorAll(".menu--categories").forEach((menu) => {
// for each link in the menu
menu.querySelectorAll(".nav-link").forEach((link) => {
// on click
link.addEventListener("click", (event) => {
event.preventDefault();
// fetch the taxonomy term id from menu link
let tid = event.target.dataset.drupalLinkSystemPath.replace(
"taxonomy/term/",
""
);
// make the ajax call
$.ajax({
url: "/views/ajax",
type: "post",
data: {
view_name: "course_browser",
view_display_id: "block_1",
view_args: tid,
},
success: (response) => {
response.forEach((action) => {
// the response contains a number of commands; I'm not sure
if (
action.command === "insert" &&
action.method === "replaceWith"
) {
let viewElement = document.querySelector(VIEW_SELECTOR);
// update the html of the course browser
viewElement.innerHTML = action.data;
// update the url in the browser
window.history.pushState("", "", event.target.href);
// seperate function to adjust my page title
updatePageTitle(event.target.textContent);
// call drupal behaviours passing context to ensure all the other js code gets a chance to manipulate the new content
Drupal.attachBehaviors(viewElement);
}
});
},
error: function (data) {
console("An error occured fetching the course browser");
},
});
});
});
});
},
};
})(jQuery);
I'm looking for feedback on my approach here; my main concern at the moment is the way I handle the response. When I look at the response I receive something like that shown below:
0: {command: "settings", settings: {…}, merge: true}
1: {command: "add_css", data: "<link rel="stylesheet" media="all" href="/core/modules/views/css/views.module.css?qcog4i" />↵"}
2: {command: "insert", method: "append", selector: "body", data: "<script src="/core/assets/vendor/jquery/jquery.min…/js/modules/views/ajax_view.js?qcog4i"></script>↵", settings: null}
3: {command: "insert", method: "replaceWith", selector: ".js-view-dom-id-", data: "The HTML"}
As you can see, I'm manually handling the response by cherry picking the part I want and replacing the HTML of view. Based on what I've seen around Drupal, I think there should be something I can pass this response to that handles it automatically. When I look at the window object of the browser, I can see Drupal.AjaxCommands which looks like it was designed to handle this, but I'm not sure how I should be using this.
I also note that in the case I can simply pass this response to something to have those AjaxCommands executed, the selector ".js-view-dom-id-" isn't right. So I could tweak the response before I pass it, or if someone knows a way to adjust the ajax request to perhaps get the right selector, that would be ideal.
Sorry if this info is readily available somewhere...there are quiet a few resources around related to Drupal and Ajax but I haven't been able to find examples of exactly what I'm doing here, the circumstances always seem to differ enough that I can't use them.
Thanks for any help.

How to add a dropdown list with page list in CQ5?

I have the following code base to share with you guys to list the pages that fetch using the query builder via AJAX call. We have to pass the URL and the parameters to fetch the child pages from the URL that we provide.
I have put some console.log to track the values of each states.
replace the with your project.
<featurearticles
jcr:primaryType="cq:Widget"
fieldLabel="Article Pages"
itemId="selectauthorId"
name="./authorselect"
type="select"
xtype="selection">
<options jcr:primaryType="cq:WidgetCollection"/>
<listeners
jcr:primaryType="nt:unstructured"
loadcontent="function(box,value) {
CQ.Ext.Ajax.request({
url: '/bin/querybuilder.json',
success: function(response, opts) {
console.log('Response from the ajax');
var resTexts = $.parseJSON(response.responseText);
var selectopts = [];
console.log(resTexts);
$.each(resTexts.hits, function(key, page) {
console.log(page);
selectopts.push({value: page['path'], text:page['name']});
});
console.log(selectopts);
box.setOptions(selectopts);
},
params: {
'type' :'cq:Page',
'group.1_path' : '/content/<PROJECT_NAME>/Feature_Articles'
}
});
}"
selectionchanged="function(box,value) {
var panel = this.findParentByType('panel');
var articleTitle = panel.getComponent('articleTitleId');
CQ.Ext.Ajax.request({
url: value + '/_jcr_content/par/featurearticleintro.json',
success: function(response, opts) {
console.log('success now');
var resTexts = $.parseJSON(response.responseText);
console.log(resTexts);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
}
});
}"/>
</featurearticles>
If you have any better idea than this, I would like to know about that.
Cheers,
Another alternative is to use the "options" attribute of the selection xtype to fetch the dropdown list options from an AJAX call via a servlet or sling selector. The widgets api (http://dev.day.com/docs/en/cq/5-6/widgets-api/index.html - search for "selection") says this for the options attribute:
If options is a string it is assumed to be an URL pointing to a JSON
resource that returns the options (same structure as above applies).
This should be either an absolute URL or it can use the path of the
content resource being edited using a placeholder
(Selection.PATH_PLACEHOLDER = "$PATH"), for example:
$PATH.options.json.
So it may be a cleaner approach to build a servlet that will respond with JSON to an AJAX request, then put this servlet as the "options" attribute. For example, the attribute might be something like options="/libs/myServlet" or something like options="$PATH.options.json". That may make the dialog cleaner (no listener required), and it uses built-in CQ capability to fetch options via AJAX.
We can use the dynamic dropdown as below:
<item
jcr:primaryType="cq:Widget"
fieldLabel="Item"
name="./item"
optionsRoot="root"
options="/bin/service/item.json"
type="select"
xtype="selection"/>
options: the url will return the json format for the selection xtype
optionsRoot: the name of the root item of the json
optionsTextField: the name of text field (default value: "text")
optionsValueField: the name of the value field (default value: "value")
Example of json: {"root":[{"text":"Item 1", "value":"Value 1"},{"text":"Item 2", "value":"Value 2"},{"text":"Item 3", "value":"Value 3"}]}
Selection xtype

ruby, sinatra, Plivo API: render API call as HTML

I am making an API call to Plivo to list available telephone numbers.
I can access the returned response and print the desired elements in my terminal BUT I do not know how to render them as HTML on my web page. This is my problem.
In the terminal, the response to a successful call is:
{"api_id"=>"23f1f0f0-0808-11e3-a442-22000ac6194a",
"meta"=>
{"limit"=>1, "next"=>nil, "offset"=>0, "previous"=>nil, "total_count"=>1},
"objects"=>
[{"group_id"=>"23928520636825",
"number_type"=>"local",
"prefix"=>"646",
"region"=>"New York, UNITED STATES",
"rental_rate"=>"0.80000",
"resource_uri"=>
"/v1/Account/MAZDQ1ZJIYMDZKMMZKYM/AvailableNumberGroup/23928520636825/",
"setup_rate"=>"0.00000",
"sms_enabled"=>true,
"sms_rate"=>"0.00800",
"stock"=>50,
"voice_enabled"=>true,
"voice_rate"=>"0.00900"}]}
"0.00900"
New York, UNITED STATES
646
The Ajax script which generates the response is:
$(".localsearch").click(function() {
var country_iso = $("#local").val();
var region = $("#region").val();
var prefix = $("#prefix").val();
$.ajax({
type: "GET",
url: "/local/data",
data: { 'country_iso' : country_iso, 'region' : region, 'prefix' : prefix },
success: function(data) {
alert(data)
},
});
});
The alert doesn't help and just shows the entire page.
The ruby code is:
get '/local/data' do
country_iso = params[:country_iso]
region = params[:region]
prefix = params[:prefix]
p = RestAPI.new(AUTH_ID, AUTH_TOKEN)
params = {'country_iso' => country_iso, 'region' => region, 'prefix' => prefix, 'limit' => '1'}
response = p.get_number_group(params)
obj = response.last
pp response.last
#region = obj["objects"][0]["region"]
puts #region
#prefix = obj["objects"][0]["prefix"]
puts #prefix
erb :search
end
So, sorry it's long and to summarize, how do I extract elements from the API response and print them as HTML? Many thanks in advance.
In the view I have tried:
<%= #region %> and <%= obj['region'] %> and <%= obj['objects][0]['region'] %>and none of them work.
Yours is a perfect use case of of rendering a partial through a ajax call.
So what you can do is:
Make your Sinatra action return html using rails like render partial functionality like this
http://steve.dynedge.co.uk/2010/04/14/render-rails-style-partials-in-sinatra/
(to get rails like partial functionality in sinatra you can use this gem also https://rubygems.org/gems/sinatra-partial )
Now since now your sinatra action returns a valid html, in your ajax success function you can just write:
$(".localsearch").click(function() {
var country_iso = $("#local").val();
var region = $("#region").val();
var prefix = $("#prefix").val();
$.ajax({
type: "GET",
url: "/local/data",
data: { 'country_iso' : country_iso, 'region' : region, 'prefix' : prefix },
success: function(data) {
$('unique_identifier_of_your_partial_on_the_html_dom').html(response)
}
});
});
another example of rendering partial in sinatra:
Ruby w/ Sinatra: Could I have an example of a jQuery AJAX request?
extract out the html that you want to populate with the response from this ajax call into a a separate erb file lets say , _my_response_partial.html.erb
now suppose this is your search.html.erb file.
#something somrthing
<%= erb(:my_response_partial, locals => {:region => #region, :prefix => #prefix},:layout => false) %> #pass whatever data you want to pass to a partial using locales
# something something
and in your get action replace the last line with:
erb(:my_response_partial, locals => {:region => #region, :prefix => #prefix},:layout => false)
By this way your action will just return the html required to populate that partial.

Django Jquery Get URL Conf

Ok, so I'm trying to call the function
def user_timetable(request, userid):
user = get_object_or_404(TwobooksUser,id = userid)
timeSlots = TimeSlot.objects.filter(user = request.user)
rawtimeslots = []
for timeSlot in timeSlots:
newSlot = {
'userid': timeSlot.user.id,
'startTime': str(timeSlot.startTime),
'endTime': str(timeSlot.endTime),
}
rawtimeslots.append(newSlot)
return HttpResponse(simplejson.dumps(rawtimeslots))
through the javascript in
{% include 'elements/header.html' %}
<script type='text/javascript'>
$(document).ready(function() {
$.get('/books/personal{{ user.id }}/timetable/', {}, function(data) {
data = JSON.parse(data);
var events = new Array();
for (var i in data) {
events.push({
id: data[i].id,
title: '{{ request.user.name }}',
start: Date.parse(data[i].startTime, "yyyy-MM-dd HH:mm:ss"),
end: Date.parse(data[i].endTime, "yyyy-MM-dd HH:mm:ss"),
allDay: false
});
}
where the above exists in a template that's being rendered (I think correctly).
The url conf that calls the function user_timetable is
url(r'^books/personal/(?P<userid>\d+)/timetable/$',twobooks.ajax.views.user_timetable),
But, user_timetable isn't being called for some reason.
Can anyone help?
EDIT-
Ok the original problem was that the template was not being rendered correctly, as the url in firebug comes to '/books/personalNone/timetable/' , which is incorrect.
I'm rendering the template like this -
def renderTimetableTemplate(request):
#if request.POST['action'] == "personalTimetable":
user = request.user
return render_to_response(
'books/personal.html',
{
'user': user,
},
context_instance = RequestContext(request)
)
Is there a mistake with this?
There is a slash missing after "personal"
$.get('/books/personal{{ user.id }}/timetable/', {}, function(data) {
should be
$.get('/books/personal/{{ user.id }}/timetable/', {}, function(data) {
Btw. you should use the {% url %} template tag.
There is a mismatch between the data you're converting to JSON and passing to the script, and the data that the script is expecting. You are passing a userId element in each timeslot, whereas the script is expecting just id.
This error should have shown up in your browser's Javascript console, and would be even easier to see in Firebug (or Chrome's built-in Developer Tools).

Valums Ajax Upload with Codeigniter: Get Parameters!

How do I use paramaters with Valums Uploader and Codeigniter?
With Valums the parameters are set like so:
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/server-side.upload',
// additional data to send, name-value pairs
params: {
param1: 'value1',
param2: 'value2'
}
});
or using
uploader.setParams({
anotherParam: 'value'
});
if you want it to be aware of the state of your app/
subD="/Pic"
function selectGaleryName()
{
subD=subD+"/3"
alert(subD) // /Pic/3
}
var uploader = new qq.FileUploader({
element: document.getElementById('UploadFile'),
action: 'http://localhost/Farainform/manager/upload.php'
// additional data to send, name-value pairs
onComplete: function(id, fileName, responseJSON){
selectGaleryName();
uploader.setParams({
subDirectory : subD
});
},
});
if you want to set an id and a description for an image you can set these in javascript and then send these. So something like (im using jQuery here):
var description = $('#input_description').val(); //This can be an input
var id = $('#input_description').att('id');
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/server-side.upload',
// additional data to send, name-value pairs
params: {
description: description,
id: id
}
});
Note I havent tested this code and its for demonstration purposes.
$_GET was always destroyed in the 1.7.3 branch but upgrade to the new CodeIgniter Reactor 2.0 and you'll find that GET strings work out of the box.
When upgraded, use this syntax:
$this->input->get('value1');
I don't know why it is not documented on Valums page, but apparently parameters should be sent not like this
params: {
param1: 'value1',
param2: 'value2'}
But like this
data: {param1: 'value1',
param2: 'value2'}
On server side you could get them with $_REQUEST['param1'];
You have to use PHP's input stream in order to obtain the data.
$fp = fopen('php://input', 'r');
Then read the data as you normally would with a regular file using fread(). Refer to valum's server side code located in server/php.php within the download.
Two related issues that I ran into that might help someone out:
1) var uploader causes issues - try using something like ajaxuploader instead
2) the documented setParams is incorrect for the latest release - it should be setData
The end result should be something like this:
var ajaxuploader = new AjaxUpload(button, {
action: 'your-server-script.php',
name: 'myfile',
onSubmit : function(file, ext){
ajaxuploader.setData({
somevar : 'somevalue',
anothervar : 'anothervalue'
});
)};

Resources